babylon.max.js 3.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597
  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. BABYLON.ToGammaSpace = 1 / 2.2;
  20. BABYLON.ToLinearSpace = 2.2;
  21. BABYLON.Epsilon = 0.001;
  22. var Color3 = (function () {
  23. /**
  24. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  25. */
  26. function Color3(r, g, b) {
  27. if (r === void 0) { r = 0; }
  28. if (g === void 0) { g = 0; }
  29. if (b === void 0) { b = 0; }
  30. this.r = r;
  31. this.g = g;
  32. this.b = b;
  33. }
  34. /**
  35. * Returns a string with the Color3 current values.
  36. */
  37. Color3.prototype.toString = function () {
  38. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  39. };
  40. /**
  41. * Returns the string "Color3".
  42. */
  43. Color3.prototype.getClassName = function () {
  44. return "Color3";
  45. };
  46. /**
  47. * Returns the Color3 hash code.
  48. */
  49. Color3.prototype.getHashCode = function () {
  50. var hash = this.r || 0;
  51. hash = (hash * 397) ^ (this.g || 0);
  52. hash = (hash * 397) ^ (this.b || 0);
  53. return hash;
  54. };
  55. // Operators
  56. /**
  57. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  58. * Returns the Color3.
  59. */
  60. Color3.prototype.toArray = function (array, index) {
  61. if (index === undefined) {
  62. index = 0;
  63. }
  64. array[index] = this.r;
  65. array[index + 1] = this.g;
  66. array[index + 2] = this.b;
  67. return this;
  68. };
  69. /**
  70. * Returns a new Color4 object from the current Color3 and the passed alpha.
  71. */
  72. Color3.prototype.toColor4 = function (alpha) {
  73. if (alpha === void 0) { alpha = 1; }
  74. return new Color4(this.r, this.g, this.b, alpha);
  75. };
  76. /**
  77. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  78. */
  79. Color3.prototype.asArray = function () {
  80. var result = [];
  81. this.toArray(result, 0);
  82. return result;
  83. };
  84. /**
  85. * Returns the luminance value (float).
  86. */
  87. Color3.prototype.toLuminance = function () {
  88. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  89. };
  90. /**
  91. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  92. * Returns this new object.
  93. */
  94. Color3.prototype.multiply = function (otherColor) {
  95. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  96. };
  97. /**
  98. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  99. * Returns the current Color3.
  100. */
  101. Color3.prototype.multiplyToRef = function (otherColor, result) {
  102. result.r = this.r * otherColor.r;
  103. result.g = this.g * otherColor.g;
  104. result.b = this.b * otherColor.b;
  105. return this;
  106. };
  107. /**
  108. * Boolean : True if the rgb values are equal to the passed ones.
  109. */
  110. Color3.prototype.equals = function (otherColor) {
  111. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  112. };
  113. /**
  114. * Boolean : True if the rgb values are equal to the passed ones.
  115. */
  116. Color3.prototype.equalsFloats = function (r, g, b) {
  117. return this.r === r && this.g === g && this.b === b;
  118. };
  119. /**
  120. * Multiplies in place each rgb value by scale.
  121. * Returns the updated Color3.
  122. */
  123. Color3.prototype.scale = function (scale) {
  124. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  125. };
  126. /**
  127. * Multiplies the rgb values by scale and stores the result into "result".
  128. * Returns the unmodified current Color3.
  129. */
  130. Color3.prototype.scaleToRef = function (scale, result) {
  131. result.r = this.r * scale;
  132. result.g = this.g * scale;
  133. result.b = this.b * scale;
  134. return this;
  135. };
  136. /**
  137. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  138. */
  139. Color3.prototype.add = function (otherColor) {
  140. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  141. };
  142. /**
  143. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  144. * Returns the unmodified current Color3.
  145. */
  146. Color3.prototype.addToRef = function (otherColor, result) {
  147. result.r = this.r + otherColor.r;
  148. result.g = this.g + otherColor.g;
  149. result.b = this.b + otherColor.b;
  150. return this;
  151. };
  152. /**
  153. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  154. */
  155. Color3.prototype.subtract = function (otherColor) {
  156. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  157. };
  158. /**
  159. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  160. * Returns the unmodified current Color3.
  161. */
  162. Color3.prototype.subtractToRef = function (otherColor, result) {
  163. result.r = this.r - otherColor.r;
  164. result.g = this.g - otherColor.g;
  165. result.b = this.b - otherColor.b;
  166. return this;
  167. };
  168. /**
  169. * Returns a new Color3 copied the current one.
  170. */
  171. Color3.prototype.clone = function () {
  172. return new Color3(this.r, this.g, this.b);
  173. };
  174. /**
  175. * Copies the rgb values from the source in the current Color3.
  176. * Returns the updated Color3.
  177. */
  178. Color3.prototype.copyFrom = function (source) {
  179. this.r = source.r;
  180. this.g = source.g;
  181. this.b = source.b;
  182. return this;
  183. };
  184. /**
  185. * Updates the Color3 rgb values from the passed floats.
  186. * Returns the Color3.
  187. */
  188. Color3.prototype.copyFromFloats = function (r, g, b) {
  189. this.r = r;
  190. this.g = g;
  191. this.b = b;
  192. return this;
  193. };
  194. /**
  195. * Updates the Color3 rgb values from the passed floats.
  196. * Returns the Color3.
  197. */
  198. Color3.prototype.set = function (r, g, b) {
  199. return this.copyFromFloats(r, g, b);
  200. };
  201. /**
  202. * Returns the Color3 hexadecimal code as a string.
  203. */
  204. Color3.prototype.toHexString = function () {
  205. var intR = (this.r * 255) | 0;
  206. var intG = (this.g * 255) | 0;
  207. var intB = (this.b * 255) | 0;
  208. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  209. };
  210. /**
  211. * Returns a new Color3 converted to linear space.
  212. */
  213. Color3.prototype.toLinearSpace = function () {
  214. var convertedColor = new Color3();
  215. this.toLinearSpaceToRef(convertedColor);
  216. return convertedColor;
  217. };
  218. /**
  219. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  220. * Returns the unmodified Color3.
  221. */
  222. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  223. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  224. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  225. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  226. return this;
  227. };
  228. /**
  229. * Returns a new Color3 converted to gamma space.
  230. */
  231. Color3.prototype.toGammaSpace = function () {
  232. var convertedColor = new Color3();
  233. this.toGammaSpaceToRef(convertedColor);
  234. return convertedColor;
  235. };
  236. /**
  237. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  238. * Returns the unmodified Color3.
  239. */
  240. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  241. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  242. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  243. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  244. return this;
  245. };
  246. // Statics
  247. /**
  248. * Creates a new Color3 from the string containing valid hexadecimal values.
  249. */
  250. Color3.FromHexString = function (hex) {
  251. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  252. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  253. return new Color3(0, 0, 0);
  254. }
  255. var r = parseInt(hex.substring(1, 3), 16);
  256. var g = parseInt(hex.substring(3, 5), 16);
  257. var b = parseInt(hex.substring(5, 7), 16);
  258. return Color3.FromInts(r, g, b);
  259. };
  260. /**
  261. * Creates a new Vector3 from the startind index of the passed array.
  262. */
  263. Color3.FromArray = function (array, offset) {
  264. if (offset === void 0) { offset = 0; }
  265. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  266. };
  267. /**
  268. * Creates a new Color3 from integer values ( < 256).
  269. */
  270. Color3.FromInts = function (r, g, b) {
  271. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  272. };
  273. /**
  274. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  275. */
  276. Color3.Lerp = function (start, end, amount) {
  277. var r = start.r + ((end.r - start.r) * amount);
  278. var g = start.g + ((end.g - start.g) * amount);
  279. var b = start.b + ((end.b - start.b) * amount);
  280. return new Color3(r, g, b);
  281. };
  282. Color3.Red = function () { return new Color3(1, 0, 0); };
  283. Color3.Green = function () { return new Color3(0, 1, 0); };
  284. Color3.Blue = function () { return new Color3(0, 0, 1); };
  285. Color3.Black = function () { return new Color3(0, 0, 0); };
  286. Color3.White = function () { return new Color3(1, 1, 1); };
  287. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  288. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  289. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  290. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  291. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  292. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  293. return Color3;
  294. }());
  295. BABYLON.Color3 = Color3;
  296. var Color4 = (function () {
  297. /**
  298. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  299. */
  300. function Color4(r, g, b, a) {
  301. if (r === void 0) { r = 0; }
  302. if (g === void 0) { g = 0; }
  303. if (b === void 0) { b = 0; }
  304. if (a === void 0) { a = 1; }
  305. this.r = r;
  306. this.g = g;
  307. this.b = b;
  308. this.a = a;
  309. }
  310. // Operators
  311. /**
  312. * Adds in place the passed Color4 values to the current Color4.
  313. * Returns the updated Color4.
  314. */
  315. Color4.prototype.addInPlace = function (right) {
  316. this.r += right.r;
  317. this.g += right.g;
  318. this.b += right.b;
  319. this.a += right.a;
  320. return this;
  321. };
  322. /**
  323. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  324. */
  325. Color4.prototype.asArray = function () {
  326. var result = [];
  327. this.toArray(result, 0);
  328. return result;
  329. };
  330. /**
  331. * Stores from the starting index in the passed array the Color4 successive values.
  332. * Returns the Color4.
  333. */
  334. Color4.prototype.toArray = function (array, index) {
  335. if (index === undefined) {
  336. index = 0;
  337. }
  338. array[index] = this.r;
  339. array[index + 1] = this.g;
  340. array[index + 2] = this.b;
  341. array[index + 3] = this.a;
  342. return this;
  343. };
  344. /**
  345. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  346. */
  347. Color4.prototype.add = function (right) {
  348. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  349. };
  350. /**
  351. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  352. */
  353. Color4.prototype.subtract = function (right) {
  354. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  355. };
  356. /**
  357. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  358. * Returns the Color4.
  359. */
  360. Color4.prototype.subtractToRef = function (right, result) {
  361. result.r = this.r - right.r;
  362. result.g = this.g - right.g;
  363. result.b = this.b - right.b;
  364. result.a = this.a - right.a;
  365. return this;
  366. };
  367. /**
  368. * Creates a new Color4 with the current Color4 values multiplied by scale.
  369. */
  370. Color4.prototype.scale = function (scale) {
  371. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  372. };
  373. /**
  374. * Multiplies the current Color4 values by scale and stores the result in "result".
  375. * Returns the Color4.
  376. */
  377. Color4.prototype.scaleToRef = function (scale, result) {
  378. result.r = this.r * scale;
  379. result.g = this.g * scale;
  380. result.b = this.b * scale;
  381. result.a = this.a * scale;
  382. return this;
  383. };
  384. /**
  385. * Multipy an RGBA Color4 value by another and return a new Color4 object
  386. * @param color The Color4 (RGBA) value to multiply by
  387. * @returns A new Color4.
  388. */
  389. Color4.prototype.multiply = function (color) {
  390. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  391. };
  392. /**
  393. * Multipy an RGBA Color4 value by another and push the result in a reference value
  394. * @param color The Color4 (RGBA) value to multiply by
  395. * @param result The Color4 (RGBA) to fill the result in
  396. * @returns the result Color4.
  397. */
  398. Color4.prototype.multiplyToRef = function (color, result) {
  399. result.r = this.r * color.r;
  400. result.g = this.g * color.g;
  401. result.b = this.b * color.b;
  402. result.a = this.a * color.a;
  403. return result;
  404. };
  405. /**
  406. * Returns a string with the Color4 values.
  407. */
  408. Color4.prototype.toString = function () {
  409. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  410. };
  411. /**
  412. * Returns the string "Color4"
  413. */
  414. Color4.prototype.getClassName = function () {
  415. return "Color4";
  416. };
  417. /**
  418. * Return the Color4 hash code as a number.
  419. */
  420. Color4.prototype.getHashCode = function () {
  421. var hash = this.r || 0;
  422. hash = (hash * 397) ^ (this.g || 0);
  423. hash = (hash * 397) ^ (this.b || 0);
  424. hash = (hash * 397) ^ (this.a || 0);
  425. return hash;
  426. };
  427. /**
  428. * Creates a new Color4 copied from the current one.
  429. */
  430. Color4.prototype.clone = function () {
  431. return new Color4(this.r, this.g, this.b, this.a);
  432. };
  433. /**
  434. * Copies the passed Color4 values into the current one.
  435. * Returns the updated Color4.
  436. */
  437. Color4.prototype.copyFrom = function (source) {
  438. this.r = source.r;
  439. this.g = source.g;
  440. this.b = source.b;
  441. this.a = source.a;
  442. return this;
  443. };
  444. /**
  445. * Copies the passed float values into the current one.
  446. * Returns the updated Color4.
  447. */
  448. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  449. this.r = r;
  450. this.g = g;
  451. this.b = b;
  452. this.a = a;
  453. return this;
  454. };
  455. /**
  456. * Copies the passed float values into the current one.
  457. * Returns the updated Color4.
  458. */
  459. Color4.prototype.set = function (r, g, b, a) {
  460. return this.copyFromFloats(r, g, b, a);
  461. };
  462. /**
  463. * Returns a string containing the hexadecimal Color4 code.
  464. */
  465. Color4.prototype.toHexString = function () {
  466. var intR = (this.r * 255) | 0;
  467. var intG = (this.g * 255) | 0;
  468. var intB = (this.b * 255) | 0;
  469. var intA = (this.a * 255) | 0;
  470. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  471. };
  472. /**
  473. * Returns a new Color4 converted to linear space.
  474. */
  475. Color4.prototype.toLinearSpace = function () {
  476. var convertedColor = new Color4();
  477. this.toLinearSpaceToRef(convertedColor);
  478. return convertedColor;
  479. };
  480. /**
  481. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  482. * Returns the unmodified Color4.
  483. */
  484. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  485. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  486. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  487. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  488. convertedColor.a = this.a;
  489. return this;
  490. };
  491. /**
  492. * Returns a new Color4 converted to gamma space.
  493. */
  494. Color4.prototype.toGammaSpace = function () {
  495. var convertedColor = new Color4();
  496. this.toGammaSpaceToRef(convertedColor);
  497. return convertedColor;
  498. };
  499. /**
  500. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  501. * Returns the unmodified Color4.
  502. */
  503. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  504. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  505. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  506. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  507. convertedColor.a = this.a;
  508. return this;
  509. };
  510. // Statics
  511. /**
  512. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  513. */
  514. Color4.FromHexString = function (hex) {
  515. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  516. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  517. return new Color4(0.0, 0.0, 0.0, 0.0);
  518. }
  519. var r = parseInt(hex.substring(1, 3), 16);
  520. var g = parseInt(hex.substring(3, 5), 16);
  521. var b = parseInt(hex.substring(5, 7), 16);
  522. var a = parseInt(hex.substring(7, 9), 16);
  523. return Color4.FromInts(r, g, b, a);
  524. };
  525. /**
  526. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  527. */
  528. Color4.Lerp = function (left, right, amount) {
  529. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  530. Color4.LerpToRef(left, right, amount, result);
  531. return result;
  532. };
  533. /**
  534. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  535. */
  536. Color4.LerpToRef = function (left, right, amount, result) {
  537. result.r = left.r + (right.r - left.r) * amount;
  538. result.g = left.g + (right.g - left.g) * amount;
  539. result.b = left.b + (right.b - left.b) * amount;
  540. result.a = left.a + (right.a - left.a) * amount;
  541. };
  542. /**
  543. * Creates a new Color4 from the starting index element of the passed array.
  544. */
  545. Color4.FromArray = function (array, offset) {
  546. if (offset === void 0) { offset = 0; }
  547. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  548. };
  549. /**
  550. * Creates a new Color4 from the passed integers ( < 256 ).
  551. */
  552. Color4.FromInts = function (r, g, b, a) {
  553. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  554. };
  555. Color4.CheckColors4 = function (colors, count) {
  556. // Check if color3 was used
  557. if (colors.length === count * 3) {
  558. var colors4 = [];
  559. for (var index = 0; index < colors.length; index += 3) {
  560. var newIndex = (index / 3) * 4;
  561. colors4[newIndex] = colors[index];
  562. colors4[newIndex + 1] = colors[index + 1];
  563. colors4[newIndex + 2] = colors[index + 2];
  564. colors4[newIndex + 3] = 1.0;
  565. }
  566. return colors4;
  567. }
  568. return colors;
  569. };
  570. return Color4;
  571. }());
  572. BABYLON.Color4 = Color4;
  573. var Vector2 = (function () {
  574. /**
  575. * Creates a new Vector2 from the passed x and y coordinates.
  576. */
  577. function Vector2(x, y) {
  578. this.x = x;
  579. this.y = y;
  580. }
  581. /**
  582. * Returns a string with the Vector2 coordinates.
  583. */
  584. Vector2.prototype.toString = function () {
  585. return "{X: " + this.x + " Y:" + this.y + "}";
  586. };
  587. /**
  588. * Returns the string "Vector2"
  589. */
  590. Vector2.prototype.getClassName = function () {
  591. return "Vector2";
  592. };
  593. /**
  594. * Returns the Vector2 hash code as a number.
  595. */
  596. Vector2.prototype.getHashCode = function () {
  597. var hash = this.x || 0;
  598. hash = (hash * 397) ^ (this.y || 0);
  599. return hash;
  600. };
  601. // Operators
  602. /**
  603. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  604. * Returns the Vector2.
  605. */
  606. Vector2.prototype.toArray = function (array, index) {
  607. if (index === void 0) { index = 0; }
  608. array[index] = this.x;
  609. array[index + 1] = this.y;
  610. return this;
  611. };
  612. /**
  613. * Returns a new array with 2 elements : the Vector2 coordinates.
  614. */
  615. Vector2.prototype.asArray = function () {
  616. var result = [];
  617. this.toArray(result, 0);
  618. return result;
  619. };
  620. /**
  621. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  622. * Returns the updated Vector2.
  623. */
  624. Vector2.prototype.copyFrom = function (source) {
  625. this.x = source.x;
  626. this.y = source.y;
  627. return this;
  628. };
  629. /**
  630. * Sets the Vector2 coordinates with the passed floats.
  631. * Returns the updated Vector2.
  632. */
  633. Vector2.prototype.copyFromFloats = function (x, y) {
  634. this.x = x;
  635. this.y = y;
  636. return this;
  637. };
  638. /**
  639. * Sets the Vector2 coordinates with the passed floats.
  640. * Returns the updated Vector2.
  641. */
  642. Vector2.prototype.set = function (x, y) {
  643. return this.copyFromFloats(x, y);
  644. };
  645. /**
  646. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  647. */
  648. Vector2.prototype.add = function (otherVector) {
  649. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  650. };
  651. /**
  652. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  653. * Returns the Vector2.
  654. */
  655. Vector2.prototype.addToRef = function (otherVector, result) {
  656. result.x = this.x + otherVector.x;
  657. result.y = this.y + otherVector.y;
  658. return this;
  659. };
  660. /**
  661. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  662. * Returns the updated Vector2.
  663. */
  664. Vector2.prototype.addInPlace = function (otherVector) {
  665. this.x += otherVector.x;
  666. this.y += otherVector.y;
  667. return this;
  668. };
  669. /**
  670. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  671. */
  672. Vector2.prototype.addVector3 = function (otherVector) {
  673. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  674. };
  675. /**
  676. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  677. */
  678. Vector2.prototype.subtract = function (otherVector) {
  679. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  680. };
  681. /**
  682. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  683. * Returns the Vector2.
  684. */
  685. Vector2.prototype.subtractToRef = function (otherVector, result) {
  686. result.x = this.x - otherVector.x;
  687. result.y = this.y - otherVector.y;
  688. return this;
  689. };
  690. /**
  691. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  692. * Returns the updated Vector2.
  693. */
  694. Vector2.prototype.subtractInPlace = function (otherVector) {
  695. this.x -= otherVector.x;
  696. this.y -= otherVector.y;
  697. return this;
  698. };
  699. /**
  700. * Multiplies in place the current Vector2 coordinates by the passed ones.
  701. * Returns the updated Vector2.
  702. */
  703. Vector2.prototype.multiplyInPlace = function (otherVector) {
  704. this.x *= otherVector.x;
  705. this.y *= otherVector.y;
  706. return this;
  707. };
  708. /**
  709. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  710. */
  711. Vector2.prototype.multiply = function (otherVector) {
  712. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  713. };
  714. /**
  715. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  716. * Returns the Vector2.
  717. */
  718. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  719. result.x = this.x * otherVector.x;
  720. result.y = this.y * otherVector.y;
  721. return this;
  722. };
  723. /**
  724. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  725. */
  726. Vector2.prototype.multiplyByFloats = function (x, y) {
  727. return new Vector2(this.x * x, this.y * y);
  728. };
  729. /**
  730. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  731. */
  732. Vector2.prototype.divide = function (otherVector) {
  733. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  734. };
  735. /**
  736. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  737. * Returns the Vector2.
  738. */
  739. Vector2.prototype.divideToRef = function (otherVector, result) {
  740. result.x = this.x / otherVector.x;
  741. result.y = this.y / otherVector.y;
  742. return this;
  743. };
  744. /**
  745. * Returns a new Vector2 with current Vector2 negated coordinates.
  746. */
  747. Vector2.prototype.negate = function () {
  748. return new Vector2(-this.x, -this.y);
  749. };
  750. /**
  751. * Multiply the Vector2 coordinates by scale.
  752. * Returns the updated Vector2.
  753. */
  754. Vector2.prototype.scaleInPlace = function (scale) {
  755. this.x *= scale;
  756. this.y *= scale;
  757. return this;
  758. };
  759. /**
  760. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  761. */
  762. Vector2.prototype.scale = function (scale) {
  763. return new Vector2(this.x * scale, this.y * scale);
  764. };
  765. /**
  766. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  767. */
  768. Vector2.prototype.equals = function (otherVector) {
  769. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  770. };
  771. /**
  772. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  773. */
  774. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  775. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  776. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  777. };
  778. // Properties
  779. /**
  780. * Returns the vector length (float).
  781. */
  782. Vector2.prototype.length = function () {
  783. return Math.sqrt(this.x * this.x + this.y * this.y);
  784. };
  785. /**
  786. * Returns the vector squared length (float);
  787. */
  788. Vector2.prototype.lengthSquared = function () {
  789. return (this.x * this.x + this.y * this.y);
  790. };
  791. // Methods
  792. /**
  793. * Normalize the vector.
  794. * Returns the updated Vector2.
  795. */
  796. Vector2.prototype.normalize = function () {
  797. var len = this.length();
  798. if (len === 0)
  799. return this;
  800. var num = 1.0 / len;
  801. this.x *= num;
  802. this.y *= num;
  803. return this;
  804. };
  805. /**
  806. * Returns a new Vector2 copied from the Vector2.
  807. */
  808. Vector2.prototype.clone = function () {
  809. return new Vector2(this.x, this.y);
  810. };
  811. // Statics
  812. /**
  813. * Returns a new Vector2(0, 0)
  814. */
  815. Vector2.Zero = function () {
  816. return new Vector2(0, 0);
  817. };
  818. /**
  819. * Returns a new Vector2(1, 1)
  820. */
  821. Vector2.One = function () {
  822. return new Vector2(1, 1);
  823. };
  824. /**
  825. * Returns a new Vector2 set from the passed index element of the passed array.
  826. */
  827. Vector2.FromArray = function (array, offset) {
  828. if (offset === void 0) { offset = 0; }
  829. return new Vector2(array[offset], array[offset + 1]);
  830. };
  831. /**
  832. * Sets "result" from the passed index element of the passed array.
  833. */
  834. Vector2.FromArrayToRef = function (array, offset, result) {
  835. result.x = array[offset];
  836. result.y = array[offset + 1];
  837. };
  838. /**
  839. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  840. */
  841. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  842. var squared = amount * amount;
  843. var cubed = amount * squared;
  844. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  845. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  846. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  847. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  848. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  849. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  850. return new Vector2(x, y);
  851. };
  852. /**
  853. * 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".
  854. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  855. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  856. */
  857. Vector2.Clamp = function (value, min, max) {
  858. var x = value.x;
  859. x = (x > max.x) ? max.x : x;
  860. x = (x < min.x) ? min.x : x;
  861. var y = value.y;
  862. y = (y > max.y) ? max.y : y;
  863. y = (y < min.y) ? min.y : y;
  864. return new Vector2(x, y);
  865. };
  866. /**
  867. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  868. */
  869. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  870. var squared = amount * amount;
  871. var cubed = amount * squared;
  872. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  873. var part2 = (-2.0 * cubed) + (3.0 * squared);
  874. var part3 = (cubed - (2.0 * squared)) + amount;
  875. var part4 = cubed - squared;
  876. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  877. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  878. return new Vector2(x, y);
  879. };
  880. /**
  881. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  882. */
  883. Vector2.Lerp = function (start, end, amount) {
  884. var x = start.x + ((end.x - start.x) * amount);
  885. var y = start.y + ((end.y - start.y) * amount);
  886. return new Vector2(x, y);
  887. };
  888. /**
  889. * Returns the dot product (float) of the vector "left" and the vector "right".
  890. */
  891. Vector2.Dot = function (left, right) {
  892. return left.x * right.x + left.y * right.y;
  893. };
  894. /**
  895. * Returns a new Vector2 equal to the normalized passed vector.
  896. */
  897. Vector2.Normalize = function (vector) {
  898. var newVector = vector.clone();
  899. newVector.normalize();
  900. return newVector;
  901. };
  902. /**
  903. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  904. */
  905. Vector2.Minimize = function (left, right) {
  906. var x = (left.x < right.x) ? left.x : right.x;
  907. var y = (left.y < right.y) ? left.y : right.y;
  908. return new Vector2(x, y);
  909. };
  910. /**
  911. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  912. */
  913. Vector2.Maximize = function (left, right) {
  914. var x = (left.x > right.x) ? left.x : right.x;
  915. var y = (left.y > right.y) ? left.y : right.y;
  916. return new Vector2(x, y);
  917. };
  918. /**
  919. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  920. */
  921. Vector2.Transform = function (vector, transformation) {
  922. var r = Vector2.Zero();
  923. Vector2.TransformToRef(vector, transformation, r);
  924. return r;
  925. };
  926. /**
  927. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  928. */
  929. Vector2.TransformToRef = function (vector, transformation, result) {
  930. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  931. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  932. result.x = x;
  933. result.y = y;
  934. };
  935. /**
  936. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  937. */
  938. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  939. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  940. var sign = a < 0 ? -1 : 1;
  941. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  942. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  943. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  944. };
  945. /**
  946. * Returns the distance (float) between the vectors "value1" and "value2".
  947. */
  948. Vector2.Distance = function (value1, value2) {
  949. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  950. };
  951. /**
  952. * Returns the squared distance (float) between the vectors "value1" and "value2".
  953. */
  954. Vector2.DistanceSquared = function (value1, value2) {
  955. var x = value1.x - value2.x;
  956. var y = value1.y - value2.y;
  957. return (x * x) + (y * y);
  958. };
  959. /**
  960. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  961. */
  962. Vector2.Center = function (value1, value2) {
  963. var center = value1.add(value2);
  964. center.scaleInPlace(0.5);
  965. return center;
  966. };
  967. /**
  968. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  969. */
  970. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  971. var l2 = Vector2.DistanceSquared(segA, segB);
  972. if (l2 === 0.0) {
  973. return Vector2.Distance(p, segA);
  974. }
  975. var v = segB.subtract(segA);
  976. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  977. var proj = segA.add(v.multiplyByFloats(t, t));
  978. return Vector2.Distance(p, proj);
  979. };
  980. return Vector2;
  981. }());
  982. BABYLON.Vector2 = Vector2;
  983. var Vector3 = (function () {
  984. /**
  985. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  986. * A Vector3 is the main object used in 3D geometry.
  987. * It can represent etiher the coordinates of a point the space, either a direction.
  988. */
  989. function Vector3(x, y, z) {
  990. this.x = x;
  991. this.y = y;
  992. this.z = z;
  993. }
  994. /**
  995. * Returns a string with the Vector3 coordinates.
  996. */
  997. Vector3.prototype.toString = function () {
  998. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  999. };
  1000. /**
  1001. * Returns the string "Vector3"
  1002. */
  1003. Vector3.prototype.getClassName = function () {
  1004. return "Vector3";
  1005. };
  1006. /**
  1007. * Returns the Vector hash code.
  1008. */
  1009. Vector3.prototype.getHashCode = function () {
  1010. var hash = this.x || 0;
  1011. hash = (hash * 397) ^ (this.y || 0);
  1012. hash = (hash * 397) ^ (this.z || 0);
  1013. return hash;
  1014. };
  1015. // Operators
  1016. /**
  1017. * Returns a new array with three elements : the coordinates the Vector3.
  1018. */
  1019. Vector3.prototype.asArray = function () {
  1020. var result = [];
  1021. this.toArray(result, 0);
  1022. return result;
  1023. };
  1024. /**
  1025. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1026. * Returns the Vector3.
  1027. */
  1028. Vector3.prototype.toArray = function (array, index) {
  1029. if (index === void 0) { index = 0; }
  1030. array[index] = this.x;
  1031. array[index + 1] = this.y;
  1032. array[index + 2] = this.z;
  1033. return this;
  1034. };
  1035. /**
  1036. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1037. */
  1038. Vector3.prototype.toQuaternion = function () {
  1039. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1040. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1041. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1042. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1043. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1044. var cosy = Math.cos(this.y * 0.5);
  1045. var siny = Math.sin(this.y * 0.5);
  1046. result.x = coszMinusx * siny;
  1047. result.y = -sinzMinusx * siny;
  1048. result.z = sinxPlusz * cosy;
  1049. result.w = cosxPlusz * cosy;
  1050. return result;
  1051. };
  1052. /**
  1053. * Adds the passed vector to the current Vector3.
  1054. * Returns the updated Vector3.
  1055. */
  1056. Vector3.prototype.addInPlace = function (otherVector) {
  1057. this.x += otherVector.x;
  1058. this.y += otherVector.y;
  1059. this.z += otherVector.z;
  1060. return this;
  1061. };
  1062. /**
  1063. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1064. */
  1065. Vector3.prototype.add = function (otherVector) {
  1066. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1067. };
  1068. /**
  1069. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1070. * Returns the current Vector3.
  1071. */
  1072. Vector3.prototype.addToRef = function (otherVector, result) {
  1073. result.x = this.x + otherVector.x;
  1074. result.y = this.y + otherVector.y;
  1075. result.z = this.z + otherVector.z;
  1076. return this;
  1077. };
  1078. /**
  1079. * Subtract the passed vector from the current Vector3.
  1080. * Returns the updated Vector3.
  1081. */
  1082. Vector3.prototype.subtractInPlace = function (otherVector) {
  1083. this.x -= otherVector.x;
  1084. this.y -= otherVector.y;
  1085. this.z -= otherVector.z;
  1086. return this;
  1087. };
  1088. /**
  1089. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1090. */
  1091. Vector3.prototype.subtract = function (otherVector) {
  1092. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1093. };
  1094. /**
  1095. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1096. * Returns the current Vector3.
  1097. */
  1098. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1099. result.x = this.x - otherVector.x;
  1100. result.y = this.y - otherVector.y;
  1101. result.z = this.z - otherVector.z;
  1102. return this;
  1103. };
  1104. /**
  1105. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1106. */
  1107. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1108. return new Vector3(this.x - x, this.y - y, this.z - z);
  1109. };
  1110. /**
  1111. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1112. * Returns the current Vector3.
  1113. */
  1114. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1115. result.x = this.x - x;
  1116. result.y = this.y - y;
  1117. result.z = this.z - z;
  1118. return this;
  1119. };
  1120. /**
  1121. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1122. */
  1123. Vector3.prototype.negate = function () {
  1124. return new Vector3(-this.x, -this.y, -this.z);
  1125. };
  1126. /**
  1127. * Multiplies the Vector3 coordinates by the float "scale".
  1128. * Returns the updated Vector3.
  1129. */
  1130. Vector3.prototype.scaleInPlace = function (scale) {
  1131. this.x *= scale;
  1132. this.y *= scale;
  1133. this.z *= scale;
  1134. return this;
  1135. };
  1136. /**
  1137. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1138. */
  1139. Vector3.prototype.scale = function (scale) {
  1140. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1141. };
  1142. /**
  1143. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1144. * Returns the current Vector3.
  1145. */
  1146. Vector3.prototype.scaleToRef = function (scale, result) {
  1147. result.x = this.x * scale;
  1148. result.y = this.y * scale;
  1149. result.z = this.z * scale;
  1150. return this;
  1151. };
  1152. /**
  1153. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1154. */
  1155. Vector3.prototype.equals = function (otherVector) {
  1156. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1157. };
  1158. /**
  1159. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1160. */
  1161. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1162. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1163. 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);
  1164. };
  1165. /**
  1166. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1167. */
  1168. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1169. return this.x === x && this.y === y && this.z === z;
  1170. };
  1171. /**
  1172. * Muliplies the current Vector3 coordinates by the passed ones.
  1173. * Returns the updated Vector3.
  1174. */
  1175. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1176. this.x *= otherVector.x;
  1177. this.y *= otherVector.y;
  1178. this.z *= otherVector.z;
  1179. return this;
  1180. };
  1181. /**
  1182. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1183. */
  1184. Vector3.prototype.multiply = function (otherVector) {
  1185. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1186. };
  1187. /**
  1188. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1189. * Returns the current Vector3.
  1190. */
  1191. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1192. result.x = this.x * otherVector.x;
  1193. result.y = this.y * otherVector.y;
  1194. result.z = this.z * otherVector.z;
  1195. return this;
  1196. };
  1197. /**
  1198. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1199. */
  1200. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1201. return new Vector3(this.x * x, this.y * y, this.z * z);
  1202. };
  1203. /**
  1204. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1205. */
  1206. Vector3.prototype.divide = function (otherVector) {
  1207. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1208. };
  1209. /**
  1210. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1211. * Returns the current Vector3.
  1212. */
  1213. Vector3.prototype.divideToRef = function (otherVector, result) {
  1214. result.x = this.x / otherVector.x;
  1215. result.y = this.y / otherVector.y;
  1216. result.z = this.z / otherVector.z;
  1217. return this;
  1218. };
  1219. /**
  1220. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1221. * Returns the updated Vector3.
  1222. */
  1223. Vector3.prototype.MinimizeInPlace = function (other) {
  1224. if (other.x < this.x)
  1225. this.x = other.x;
  1226. if (other.y < this.y)
  1227. this.y = other.y;
  1228. if (other.z < this.z)
  1229. this.z = other.z;
  1230. return this;
  1231. };
  1232. /**
  1233. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1234. * Returns the updated Vector3.
  1235. */
  1236. Vector3.prototype.MaximizeInPlace = function (other) {
  1237. if (other.x > this.x)
  1238. this.x = other.x;
  1239. if (other.y > this.y)
  1240. this.y = other.y;
  1241. if (other.z > this.z)
  1242. this.z = other.z;
  1243. return this;
  1244. };
  1245. // Properties
  1246. /**
  1247. * Returns the length of the Vector3 (float).
  1248. */
  1249. Vector3.prototype.length = function () {
  1250. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1251. };
  1252. /**
  1253. * Returns the squared length of the Vector3 (float).
  1254. */
  1255. Vector3.prototype.lengthSquared = function () {
  1256. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1257. };
  1258. // Methods
  1259. /**
  1260. * Normalize the current Vector3.
  1261. * Returns the updated Vector3.
  1262. */
  1263. Vector3.prototype.normalize = function () {
  1264. var len = this.length();
  1265. if (len === 0 || len === 1.0)
  1266. return this;
  1267. var num = 1.0 / len;
  1268. this.x *= num;
  1269. this.y *= num;
  1270. this.z *= num;
  1271. return this;
  1272. };
  1273. /**
  1274. * Returns a new Vector3 copied from the current Vector3.
  1275. */
  1276. Vector3.prototype.clone = function () {
  1277. return new Vector3(this.x, this.y, this.z);
  1278. };
  1279. /**
  1280. * Copies the passed vector coordinates to the current Vector3 ones.
  1281. * Returns the updated Vector3.
  1282. */
  1283. Vector3.prototype.copyFrom = function (source) {
  1284. this.x = source.x;
  1285. this.y = source.y;
  1286. this.z = source.z;
  1287. return this;
  1288. };
  1289. /**
  1290. * Copies the passed floats to the current Vector3 coordinates.
  1291. * Returns the updated Vector3.
  1292. */
  1293. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1294. this.x = x;
  1295. this.y = y;
  1296. this.z = z;
  1297. return this;
  1298. };
  1299. /**
  1300. * Copies the passed floats to the current Vector3 coordinates.
  1301. * Returns the updated Vector3.
  1302. */
  1303. Vector3.prototype.set = function (x, y, z) {
  1304. return this.copyFromFloats(x, y, z);
  1305. };
  1306. // Statics
  1307. /**
  1308. *
  1309. */
  1310. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1311. var d0 = Vector3.Dot(vector0, axis) - size;
  1312. var d1 = Vector3.Dot(vector1, axis) - size;
  1313. var s = d0 / (d0 - d1);
  1314. return s;
  1315. };
  1316. /**
  1317. * Returns a new Vector3 set from the index "offset" of the passed array.
  1318. */
  1319. Vector3.FromArray = function (array, offset) {
  1320. if (!offset) {
  1321. offset = 0;
  1322. }
  1323. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1324. };
  1325. /**
  1326. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1327. * This function is deprecated. Use FromArray instead.
  1328. */
  1329. Vector3.FromFloatArray = function (array, offset) {
  1330. return Vector3.FromArray(array, offset);
  1331. };
  1332. /**
  1333. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1334. */
  1335. Vector3.FromArrayToRef = function (array, offset, result) {
  1336. result.x = array[offset];
  1337. result.y = array[offset + 1];
  1338. result.z = array[offset + 2];
  1339. };
  1340. /**
  1341. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1342. * This function is deprecated. Use FromArrayToRef instead.
  1343. */
  1344. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1345. return Vector3.FromArrayToRef(array, offset, result);
  1346. };
  1347. /**
  1348. * Sets the passed vector "result" with the passed floats.
  1349. */
  1350. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1351. result.x = x;
  1352. result.y = y;
  1353. result.z = z;
  1354. };
  1355. /**
  1356. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1357. */
  1358. Vector3.Zero = function () {
  1359. return new Vector3(0.0, 0.0, 0.0);
  1360. };
  1361. /**
  1362. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  1363. */
  1364. Vector3.One = function () {
  1365. return new Vector3(1.0, 1.0, 1.0);
  1366. };
  1367. /**
  1368. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1369. */
  1370. Vector3.Up = function () {
  1371. return new Vector3(0.0, 1.0, 0.0);
  1372. };
  1373. /**
  1374. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1375. */
  1376. Vector3.Forward = function () {
  1377. return new Vector3(0.0, 0.0, 1.0);
  1378. };
  1379. /**
  1380. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1381. */
  1382. Vector3.Right = function () {
  1383. return new Vector3(1.0, 0.0, 0.0);
  1384. };
  1385. /**
  1386. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1387. */
  1388. Vector3.Left = function () {
  1389. return new Vector3(-1.0, 0.0, 0.0);
  1390. };
  1391. /**
  1392. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1393. * This method computes tranformed coordinates only, not transformed direction vectors.
  1394. */
  1395. Vector3.TransformCoordinates = function (vector, transformation) {
  1396. var result = Vector3.Zero();
  1397. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1398. return result;
  1399. };
  1400. /**
  1401. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1402. * This method computes tranformed coordinates only, not transformed direction vectors.
  1403. */
  1404. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1405. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1406. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1407. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1408. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1409. result.x = x / w;
  1410. result.y = y / w;
  1411. result.z = z / w;
  1412. };
  1413. /**
  1414. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1415. * This method computes tranformed coordinates only, not transformed direction vectors.
  1416. */
  1417. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1418. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1419. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1420. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1421. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1422. result.x = rx / rw;
  1423. result.y = ry / rw;
  1424. result.z = rz / rw;
  1425. };
  1426. /**
  1427. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1428. * This methods computes transformed normalized direction vectors only.
  1429. */
  1430. Vector3.TransformNormal = function (vector, transformation) {
  1431. var result = Vector3.Zero();
  1432. Vector3.TransformNormalToRef(vector, transformation, result);
  1433. return result;
  1434. };
  1435. /**
  1436. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1437. * This methods computes transformed normalized direction vectors only.
  1438. */
  1439. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1440. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1441. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1442. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1443. result.x = x;
  1444. result.y = y;
  1445. result.z = z;
  1446. };
  1447. /**
  1448. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1449. * This methods computes transformed normalized direction vectors only.
  1450. */
  1451. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1452. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1453. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1454. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1455. };
  1456. /**
  1457. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1458. */
  1459. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1460. var squared = amount * amount;
  1461. var cubed = amount * squared;
  1462. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1463. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1464. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1465. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1466. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1467. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1468. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1469. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1470. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1471. return new Vector3(x, y, z);
  1472. };
  1473. /**
  1474. * 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".
  1475. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1476. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1477. */
  1478. Vector3.Clamp = function (value, min, max) {
  1479. var x = value.x;
  1480. x = (x > max.x) ? max.x : x;
  1481. x = (x < min.x) ? min.x : x;
  1482. var y = value.y;
  1483. y = (y > max.y) ? max.y : y;
  1484. y = (y < min.y) ? min.y : y;
  1485. var z = value.z;
  1486. z = (z > max.z) ? max.z : z;
  1487. z = (z < min.z) ? min.z : z;
  1488. return new Vector3(x, y, z);
  1489. };
  1490. /**
  1491. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1492. */
  1493. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1494. var squared = amount * amount;
  1495. var cubed = amount * squared;
  1496. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1497. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1498. var part3 = (cubed - (2.0 * squared)) + amount;
  1499. var part4 = cubed - squared;
  1500. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1501. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1502. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1503. return new Vector3(x, y, z);
  1504. };
  1505. /**
  1506. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1507. */
  1508. Vector3.Lerp = function (start, end, amount) {
  1509. var result = new Vector3(0, 0, 0);
  1510. Vector3.LerpToRef(start, end, amount, result);
  1511. return result;
  1512. };
  1513. /**
  1514. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1515. */
  1516. Vector3.LerpToRef = function (start, end, amount, result) {
  1517. result.x = start.x + ((end.x - start.x) * amount);
  1518. result.y = start.y + ((end.y - start.y) * amount);
  1519. result.z = start.z + ((end.z - start.z) * amount);
  1520. };
  1521. /**
  1522. * Returns the dot product (float) between the vectors "left" and "right".
  1523. */
  1524. Vector3.Dot = function (left, right) {
  1525. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1526. };
  1527. /**
  1528. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1529. * The cross product is then orthogonal to both "left" and "right".
  1530. */
  1531. Vector3.Cross = function (left, right) {
  1532. var result = Vector3.Zero();
  1533. Vector3.CrossToRef(left, right, result);
  1534. return result;
  1535. };
  1536. /**
  1537. * Sets the passed vector "result" with the cross product of "left" and "right".
  1538. * The cross product is then orthogonal to both "left" and "right".
  1539. */
  1540. Vector3.CrossToRef = function (left, right, result) {
  1541. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1542. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1543. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1544. result.copyFrom(MathTmp.Vector3[0]);
  1545. };
  1546. /**
  1547. * Returns a new Vector3 as the normalization of the passed vector.
  1548. */
  1549. Vector3.Normalize = function (vector) {
  1550. var result = Vector3.Zero();
  1551. Vector3.NormalizeToRef(vector, result);
  1552. return result;
  1553. };
  1554. /**
  1555. * Sets the passed vector "result" with the normalization of the passed first vector.
  1556. */
  1557. Vector3.NormalizeToRef = function (vector, result) {
  1558. result.copyFrom(vector);
  1559. result.normalize();
  1560. };
  1561. Vector3.Project = function (vector, world, transform, viewport) {
  1562. var cw = viewport.width;
  1563. var ch = viewport.height;
  1564. var cx = viewport.x;
  1565. var cy = viewport.y;
  1566. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1567. 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);
  1568. var matrix = MathTmp.Matrix[0];
  1569. world.multiplyToRef(transform, matrix);
  1570. matrix.multiplyToRef(viewportMatrix, matrix);
  1571. return Vector3.TransformCoordinates(vector, matrix);
  1572. };
  1573. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1574. var matrix = MathTmp.Matrix[0];
  1575. world.multiplyToRef(transform, matrix);
  1576. matrix.invert();
  1577. source.x = source.x / viewportWidth * 2 - 1;
  1578. source.y = -(source.y / viewportHeight * 2 - 1);
  1579. var vector = Vector3.TransformCoordinates(source, matrix);
  1580. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1581. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1582. vector = vector.scale(1.0 / num);
  1583. }
  1584. return vector;
  1585. };
  1586. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1587. var matrix = MathTmp.Matrix[0];
  1588. world.multiplyToRef(view, matrix);
  1589. matrix.multiplyToRef(projection, matrix);
  1590. matrix.invert();
  1591. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1592. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1593. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1594. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1595. vector = vector.scale(1.0 / num);
  1596. }
  1597. return vector;
  1598. };
  1599. Vector3.Minimize = function (left, right) {
  1600. var min = left.clone();
  1601. min.MinimizeInPlace(right);
  1602. return min;
  1603. };
  1604. Vector3.Maximize = function (left, right) {
  1605. var max = left.clone();
  1606. max.MaximizeInPlace(right);
  1607. return max;
  1608. };
  1609. /**
  1610. * Returns the distance (float) between the vectors "value1" and "value2".
  1611. */
  1612. Vector3.Distance = function (value1, value2) {
  1613. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1614. };
  1615. /**
  1616. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1617. */
  1618. Vector3.DistanceSquared = function (value1, value2) {
  1619. var x = value1.x - value2.x;
  1620. var y = value1.y - value2.y;
  1621. var z = value1.z - value2.z;
  1622. return (x * x) + (y * y) + (z * z);
  1623. };
  1624. /**
  1625. * Returns a new Vector3 located at the center between "value1" and "value2".
  1626. */
  1627. Vector3.Center = function (value1, value2) {
  1628. var center = value1.add(value2);
  1629. center.scaleInPlace(0.5);
  1630. return center;
  1631. };
  1632. /**
  1633. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1634. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1635. * to something in order to rotate it from its local system to the given target system.
  1636. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1637. * Returns a new Vector3.
  1638. */
  1639. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1640. var rotation = Vector3.Zero();
  1641. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1642. return rotation;
  1643. };
  1644. /**
  1645. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1646. */
  1647. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1648. var quat = MathTmp.Quaternion[0];
  1649. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1650. quat.toEulerAnglesToRef(ref);
  1651. };
  1652. return Vector3;
  1653. }());
  1654. BABYLON.Vector3 = Vector3;
  1655. //Vector4 class created for EulerAngle class conversion to Quaternion
  1656. var Vector4 = (function () {
  1657. /**
  1658. * Creates a Vector4 object from the passed floats.
  1659. */
  1660. function Vector4(x, y, z, w) {
  1661. this.x = x;
  1662. this.y = y;
  1663. this.z = z;
  1664. this.w = w;
  1665. }
  1666. /**
  1667. * Returns the string with the Vector4 coordinates.
  1668. */
  1669. Vector4.prototype.toString = function () {
  1670. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1671. };
  1672. /**
  1673. * Returns the string "Vector4".
  1674. */
  1675. Vector4.prototype.getClassName = function () {
  1676. return "Vector4";
  1677. };
  1678. /**
  1679. * Returns the Vector4 hash code.
  1680. */
  1681. Vector4.prototype.getHashCode = function () {
  1682. var hash = this.x || 0;
  1683. hash = (hash * 397) ^ (this.y || 0);
  1684. hash = (hash * 397) ^ (this.z || 0);
  1685. hash = (hash * 397) ^ (this.w || 0);
  1686. return hash;
  1687. };
  1688. // Operators
  1689. /**
  1690. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1691. */
  1692. Vector4.prototype.asArray = function () {
  1693. var result = [];
  1694. this.toArray(result, 0);
  1695. return result;
  1696. };
  1697. /**
  1698. * Populates the passed array from the passed index with the Vector4 coordinates.
  1699. * Returns the Vector4.
  1700. */
  1701. Vector4.prototype.toArray = function (array, index) {
  1702. if (index === undefined) {
  1703. index = 0;
  1704. }
  1705. array[index] = this.x;
  1706. array[index + 1] = this.y;
  1707. array[index + 2] = this.z;
  1708. array[index + 3] = this.w;
  1709. return this;
  1710. };
  1711. /**
  1712. * Adds the passed vector to the current Vector4.
  1713. * Returns the updated Vector4.
  1714. */
  1715. Vector4.prototype.addInPlace = function (otherVector) {
  1716. this.x += otherVector.x;
  1717. this.y += otherVector.y;
  1718. this.z += otherVector.z;
  1719. this.w += otherVector.w;
  1720. return this;
  1721. };
  1722. /**
  1723. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1724. */
  1725. Vector4.prototype.add = function (otherVector) {
  1726. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1727. };
  1728. /**
  1729. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1730. * Returns the current Vector4.
  1731. */
  1732. Vector4.prototype.addToRef = function (otherVector, result) {
  1733. result.x = this.x + otherVector.x;
  1734. result.y = this.y + otherVector.y;
  1735. result.z = this.z + otherVector.z;
  1736. result.w = this.w + otherVector.w;
  1737. return this;
  1738. };
  1739. /**
  1740. * Subtract in place the passed vector from the current Vector4.
  1741. * Returns the updated Vector4.
  1742. */
  1743. Vector4.prototype.subtractInPlace = function (otherVector) {
  1744. this.x -= otherVector.x;
  1745. this.y -= otherVector.y;
  1746. this.z -= otherVector.z;
  1747. this.w -= otherVector.w;
  1748. return this;
  1749. };
  1750. /**
  1751. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1752. */
  1753. Vector4.prototype.subtract = function (otherVector) {
  1754. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1755. };
  1756. /**
  1757. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1758. * Returns the current Vector4.
  1759. */
  1760. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1761. result.x = this.x - otherVector.x;
  1762. result.y = this.y - otherVector.y;
  1763. result.z = this.z - otherVector.z;
  1764. result.w = this.w - otherVector.w;
  1765. return this;
  1766. };
  1767. /**
  1768. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1769. */
  1770. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1771. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1772. };
  1773. /**
  1774. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1775. * Returns the current Vector4.
  1776. */
  1777. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1778. result.x = this.x - x;
  1779. result.y = this.y - y;
  1780. result.z = this.z - z;
  1781. result.w = this.w - w;
  1782. return this;
  1783. };
  1784. /**
  1785. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1786. */
  1787. Vector4.prototype.negate = function () {
  1788. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1789. };
  1790. /**
  1791. * Multiplies the current Vector4 coordinates by scale (float).
  1792. * Returns the updated Vector4.
  1793. */
  1794. Vector4.prototype.scaleInPlace = function (scale) {
  1795. this.x *= scale;
  1796. this.y *= scale;
  1797. this.z *= scale;
  1798. this.w *= scale;
  1799. return this;
  1800. };
  1801. /**
  1802. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1803. */
  1804. Vector4.prototype.scale = function (scale) {
  1805. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1806. };
  1807. /**
  1808. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1809. * Returns the current Vector4.
  1810. */
  1811. Vector4.prototype.scaleToRef = function (scale, result) {
  1812. result.x = this.x * scale;
  1813. result.y = this.y * scale;
  1814. result.z = this.z * scale;
  1815. result.w = this.w * scale;
  1816. return this;
  1817. };
  1818. /**
  1819. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1820. */
  1821. Vector4.prototype.equals = function (otherVector) {
  1822. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1823. };
  1824. /**
  1825. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1826. */
  1827. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1828. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1829. return otherVector
  1830. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  1831. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  1832. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  1833. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  1834. };
  1835. /**
  1836. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  1837. */
  1838. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1839. return this.x === x && this.y === y && this.z === z && this.w === w;
  1840. };
  1841. /**
  1842. * Multiplies in place the current Vector4 by the passed one.
  1843. * Returns the updated Vector4.
  1844. */
  1845. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1846. this.x *= otherVector.x;
  1847. this.y *= otherVector.y;
  1848. this.z *= otherVector.z;
  1849. this.w *= otherVector.w;
  1850. return this;
  1851. };
  1852. /**
  1853. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  1854. */
  1855. Vector4.prototype.multiply = function (otherVector) {
  1856. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1857. };
  1858. /**
  1859. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  1860. * Returns the current Vector4.
  1861. */
  1862. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1863. result.x = this.x * otherVector.x;
  1864. result.y = this.y * otherVector.y;
  1865. result.z = this.z * otherVector.z;
  1866. result.w = this.w * otherVector.w;
  1867. return this;
  1868. };
  1869. /**
  1870. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  1871. */
  1872. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1873. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1874. };
  1875. /**
  1876. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  1877. */
  1878. Vector4.prototype.divide = function (otherVector) {
  1879. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1880. };
  1881. /**
  1882. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  1883. * Returns the current Vector4.
  1884. */
  1885. Vector4.prototype.divideToRef = function (otherVector, result) {
  1886. result.x = this.x / otherVector.x;
  1887. result.y = this.y / otherVector.y;
  1888. result.z = this.z / otherVector.z;
  1889. result.w = this.w / otherVector.w;
  1890. return this;
  1891. };
  1892. /**
  1893. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  1894. */
  1895. Vector4.prototype.MinimizeInPlace = function (other) {
  1896. if (other.x < this.x)
  1897. this.x = other.x;
  1898. if (other.y < this.y)
  1899. this.y = other.y;
  1900. if (other.z < this.z)
  1901. this.z = other.z;
  1902. if (other.w < this.w)
  1903. this.w = other.w;
  1904. return this;
  1905. };
  1906. /**
  1907. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  1908. */
  1909. Vector4.prototype.MaximizeInPlace = function (other) {
  1910. if (other.x > this.x)
  1911. this.x = other.x;
  1912. if (other.y > this.y)
  1913. this.y = other.y;
  1914. if (other.z > this.z)
  1915. this.z = other.z;
  1916. if (other.w > this.w)
  1917. this.w = other.w;
  1918. return this;
  1919. };
  1920. // Properties
  1921. /**
  1922. * Returns the Vector4 length (float).
  1923. */
  1924. Vector4.prototype.length = function () {
  1925. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1926. };
  1927. /**
  1928. * Returns the Vector4 squared length (float).
  1929. */
  1930. Vector4.prototype.lengthSquared = function () {
  1931. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1932. };
  1933. // Methods
  1934. /**
  1935. * Normalizes in place the Vector4.
  1936. * Returns the updated Vector4.
  1937. */
  1938. Vector4.prototype.normalize = function () {
  1939. var len = this.length();
  1940. if (len === 0)
  1941. return this;
  1942. var num = 1.0 / len;
  1943. this.x *= num;
  1944. this.y *= num;
  1945. this.z *= num;
  1946. this.w *= num;
  1947. return this;
  1948. };
  1949. /**
  1950. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  1951. */
  1952. Vector4.prototype.toVector3 = function () {
  1953. return new Vector3(this.x, this.y, this.z);
  1954. };
  1955. /**
  1956. * Returns a new Vector4 copied from the current one.
  1957. */
  1958. Vector4.prototype.clone = function () {
  1959. return new Vector4(this.x, this.y, this.z, this.w);
  1960. };
  1961. /**
  1962. * Updates the current Vector4 with the passed one coordinates.
  1963. * Returns the updated Vector4.
  1964. */
  1965. Vector4.prototype.copyFrom = function (source) {
  1966. this.x = source.x;
  1967. this.y = source.y;
  1968. this.z = source.z;
  1969. this.w = source.w;
  1970. return this;
  1971. };
  1972. /**
  1973. * Updates the current Vector4 coordinates with the passed floats.
  1974. * Returns the updated Vector4.
  1975. */
  1976. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1977. this.x = x;
  1978. this.y = y;
  1979. this.z = z;
  1980. this.w = w;
  1981. return this;
  1982. };
  1983. /**
  1984. * Updates the current Vector4 coordinates with the passed floats.
  1985. * Returns the updated Vector4.
  1986. */
  1987. Vector4.prototype.set = function (x, y, z, w) {
  1988. return this.copyFromFloats(x, y, z, w);
  1989. };
  1990. // Statics
  1991. /**
  1992. * Returns a new Vector4 set from the starting index of the passed array.
  1993. */
  1994. Vector4.FromArray = function (array, offset) {
  1995. if (!offset) {
  1996. offset = 0;
  1997. }
  1998. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1999. };
  2000. /**
  2001. * Updates the passed vector "result" from the starting index of the passed array.
  2002. */
  2003. Vector4.FromArrayToRef = function (array, offset, result) {
  2004. result.x = array[offset];
  2005. result.y = array[offset + 1];
  2006. result.z = array[offset + 2];
  2007. result.w = array[offset + 3];
  2008. };
  2009. /**
  2010. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2011. */
  2012. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2013. Vector4.FromArrayToRef(array, offset, result);
  2014. };
  2015. /**
  2016. * Updates the passed vector "result" coordinates from the passed floats.
  2017. */
  2018. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2019. result.x = x;
  2020. result.y = y;
  2021. result.z = z;
  2022. result.w = w;
  2023. };
  2024. /**
  2025. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2026. */
  2027. Vector4.Zero = function () {
  2028. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2029. };
  2030. /**
  2031. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  2032. */
  2033. Vector4.One = function () {
  2034. return new Vector4(1.0, 1.0, 1.0, 1.0);
  2035. };
  2036. /**
  2037. * Returns a new normalized Vector4 from the passed one.
  2038. */
  2039. Vector4.Normalize = function (vector) {
  2040. var result = Vector4.Zero();
  2041. Vector4.NormalizeToRef(vector, result);
  2042. return result;
  2043. };
  2044. /**
  2045. * Updates the passed vector "result" from the normalization of the passed one.
  2046. */
  2047. Vector4.NormalizeToRef = function (vector, result) {
  2048. result.copyFrom(vector);
  2049. result.normalize();
  2050. };
  2051. Vector4.Minimize = function (left, right) {
  2052. var min = left.clone();
  2053. min.MinimizeInPlace(right);
  2054. return min;
  2055. };
  2056. Vector4.Maximize = function (left, right) {
  2057. var max = left.clone();
  2058. max.MaximizeInPlace(right);
  2059. return max;
  2060. };
  2061. /**
  2062. * Returns the distance (float) between the vectors "value1" and "value2".
  2063. */
  2064. Vector4.Distance = function (value1, value2) {
  2065. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2066. };
  2067. /**
  2068. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2069. */
  2070. Vector4.DistanceSquared = function (value1, value2) {
  2071. var x = value1.x - value2.x;
  2072. var y = value1.y - value2.y;
  2073. var z = value1.z - value2.z;
  2074. var w = value1.w - value2.w;
  2075. return (x * x) + (y * y) + (z * z) + (w * w);
  2076. };
  2077. /**
  2078. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2079. */
  2080. Vector4.Center = function (value1, value2) {
  2081. var center = value1.add(value2);
  2082. center.scaleInPlace(0.5);
  2083. return center;
  2084. };
  2085. /**
  2086. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2087. * This methods computes transformed normalized direction vectors only.
  2088. */
  2089. Vector4.TransformNormal = function (vector, transformation) {
  2090. var result = Vector4.Zero();
  2091. Vector4.TransformNormalToRef(vector, transformation, result);
  2092. return result;
  2093. };
  2094. /**
  2095. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2096. * This methods computes transformed normalized direction vectors only.
  2097. */
  2098. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2099. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2100. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2101. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2102. result.x = x;
  2103. result.y = y;
  2104. result.z = z;
  2105. result.w = vector.w;
  2106. };
  2107. /**
  2108. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2109. * This methods computes transformed normalized direction vectors only.
  2110. */
  2111. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2112. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2113. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2114. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2115. result.w = w;
  2116. };
  2117. return Vector4;
  2118. }());
  2119. BABYLON.Vector4 = Vector4;
  2120. var Size = (function () {
  2121. /**
  2122. * Creates a Size object from the passed width and height (floats).
  2123. */
  2124. function Size(width, height) {
  2125. this.width = width;
  2126. this.height = height;
  2127. }
  2128. // Returns a string with the Size width and height.
  2129. Size.prototype.toString = function () {
  2130. return "{W: " + this.width + ", H: " + this.height + "}";
  2131. };
  2132. /**
  2133. * Returns the string "Size"
  2134. */
  2135. Size.prototype.getClassName = function () {
  2136. return "Size";
  2137. };
  2138. /**
  2139. * Returns the Size hash code.
  2140. */
  2141. Size.prototype.getHashCode = function () {
  2142. var hash = this.width || 0;
  2143. hash = (hash * 397) ^ (this.height || 0);
  2144. return hash;
  2145. };
  2146. /**
  2147. * Updates the current size from the passed one.
  2148. * Returns the updated Size.
  2149. */
  2150. Size.prototype.copyFrom = function (src) {
  2151. this.width = src.width;
  2152. this.height = src.height;
  2153. };
  2154. /**
  2155. * Updates in place the current Size from the passed floats.
  2156. * Returns the updated Size.
  2157. */
  2158. Size.prototype.copyFromFloats = function (width, height) {
  2159. this.width = width;
  2160. this.height = height;
  2161. return this;
  2162. };
  2163. /**
  2164. * Updates in place the current Size from the passed floats.
  2165. * Returns the updated Size.
  2166. */
  2167. Size.prototype.set = function (width, height) {
  2168. return this.copyFromFloats(width, height);
  2169. };
  2170. /**
  2171. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2172. */
  2173. Size.prototype.multiplyByFloats = function (w, h) {
  2174. return new Size(this.width * w, this.height * h);
  2175. };
  2176. /**
  2177. * Returns a new Size copied from the passed one.
  2178. */
  2179. Size.prototype.clone = function () {
  2180. return new Size(this.width, this.height);
  2181. };
  2182. /**
  2183. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2184. */
  2185. Size.prototype.equals = function (other) {
  2186. if (!other) {
  2187. return false;
  2188. }
  2189. return (this.width === other.width) && (this.height === other.height);
  2190. };
  2191. Object.defineProperty(Size.prototype, "surface", {
  2192. /**
  2193. * Returns the surface of the Size : width * height (float).
  2194. */
  2195. get: function () {
  2196. return this.width * this.height;
  2197. },
  2198. enumerable: true,
  2199. configurable: true
  2200. });
  2201. /**
  2202. * Returns a new Size set to (0.0, 0.0)
  2203. */
  2204. Size.Zero = function () {
  2205. return new Size(0.0, 0.0);
  2206. };
  2207. /**
  2208. * Returns a new Size set as the addition result of the current Size and the passed one.
  2209. */
  2210. Size.prototype.add = function (otherSize) {
  2211. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2212. return r;
  2213. };
  2214. /**
  2215. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2216. */
  2217. Size.prototype.subtract = function (otherSize) {
  2218. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2219. return r;
  2220. };
  2221. /**
  2222. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2223. */
  2224. Size.Lerp = function (start, end, amount) {
  2225. var w = start.width + ((end.width - start.width) * amount);
  2226. var h = start.height + ((end.height - start.height) * amount);
  2227. return new Size(w, h);
  2228. };
  2229. return Size;
  2230. }());
  2231. BABYLON.Size = Size;
  2232. var Quaternion = (function () {
  2233. /**
  2234. * Creates a new Quaternion from the passed floats.
  2235. */
  2236. function Quaternion(x, y, z, w) {
  2237. if (x === void 0) { x = 0.0; }
  2238. if (y === void 0) { y = 0.0; }
  2239. if (z === void 0) { z = 0.0; }
  2240. if (w === void 0) { w = 1.0; }
  2241. this.x = x;
  2242. this.y = y;
  2243. this.z = z;
  2244. this.w = w;
  2245. }
  2246. /**
  2247. * Returns a string with the Quaternion coordinates.
  2248. */
  2249. Quaternion.prototype.toString = function () {
  2250. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2251. };
  2252. /**
  2253. * Returns the string "Quaternion".
  2254. */
  2255. Quaternion.prototype.getClassName = function () {
  2256. return "Quaternion";
  2257. };
  2258. /**
  2259. * Returns the Quaternion hash code.
  2260. */
  2261. Quaternion.prototype.getHashCode = function () {
  2262. var hash = this.x || 0;
  2263. hash = (hash * 397) ^ (this.y || 0);
  2264. hash = (hash * 397) ^ (this.z || 0);
  2265. hash = (hash * 397) ^ (this.w || 0);
  2266. return hash;
  2267. };
  2268. /**
  2269. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2270. */
  2271. Quaternion.prototype.asArray = function () {
  2272. return [this.x, this.y, this.z, this.w];
  2273. };
  2274. /**
  2275. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2276. */
  2277. Quaternion.prototype.equals = function (otherQuaternion) {
  2278. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2279. };
  2280. /**
  2281. * Returns a new Quaternion copied from the current one.
  2282. */
  2283. Quaternion.prototype.clone = function () {
  2284. return new Quaternion(this.x, this.y, this.z, this.w);
  2285. };
  2286. /**
  2287. * Updates the current Quaternion from the passed one coordinates.
  2288. * Returns the updated Quaterion.
  2289. */
  2290. Quaternion.prototype.copyFrom = function (other) {
  2291. this.x = other.x;
  2292. this.y = other.y;
  2293. this.z = other.z;
  2294. this.w = other.w;
  2295. return this;
  2296. };
  2297. /**
  2298. * Updates the current Quaternion from the passed float coordinates.
  2299. * Returns the updated Quaterion.
  2300. */
  2301. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2302. this.x = x;
  2303. this.y = y;
  2304. this.z = z;
  2305. this.w = w;
  2306. return this;
  2307. };
  2308. /**
  2309. * Updates the current Quaternion from the passed float coordinates.
  2310. * Returns the updated Quaterion.
  2311. */
  2312. Quaternion.prototype.set = function (x, y, z, w) {
  2313. return this.copyFromFloats(x, y, z, w);
  2314. };
  2315. /**
  2316. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2317. */
  2318. Quaternion.prototype.add = function (other) {
  2319. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2320. };
  2321. /**
  2322. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2323. */
  2324. Quaternion.prototype.subtract = function (other) {
  2325. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2326. };
  2327. /**
  2328. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2329. */
  2330. Quaternion.prototype.scale = function (value) {
  2331. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2332. };
  2333. /**
  2334. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2335. */
  2336. Quaternion.prototype.multiply = function (q1) {
  2337. var result = new Quaternion(0, 0, 0, 1.0);
  2338. this.multiplyToRef(q1, result);
  2339. return result;
  2340. };
  2341. /**
  2342. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2343. * Returns the current Quaternion.
  2344. */
  2345. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2346. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2347. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2348. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2349. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2350. result.copyFromFloats(x, y, z, w);
  2351. return this;
  2352. };
  2353. /**
  2354. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2355. * Returns the updated Quaternion.
  2356. */
  2357. Quaternion.prototype.multiplyInPlace = function (q1) {
  2358. this.multiplyToRef(q1, this);
  2359. return this;
  2360. };
  2361. /**
  2362. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2363. * Returns the current Quaternion.
  2364. */
  2365. Quaternion.prototype.conjugateToRef = function (ref) {
  2366. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2367. return this;
  2368. };
  2369. /**
  2370. * Conjugates in place the current Quaternion.
  2371. * Returns the updated Quaternion.
  2372. */
  2373. Quaternion.prototype.conjugateInPlace = function () {
  2374. this.x *= -1;
  2375. this.y *= -1;
  2376. this.z *= -1;
  2377. return this;
  2378. };
  2379. /**
  2380. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2381. */
  2382. Quaternion.prototype.conjugate = function () {
  2383. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2384. return result;
  2385. };
  2386. /**
  2387. * Returns the Quaternion length (float).
  2388. */
  2389. Quaternion.prototype.length = function () {
  2390. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2391. };
  2392. /**
  2393. * Normalize in place the current Quaternion.
  2394. * Returns the updated Quaternion.
  2395. */
  2396. Quaternion.prototype.normalize = function () {
  2397. var length = 1.0 / this.length();
  2398. this.x *= length;
  2399. this.y *= length;
  2400. this.z *= length;
  2401. this.w *= length;
  2402. return this;
  2403. };
  2404. /**
  2405. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2406. */
  2407. Quaternion.prototype.toEulerAngles = function (order) {
  2408. if (order === void 0) { order = "YZX"; }
  2409. var result = Vector3.Zero();
  2410. this.toEulerAnglesToRef(result, order);
  2411. return result;
  2412. };
  2413. /**
  2414. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2415. * Returns the current Quaternion.
  2416. */
  2417. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2418. if (order === void 0) { order = "YZX"; }
  2419. var qz = this.z;
  2420. var qx = this.x;
  2421. var qy = this.y;
  2422. var qw = this.w;
  2423. var sqw = qw * qw;
  2424. var sqz = qz * qz;
  2425. var sqx = qx * qx;
  2426. var sqy = qy * qy;
  2427. var zAxisY = qy * qz - qx * qw;
  2428. var limit = .4999999;
  2429. if (zAxisY < -limit) {
  2430. result.y = 2 * Math.atan2(qy, qw);
  2431. result.x = Math.PI / 2;
  2432. result.z = 0;
  2433. }
  2434. else if (zAxisY > limit) {
  2435. result.y = 2 * Math.atan2(qy, qw);
  2436. result.x = -Math.PI / 2;
  2437. result.z = 0;
  2438. }
  2439. else {
  2440. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2441. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2442. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2443. }
  2444. return this;
  2445. };
  2446. /**
  2447. * Updates the passed rotation matrix with the current Quaternion values.
  2448. * Returns the current Quaternion.
  2449. */
  2450. Quaternion.prototype.toRotationMatrix = function (result) {
  2451. var xx = this.x * this.x;
  2452. var yy = this.y * this.y;
  2453. var zz = this.z * this.z;
  2454. var xy = this.x * this.y;
  2455. var zw = this.z * this.w;
  2456. var zx = this.z * this.x;
  2457. var yw = this.y * this.w;
  2458. var yz = this.y * this.z;
  2459. var xw = this.x * this.w;
  2460. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2461. result.m[1] = 2.0 * (xy + zw);
  2462. result.m[2] = 2.0 * (zx - yw);
  2463. result.m[3] = 0;
  2464. result.m[4] = 2.0 * (xy - zw);
  2465. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2466. result.m[6] = 2.0 * (yz + xw);
  2467. result.m[7] = 0;
  2468. result.m[8] = 2.0 * (zx + yw);
  2469. result.m[9] = 2.0 * (yz - xw);
  2470. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2471. result.m[11] = 0;
  2472. result.m[12] = 0;
  2473. result.m[13] = 0;
  2474. result.m[14] = 0;
  2475. result.m[15] = 1.0;
  2476. result._markAsUpdated();
  2477. return this;
  2478. };
  2479. /**
  2480. * Updates the current Quaternion from the passed rotation matrix values.
  2481. * Returns the updated Quaternion.
  2482. */
  2483. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2484. Quaternion.FromRotationMatrixToRef(matrix, this);
  2485. return this;
  2486. };
  2487. // Statics
  2488. /**
  2489. * Returns a new Quaternion set from the passed rotation matrix values.
  2490. */
  2491. Quaternion.FromRotationMatrix = function (matrix) {
  2492. var result = new Quaternion();
  2493. Quaternion.FromRotationMatrixToRef(matrix, result);
  2494. return result;
  2495. };
  2496. /**
  2497. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2498. */
  2499. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2500. var data = matrix.m;
  2501. var m11 = data[0], m12 = data[4], m13 = data[8];
  2502. var m21 = data[1], m22 = data[5], m23 = data[9];
  2503. var m31 = data[2], m32 = data[6], m33 = data[10];
  2504. var trace = m11 + m22 + m33;
  2505. var s;
  2506. if (trace > 0) {
  2507. s = 0.5 / Math.sqrt(trace + 1.0);
  2508. result.w = 0.25 / s;
  2509. result.x = (m32 - m23) * s;
  2510. result.y = (m13 - m31) * s;
  2511. result.z = (m21 - m12) * s;
  2512. }
  2513. else if (m11 > m22 && m11 > m33) {
  2514. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2515. result.w = (m32 - m23) / s;
  2516. result.x = 0.25 * s;
  2517. result.y = (m12 + m21) / s;
  2518. result.z = (m13 + m31) / s;
  2519. }
  2520. else if (m22 > m33) {
  2521. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2522. result.w = (m13 - m31) / s;
  2523. result.x = (m12 + m21) / s;
  2524. result.y = 0.25 * s;
  2525. result.z = (m23 + m32) / s;
  2526. }
  2527. else {
  2528. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2529. result.w = (m21 - m12) / s;
  2530. result.x = (m13 + m31) / s;
  2531. result.y = (m23 + m32) / s;
  2532. result.z = 0.25 * s;
  2533. }
  2534. };
  2535. /**
  2536. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2537. */
  2538. Quaternion.Zero = function () {
  2539. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2540. };
  2541. /**
  2542. * Returns a new Quaternion as the inverted current Quaternion.
  2543. */
  2544. Quaternion.Inverse = function (q) {
  2545. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2546. };
  2547. /**
  2548. * Returns the identity Quaternion.
  2549. */
  2550. Quaternion.Identity = function () {
  2551. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2552. };
  2553. Quaternion.IsIdentity = function (quaternion) {
  2554. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2555. };
  2556. /**
  2557. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2558. */
  2559. Quaternion.RotationAxis = function (axis, angle) {
  2560. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2561. };
  2562. /**
  2563. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2564. */
  2565. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2566. var sin = Math.sin(angle / 2);
  2567. axis.normalize();
  2568. result.w = Math.cos(angle / 2);
  2569. result.x = axis.x * sin;
  2570. result.y = axis.y * sin;
  2571. result.z = axis.z * sin;
  2572. return result;
  2573. };
  2574. /**
  2575. * Retuns a new Quaternion set from the starting index of the passed array.
  2576. */
  2577. Quaternion.FromArray = function (array, offset) {
  2578. if (!offset) {
  2579. offset = 0;
  2580. }
  2581. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2582. };
  2583. /**
  2584. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2585. */
  2586. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2587. var q = new Quaternion();
  2588. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2589. return q;
  2590. };
  2591. /**
  2592. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2593. */
  2594. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2595. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2596. var halfRoll = roll * 0.5;
  2597. var halfPitch = pitch * 0.5;
  2598. var halfYaw = yaw * 0.5;
  2599. var sinRoll = Math.sin(halfRoll);
  2600. var cosRoll = Math.cos(halfRoll);
  2601. var sinPitch = Math.sin(halfPitch);
  2602. var cosPitch = Math.cos(halfPitch);
  2603. var sinYaw = Math.sin(halfYaw);
  2604. var cosYaw = Math.cos(halfYaw);
  2605. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2606. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2607. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2608. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2609. };
  2610. /**
  2611. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2612. */
  2613. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2614. var result = new Quaternion();
  2615. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2616. return result;
  2617. };
  2618. /**
  2619. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2620. */
  2621. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2622. // Produces a quaternion from Euler angles in the z-x-z orientation
  2623. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2624. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2625. var halfBeta = beta * 0.5;
  2626. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2627. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2628. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2629. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2630. };
  2631. /**
  2632. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2633. * cf to Vector3.RotationFromAxis() documentation.
  2634. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2635. */
  2636. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2637. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2638. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2639. return quat;
  2640. };
  2641. /**
  2642. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2643. * cf to Vector3.RotationFromAxis() documentation.
  2644. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2645. */
  2646. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2647. var rotMat = MathTmp.Matrix[0];
  2648. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2649. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2650. };
  2651. Quaternion.Slerp = function (left, right, amount) {
  2652. var result = Quaternion.Identity();
  2653. Quaternion.SlerpToRef(left, right, amount, result);
  2654. return result;
  2655. };
  2656. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2657. var num2;
  2658. var num3;
  2659. var num = amount;
  2660. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2661. var flag = false;
  2662. if (num4 < 0) {
  2663. flag = true;
  2664. num4 = -num4;
  2665. }
  2666. if (num4 > 0.999999) {
  2667. num3 = 1 - num;
  2668. num2 = flag ? -num : num;
  2669. }
  2670. else {
  2671. var num5 = Math.acos(num4);
  2672. var num6 = (1.0 / Math.sin(num5));
  2673. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2674. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2675. }
  2676. result.x = (num3 * left.x) + (num2 * right.x);
  2677. result.y = (num3 * left.y) + (num2 * right.y);
  2678. result.z = (num3 * left.z) + (num2 * right.z);
  2679. result.w = (num3 * left.w) + (num2 * right.w);
  2680. };
  2681. /**
  2682. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2683. */
  2684. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2685. var squared = amount * amount;
  2686. var cubed = amount * squared;
  2687. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2688. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2689. var part3 = (cubed - (2.0 * squared)) + amount;
  2690. var part4 = cubed - squared;
  2691. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2692. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2693. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2694. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2695. return new Quaternion(x, y, z, w);
  2696. };
  2697. return Quaternion;
  2698. }());
  2699. BABYLON.Quaternion = Quaternion;
  2700. var Matrix = (function () {
  2701. function Matrix() {
  2702. this._isIdentity = false;
  2703. this._isIdentityDirty = true;
  2704. this.m = new Float32Array(16);
  2705. this._markAsUpdated();
  2706. }
  2707. Matrix.prototype._markAsUpdated = function () {
  2708. this.updateFlag = Matrix._updateFlagSeed++;
  2709. this._isIdentityDirty = true;
  2710. };
  2711. // Properties
  2712. /**
  2713. * Boolean : True is the matrix is the identity matrix
  2714. */
  2715. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  2716. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  2717. if (this._isIdentityDirty) {
  2718. this._isIdentityDirty = false;
  2719. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  2720. this._isIdentity = false;
  2721. }
  2722. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2723. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2724. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2725. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  2726. this._isIdentity = false;
  2727. }
  2728. else {
  2729. this._isIdentity = true;
  2730. }
  2731. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  2732. this._isIdentity = false;
  2733. }
  2734. }
  2735. return this._isIdentity;
  2736. };
  2737. /**
  2738. * Returns the matrix determinant (float).
  2739. */
  2740. Matrix.prototype.determinant = function () {
  2741. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2742. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2743. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2744. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2745. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2746. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2747. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2748. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2749. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2750. };
  2751. // Methods
  2752. /**
  2753. * Returns the matrix underlying array.
  2754. */
  2755. Matrix.prototype.toArray = function () {
  2756. return this.m;
  2757. };
  2758. /**
  2759. * Returns the matrix underlying array.
  2760. */
  2761. Matrix.prototype.asArray = function () {
  2762. return this.toArray();
  2763. };
  2764. /**
  2765. * Inverts in place the Matrix.
  2766. * Returns the Matrix inverted.
  2767. */
  2768. Matrix.prototype.invert = function () {
  2769. this.invertToRef(this);
  2770. return this;
  2771. };
  2772. /**
  2773. * Sets all the matrix elements to zero.
  2774. * Returns the Matrix.
  2775. */
  2776. Matrix.prototype.reset = function () {
  2777. for (var index = 0; index < 16; index++) {
  2778. this.m[index] = 0.0;
  2779. }
  2780. this._markAsUpdated();
  2781. return this;
  2782. };
  2783. /**
  2784. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2785. */
  2786. Matrix.prototype.add = function (other) {
  2787. var result = new Matrix();
  2788. this.addToRef(other, result);
  2789. return result;
  2790. };
  2791. /**
  2792. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2793. * Returns the Matrix.
  2794. */
  2795. Matrix.prototype.addToRef = function (other, result) {
  2796. for (var index = 0; index < 16; index++) {
  2797. result.m[index] = this.m[index] + other.m[index];
  2798. }
  2799. result._markAsUpdated();
  2800. return this;
  2801. };
  2802. /**
  2803. * Adds in place the passed matrix to the current Matrix.
  2804. * Returns the updated Matrix.
  2805. */
  2806. Matrix.prototype.addToSelf = function (other) {
  2807. for (var index = 0; index < 16; index++) {
  2808. this.m[index] += other.m[index];
  2809. }
  2810. this._markAsUpdated();
  2811. return this;
  2812. };
  2813. /**
  2814. * Sets the passed matrix with the current inverted Matrix.
  2815. * Returns the unmodified current Matrix.
  2816. */
  2817. Matrix.prototype.invertToRef = function (other) {
  2818. var l1 = this.m[0];
  2819. var l2 = this.m[1];
  2820. var l3 = this.m[2];
  2821. var l4 = this.m[3];
  2822. var l5 = this.m[4];
  2823. var l6 = this.m[5];
  2824. var l7 = this.m[6];
  2825. var l8 = this.m[7];
  2826. var l9 = this.m[8];
  2827. var l10 = this.m[9];
  2828. var l11 = this.m[10];
  2829. var l12 = this.m[11];
  2830. var l13 = this.m[12];
  2831. var l14 = this.m[13];
  2832. var l15 = this.m[14];
  2833. var l16 = this.m[15];
  2834. var l17 = (l11 * l16) - (l12 * l15);
  2835. var l18 = (l10 * l16) - (l12 * l14);
  2836. var l19 = (l10 * l15) - (l11 * l14);
  2837. var l20 = (l9 * l16) - (l12 * l13);
  2838. var l21 = (l9 * l15) - (l11 * l13);
  2839. var l22 = (l9 * l14) - (l10 * l13);
  2840. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2841. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2842. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2843. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2844. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2845. var l28 = (l7 * l16) - (l8 * l15);
  2846. var l29 = (l6 * l16) - (l8 * l14);
  2847. var l30 = (l6 * l15) - (l7 * l14);
  2848. var l31 = (l5 * l16) - (l8 * l13);
  2849. var l32 = (l5 * l15) - (l7 * l13);
  2850. var l33 = (l5 * l14) - (l6 * l13);
  2851. var l34 = (l7 * l12) - (l8 * l11);
  2852. var l35 = (l6 * l12) - (l8 * l10);
  2853. var l36 = (l6 * l11) - (l7 * l10);
  2854. var l37 = (l5 * l12) - (l8 * l9);
  2855. var l38 = (l5 * l11) - (l7 * l9);
  2856. var l39 = (l5 * l10) - (l6 * l9);
  2857. other.m[0] = l23 * l27;
  2858. other.m[4] = l24 * l27;
  2859. other.m[8] = l25 * l27;
  2860. other.m[12] = l26 * l27;
  2861. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  2862. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  2863. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  2864. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  2865. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  2866. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  2867. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  2868. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  2869. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  2870. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  2871. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  2872. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  2873. other._markAsUpdated();
  2874. return this;
  2875. };
  2876. /**
  2877. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  2878. * Returns the updated Matrix.
  2879. */
  2880. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  2881. this.m[12] = x;
  2882. this.m[13] = y;
  2883. this.m[14] = z;
  2884. this._markAsUpdated();
  2885. return this;
  2886. };
  2887. /**
  2888. * Inserts the translation vector in the current Matrix.
  2889. * Returns the updated Matrix.
  2890. */
  2891. Matrix.prototype.setTranslation = function (vector3) {
  2892. this.m[12] = vector3.x;
  2893. this.m[13] = vector3.y;
  2894. this.m[14] = vector3.z;
  2895. this._markAsUpdated();
  2896. return this;
  2897. };
  2898. /**
  2899. * Returns a new Vector3 as the extracted translation from the Matrix.
  2900. */
  2901. Matrix.prototype.getTranslation = function () {
  2902. return new Vector3(this.m[12], this.m[13], this.m[14]);
  2903. };
  2904. /**
  2905. * Fill a Vector3 with the extracted translation from the Matrix.
  2906. */
  2907. Matrix.prototype.getTranslationToRef = function (result) {
  2908. result.x = this.m[12];
  2909. result.y = this.m[13];
  2910. result.z = this.m[14];
  2911. return this;
  2912. };
  2913. /**
  2914. * Remove rotation and scaling part from the Matrix.
  2915. * Returns the updated Matrix.
  2916. */
  2917. Matrix.prototype.removeRotationAndScaling = function () {
  2918. this.setRowFromFloats(0, 1, 0, 0, 0);
  2919. this.setRowFromFloats(1, 0, 1, 0, 0);
  2920. this.setRowFromFloats(2, 0, 0, 1, 0);
  2921. return this;
  2922. };
  2923. /**
  2924. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  2925. */
  2926. Matrix.prototype.multiply = function (other) {
  2927. var result = new Matrix();
  2928. this.multiplyToRef(other, result);
  2929. return result;
  2930. };
  2931. /**
  2932. * Updates the current Matrix from the passed one values.
  2933. * Returns the updated Matrix.
  2934. */
  2935. Matrix.prototype.copyFrom = function (other) {
  2936. for (var index = 0; index < 16; index++) {
  2937. this.m[index] = other.m[index];
  2938. }
  2939. this._markAsUpdated();
  2940. return this;
  2941. };
  2942. /**
  2943. * Populates the passed array from the starting index with the Matrix values.
  2944. * Returns the Matrix.
  2945. */
  2946. Matrix.prototype.copyToArray = function (array, offset) {
  2947. if (offset === void 0) { offset = 0; }
  2948. for (var index = 0; index < 16; index++) {
  2949. array[offset + index] = this.m[index];
  2950. }
  2951. return this;
  2952. };
  2953. /**
  2954. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  2955. */
  2956. Matrix.prototype.multiplyToRef = function (other, result) {
  2957. this.multiplyToArray(other, result.m, 0);
  2958. result._markAsUpdated();
  2959. return this;
  2960. };
  2961. /**
  2962. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  2963. */
  2964. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  2965. var tm0 = this.m[0];
  2966. var tm1 = this.m[1];
  2967. var tm2 = this.m[2];
  2968. var tm3 = this.m[3];
  2969. var tm4 = this.m[4];
  2970. var tm5 = this.m[5];
  2971. var tm6 = this.m[6];
  2972. var tm7 = this.m[7];
  2973. var tm8 = this.m[8];
  2974. var tm9 = this.m[9];
  2975. var tm10 = this.m[10];
  2976. var tm11 = this.m[11];
  2977. var tm12 = this.m[12];
  2978. var tm13 = this.m[13];
  2979. var tm14 = this.m[14];
  2980. var tm15 = this.m[15];
  2981. var om0 = other.m[0];
  2982. var om1 = other.m[1];
  2983. var om2 = other.m[2];
  2984. var om3 = other.m[3];
  2985. var om4 = other.m[4];
  2986. var om5 = other.m[5];
  2987. var om6 = other.m[6];
  2988. var om7 = other.m[7];
  2989. var om8 = other.m[8];
  2990. var om9 = other.m[9];
  2991. var om10 = other.m[10];
  2992. var om11 = other.m[11];
  2993. var om12 = other.m[12];
  2994. var om13 = other.m[13];
  2995. var om14 = other.m[14];
  2996. var om15 = other.m[15];
  2997. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  2998. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  2999. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  3000. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  3001. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  3002. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  3003. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  3004. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  3005. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  3006. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  3007. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3008. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3009. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3010. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3011. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3012. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3013. return this;
  3014. };
  3015. /**
  3016. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3017. */
  3018. Matrix.prototype.equals = function (value) {
  3019. return value &&
  3020. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3021. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3022. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3023. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3024. };
  3025. /**
  3026. * Returns a new Matrix from the current Matrix.
  3027. */
  3028. Matrix.prototype.clone = function () {
  3029. 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]);
  3030. };
  3031. /**
  3032. * Returns the string "Matrix"
  3033. */
  3034. Matrix.prototype.getClassName = function () {
  3035. return "Matrix";
  3036. };
  3037. /**
  3038. * Returns the Matrix hash code.
  3039. */
  3040. Matrix.prototype.getHashCode = function () {
  3041. var hash = this.m[0] || 0;
  3042. for (var i = 1; i < 16; i++) {
  3043. hash = (hash * 397) ^ (this.m[i] || 0);
  3044. }
  3045. return hash;
  3046. };
  3047. /**
  3048. * Decomposes the current Matrix into :
  3049. * - a scale vector3 passed as a reference to update,
  3050. * - a rotation quaternion passed as a reference to update,
  3051. * - a translation vector3 passed as a reference to update.
  3052. * Returns the boolean `true`.
  3053. */
  3054. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3055. translation.x = this.m[12];
  3056. translation.y = this.m[13];
  3057. translation.z = this.m[14];
  3058. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3059. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3060. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3061. if (this.determinant() <= 0) {
  3062. scale.y *= -1;
  3063. }
  3064. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3065. rotation.x = 0;
  3066. rotation.y = 0;
  3067. rotation.z = 0;
  3068. rotation.w = 1;
  3069. return false;
  3070. }
  3071. 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]);
  3072. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3073. return true;
  3074. };
  3075. /**
  3076. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3077. */
  3078. Matrix.prototype.getRotationMatrix = function () {
  3079. var result = Matrix.Identity();
  3080. this.getRotationMatrixToRef(result);
  3081. return result;
  3082. };
  3083. /**
  3084. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3085. * Returns the current Matrix.
  3086. */
  3087. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3088. var m = this.m;
  3089. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3090. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3091. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3092. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3093. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3094. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3095. 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);
  3096. return this;
  3097. };
  3098. // Statics
  3099. /**
  3100. * Returns a new Matrix set from the starting index of the passed array.
  3101. */
  3102. Matrix.FromArray = function (array, offset) {
  3103. var result = new Matrix();
  3104. if (!offset) {
  3105. offset = 0;
  3106. }
  3107. Matrix.FromArrayToRef(array, offset, result);
  3108. return result;
  3109. };
  3110. /**
  3111. * Sets the passed "result" matrix from the starting index of the passed array.
  3112. */
  3113. Matrix.FromArrayToRef = function (array, offset, result) {
  3114. for (var index = 0; index < 16; index++) {
  3115. result.m[index] = array[index + offset];
  3116. }
  3117. result._markAsUpdated();
  3118. };
  3119. /**
  3120. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3121. */
  3122. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3123. for (var index = 0; index < 16; index++) {
  3124. result.m[index] = array[index + offset] * scale;
  3125. }
  3126. result._markAsUpdated();
  3127. };
  3128. /**
  3129. * Sets the passed matrix "result" with the 16 passed floats.
  3130. */
  3131. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3132. result.m[0] = initialM11;
  3133. result.m[1] = initialM12;
  3134. result.m[2] = initialM13;
  3135. result.m[3] = initialM14;
  3136. result.m[4] = initialM21;
  3137. result.m[5] = initialM22;
  3138. result.m[6] = initialM23;
  3139. result.m[7] = initialM24;
  3140. result.m[8] = initialM31;
  3141. result.m[9] = initialM32;
  3142. result.m[10] = initialM33;
  3143. result.m[11] = initialM34;
  3144. result.m[12] = initialM41;
  3145. result.m[13] = initialM42;
  3146. result.m[14] = initialM43;
  3147. result.m[15] = initialM44;
  3148. result._markAsUpdated();
  3149. };
  3150. /**
  3151. * Returns the index-th row of the current matrix as a new Vector4.
  3152. */
  3153. Matrix.prototype.getRow = function (index) {
  3154. if (index < 0 || index > 3) {
  3155. return null;
  3156. }
  3157. var i = index * 4;
  3158. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3159. };
  3160. /**
  3161. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3162. * Returns the updated Matrix.
  3163. */
  3164. Matrix.prototype.setRow = function (index, row) {
  3165. if (index < 0 || index > 3) {
  3166. return this;
  3167. }
  3168. var i = index * 4;
  3169. this.m[i + 0] = row.x;
  3170. this.m[i + 1] = row.y;
  3171. this.m[i + 2] = row.z;
  3172. this.m[i + 3] = row.w;
  3173. this._markAsUpdated();
  3174. return this;
  3175. };
  3176. /**
  3177. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3178. * Returns the updated Matrix.
  3179. */
  3180. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3181. if (index < 0 || index > 3) {
  3182. return this;
  3183. }
  3184. var i = index * 4;
  3185. this.m[i + 0] = x;
  3186. this.m[i + 1] = y;
  3187. this.m[i + 2] = z;
  3188. this.m[i + 3] = w;
  3189. this._markAsUpdated();
  3190. return this;
  3191. };
  3192. /**
  3193. * Returns a new Matrix set from the 16 passed floats.
  3194. */
  3195. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3196. var result = new Matrix();
  3197. result.m[0] = initialM11;
  3198. result.m[1] = initialM12;
  3199. result.m[2] = initialM13;
  3200. result.m[3] = initialM14;
  3201. result.m[4] = initialM21;
  3202. result.m[5] = initialM22;
  3203. result.m[6] = initialM23;
  3204. result.m[7] = initialM24;
  3205. result.m[8] = initialM31;
  3206. result.m[9] = initialM32;
  3207. result.m[10] = initialM33;
  3208. result.m[11] = initialM34;
  3209. result.m[12] = initialM41;
  3210. result.m[13] = initialM42;
  3211. result.m[14] = initialM43;
  3212. result.m[15] = initialM44;
  3213. return result;
  3214. };
  3215. /**
  3216. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3217. */
  3218. Matrix.Compose = function (scale, rotation, translation) {
  3219. var result = Matrix.Identity();
  3220. Matrix.ComposeToRef(scale, rotation, translation, result);
  3221. return result;
  3222. };
  3223. /**
  3224. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3225. */
  3226. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3227. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3228. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3229. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3230. result.setTranslation(translation);
  3231. };
  3232. /**
  3233. * Returns a new indentity Matrix.
  3234. */
  3235. Matrix.Identity = function () {
  3236. 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);
  3237. };
  3238. /**
  3239. * Sets the passed "result" as an identity matrix.
  3240. */
  3241. Matrix.IdentityToRef = function (result) {
  3242. 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);
  3243. };
  3244. /**
  3245. * Returns a new zero Matrix.
  3246. */
  3247. Matrix.Zero = function () {
  3248. 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);
  3249. };
  3250. /**
  3251. * Returns a new rotation matrix for "angle" radians around the X axis.
  3252. */
  3253. Matrix.RotationX = function (angle) {
  3254. var result = new Matrix();
  3255. Matrix.RotationXToRef(angle, result);
  3256. return result;
  3257. };
  3258. /**
  3259. * Returns a new Matrix as the passed inverted one.
  3260. */
  3261. Matrix.Invert = function (source) {
  3262. var result = new Matrix();
  3263. source.invertToRef(result);
  3264. return result;
  3265. };
  3266. /**
  3267. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3268. */
  3269. Matrix.RotationXToRef = function (angle, result) {
  3270. var s = Math.sin(angle);
  3271. var c = Math.cos(angle);
  3272. result.m[0] = 1.0;
  3273. result.m[15] = 1.0;
  3274. result.m[5] = c;
  3275. result.m[10] = c;
  3276. result.m[9] = -s;
  3277. result.m[6] = s;
  3278. result.m[1] = 0.0;
  3279. result.m[2] = 0.0;
  3280. result.m[3] = 0.0;
  3281. result.m[4] = 0.0;
  3282. result.m[7] = 0.0;
  3283. result.m[8] = 0.0;
  3284. result.m[11] = 0.0;
  3285. result.m[12] = 0.0;
  3286. result.m[13] = 0.0;
  3287. result.m[14] = 0.0;
  3288. result._markAsUpdated();
  3289. };
  3290. /**
  3291. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3292. */
  3293. Matrix.RotationY = function (angle) {
  3294. var result = new Matrix();
  3295. Matrix.RotationYToRef(angle, result);
  3296. return result;
  3297. };
  3298. /**
  3299. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3300. */
  3301. Matrix.RotationYToRef = function (angle, result) {
  3302. var s = Math.sin(angle);
  3303. var c = Math.cos(angle);
  3304. result.m[5] = 1.0;
  3305. result.m[15] = 1.0;
  3306. result.m[0] = c;
  3307. result.m[2] = -s;
  3308. result.m[8] = s;
  3309. result.m[10] = c;
  3310. result.m[1] = 0.0;
  3311. result.m[3] = 0.0;
  3312. result.m[4] = 0.0;
  3313. result.m[6] = 0.0;
  3314. result.m[7] = 0.0;
  3315. result.m[9] = 0.0;
  3316. result.m[11] = 0.0;
  3317. result.m[12] = 0.0;
  3318. result.m[13] = 0.0;
  3319. result.m[14] = 0.0;
  3320. result._markAsUpdated();
  3321. };
  3322. /**
  3323. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3324. */
  3325. Matrix.RotationZ = function (angle) {
  3326. var result = new Matrix();
  3327. Matrix.RotationZToRef(angle, result);
  3328. return result;
  3329. };
  3330. /**
  3331. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3332. */
  3333. Matrix.RotationZToRef = function (angle, result) {
  3334. var s = Math.sin(angle);
  3335. var c = Math.cos(angle);
  3336. result.m[10] = 1.0;
  3337. result.m[15] = 1.0;
  3338. result.m[0] = c;
  3339. result.m[1] = s;
  3340. result.m[4] = -s;
  3341. result.m[5] = c;
  3342. result.m[2] = 0.0;
  3343. result.m[3] = 0.0;
  3344. result.m[6] = 0.0;
  3345. result.m[7] = 0.0;
  3346. result.m[8] = 0.0;
  3347. result.m[9] = 0.0;
  3348. result.m[11] = 0.0;
  3349. result.m[12] = 0.0;
  3350. result.m[13] = 0.0;
  3351. result.m[14] = 0.0;
  3352. result._markAsUpdated();
  3353. };
  3354. /**
  3355. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3356. */
  3357. Matrix.RotationAxis = function (axis, angle) {
  3358. var result = Matrix.Zero();
  3359. Matrix.RotationAxisToRef(axis, angle, result);
  3360. return result;
  3361. };
  3362. /**
  3363. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3364. */
  3365. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3366. var s = Math.sin(-angle);
  3367. var c = Math.cos(-angle);
  3368. var c1 = 1 - c;
  3369. axis.normalize();
  3370. result.m[0] = (axis.x * axis.x) * c1 + c;
  3371. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3372. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3373. result.m[3] = 0.0;
  3374. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3375. result.m[5] = (axis.y * axis.y) * c1 + c;
  3376. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3377. result.m[7] = 0.0;
  3378. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3379. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3380. result.m[10] = (axis.z * axis.z) * c1 + c;
  3381. result.m[11] = 0.0;
  3382. result.m[15] = 1.0;
  3383. result._markAsUpdated();
  3384. };
  3385. /**
  3386. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3387. */
  3388. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3389. var result = new Matrix();
  3390. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3391. return result;
  3392. };
  3393. /**
  3394. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3395. */
  3396. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3397. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3398. this._tempQuaternion.toRotationMatrix(result);
  3399. };
  3400. /**
  3401. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3402. */
  3403. Matrix.Scaling = function (x, y, z) {
  3404. var result = Matrix.Zero();
  3405. Matrix.ScalingToRef(x, y, z, result);
  3406. return result;
  3407. };
  3408. /**
  3409. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3410. */
  3411. Matrix.ScalingToRef = function (x, y, z, result) {
  3412. result.m[0] = x;
  3413. result.m[1] = 0.0;
  3414. result.m[2] = 0.0;
  3415. result.m[3] = 0.0;
  3416. result.m[4] = 0.0;
  3417. result.m[5] = y;
  3418. result.m[6] = 0.0;
  3419. result.m[7] = 0.0;
  3420. result.m[8] = 0.0;
  3421. result.m[9] = 0.0;
  3422. result.m[10] = z;
  3423. result.m[11] = 0.0;
  3424. result.m[12] = 0.0;
  3425. result.m[13] = 0.0;
  3426. result.m[14] = 0.0;
  3427. result.m[15] = 1.0;
  3428. result._markAsUpdated();
  3429. };
  3430. /**
  3431. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3432. */
  3433. Matrix.Translation = function (x, y, z) {
  3434. var result = Matrix.Identity();
  3435. Matrix.TranslationToRef(x, y, z, result);
  3436. return result;
  3437. };
  3438. /**
  3439. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3440. */
  3441. Matrix.TranslationToRef = function (x, y, z, result) {
  3442. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  3443. };
  3444. /**
  3445. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3446. */
  3447. Matrix.Lerp = function (startValue, endValue, gradient) {
  3448. var result = Matrix.Zero();
  3449. for (var index = 0; index < 16; index++) {
  3450. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3451. }
  3452. result._markAsUpdated();
  3453. return result;
  3454. };
  3455. /**
  3456. * Returns a new Matrix whose values are computed by :
  3457. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3458. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3459. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3460. */
  3461. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3462. var startScale = new Vector3(0, 0, 0);
  3463. var startRotation = new Quaternion();
  3464. var startTranslation = new Vector3(0, 0, 0);
  3465. startValue.decompose(startScale, startRotation, startTranslation);
  3466. var endScale = new Vector3(0, 0, 0);
  3467. var endRotation = new Quaternion();
  3468. var endTranslation = new Vector3(0, 0, 0);
  3469. endValue.decompose(endScale, endRotation, endTranslation);
  3470. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3471. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3472. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3473. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3474. };
  3475. /**
  3476. * 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".
  3477. * This methods works for a Left-Handed system.
  3478. */
  3479. Matrix.LookAtLH = function (eye, target, up) {
  3480. var result = Matrix.Zero();
  3481. Matrix.LookAtLHToRef(eye, target, up, result);
  3482. return result;
  3483. };
  3484. /**
  3485. * 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".
  3486. * This methods works for a Left-Handed system.
  3487. */
  3488. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3489. // Z axis
  3490. target.subtractToRef(eye, this._zAxis);
  3491. this._zAxis.normalize();
  3492. // X axis
  3493. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3494. if (this._xAxis.lengthSquared() === 0) {
  3495. this._xAxis.x = 1.0;
  3496. }
  3497. else {
  3498. this._xAxis.normalize();
  3499. }
  3500. // Y axis
  3501. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3502. this._yAxis.normalize();
  3503. // Eye angles
  3504. var ex = -Vector3.Dot(this._xAxis, eye);
  3505. var ey = -Vector3.Dot(this._yAxis, eye);
  3506. var ez = -Vector3.Dot(this._zAxis, eye);
  3507. 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);
  3508. };
  3509. /**
  3510. * 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".
  3511. * This methods works for a Right-Handed system.
  3512. */
  3513. Matrix.LookAtRH = function (eye, target, up) {
  3514. var result = Matrix.Zero();
  3515. Matrix.LookAtRHToRef(eye, target, up, result);
  3516. return result;
  3517. };
  3518. /**
  3519. * 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".
  3520. * This methods works for a Left-Handed system.
  3521. */
  3522. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3523. // Z axis
  3524. eye.subtractToRef(target, this._zAxis);
  3525. this._zAxis.normalize();
  3526. // X axis
  3527. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3528. if (this._xAxis.lengthSquared() === 0) {
  3529. this._xAxis.x = 1.0;
  3530. }
  3531. else {
  3532. this._xAxis.normalize();
  3533. }
  3534. // Y axis
  3535. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3536. this._yAxis.normalize();
  3537. // Eye angles
  3538. var ex = -Vector3.Dot(this._xAxis, eye);
  3539. var ey = -Vector3.Dot(this._yAxis, eye);
  3540. var ez = -Vector3.Dot(this._zAxis, eye);
  3541. 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);
  3542. };
  3543. /**
  3544. * 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.
  3545. */
  3546. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3547. var matrix = Matrix.Zero();
  3548. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3549. return matrix;
  3550. };
  3551. /**
  3552. * 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.
  3553. */
  3554. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3555. var n = znear;
  3556. var f = zfar;
  3557. var a = 2.0 / width;
  3558. var b = 2.0 / height;
  3559. var c = 2.0 / (f - n);
  3560. var d = -(f + n) / (f - n);
  3561. 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);
  3562. };
  3563. /**
  3564. * 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.
  3565. */
  3566. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3567. var matrix = Matrix.Zero();
  3568. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3569. return matrix;
  3570. };
  3571. /**
  3572. * 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.
  3573. */
  3574. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3575. var n = znear;
  3576. var f = zfar;
  3577. var a = 2.0 / (right - left);
  3578. var b = 2.0 / (top - bottom);
  3579. var c = 2.0 / (f - n);
  3580. var d = -(f + n) / (f - n);
  3581. var i0 = (left + right) / (left - right);
  3582. var i1 = (top + bottom) / (bottom - top);
  3583. 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);
  3584. };
  3585. /**
  3586. * 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.
  3587. */
  3588. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3589. var matrix = Matrix.Zero();
  3590. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3591. return matrix;
  3592. };
  3593. /**
  3594. * 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.
  3595. */
  3596. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3597. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3598. result.m[10] *= -1.0;
  3599. };
  3600. /**
  3601. * 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.
  3602. */
  3603. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3604. var matrix = Matrix.Zero();
  3605. var n = znear;
  3606. var f = zfar;
  3607. var a = 2.0 * n / width;
  3608. var b = 2.0 * n / height;
  3609. var c = (f + n) / (f - n);
  3610. var d = -2.0 * f * n / (f - n);
  3611. 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);
  3612. return matrix;
  3613. };
  3614. /**
  3615. * 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.
  3616. */
  3617. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3618. var matrix = Matrix.Zero();
  3619. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3620. return matrix;
  3621. };
  3622. /**
  3623. * 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.
  3624. */
  3625. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3626. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3627. var n = znear;
  3628. var f = zfar;
  3629. var t = 1.0 / (Math.tan(fov * 0.5));
  3630. var a = isVerticalFovFixed ? (t / aspect) : t;
  3631. var b = isVerticalFovFixed ? t : (t * aspect);
  3632. var c = (f + n) / (f - n);
  3633. var d = -2.0 * f * n / (f - n);
  3634. 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);
  3635. };
  3636. /**
  3637. * 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.
  3638. */
  3639. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3640. var matrix = Matrix.Zero();
  3641. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3642. return matrix;
  3643. };
  3644. /**
  3645. * 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.
  3646. */
  3647. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3648. //alternatively this could be expressed as:
  3649. // m = PerspectiveFovLHToRef
  3650. // m[10] *= -1.0;
  3651. // m[11] *= -1.0;
  3652. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3653. var n = znear;
  3654. var f = zfar;
  3655. var t = 1.0 / (Math.tan(fov * 0.5));
  3656. var a = isVerticalFovFixed ? (t / aspect) : t;
  3657. var b = isVerticalFovFixed ? t : (t * aspect);
  3658. var c = -(f + n) / (f - n);
  3659. var d = -2 * f * n / (f - n);
  3660. 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);
  3661. };
  3662. /**
  3663. * 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.
  3664. */
  3665. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3666. if (rightHanded === void 0) { rightHanded = false; }
  3667. var rightHandedFactor = rightHanded ? -1 : 1;
  3668. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3669. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3670. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3671. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3672. var xScale = 2.0 / (leftTan + rightTan);
  3673. var yScale = 2.0 / (upTan + downTan);
  3674. result.m[0] = xScale;
  3675. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3676. result.m[5] = yScale;
  3677. result.m[6] = result.m[7] = 0.0;
  3678. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3679. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3680. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3681. result.m[10] = -zfar / (znear - zfar);
  3682. result.m[11] = 1.0 * rightHandedFactor;
  3683. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3684. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3685. // result.m[14] = (znear * zfar) / (znear - zfar);
  3686. result._markAsUpdated();
  3687. };
  3688. /**
  3689. * Returns the final transformation matrix : world * view * projection * viewport
  3690. */
  3691. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3692. var cw = viewport.width;
  3693. var ch = viewport.height;
  3694. var cx = viewport.x;
  3695. var cy = viewport.y;
  3696. 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);
  3697. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3698. };
  3699. /**
  3700. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3701. */
  3702. Matrix.GetAsMatrix2x2 = function (matrix) {
  3703. return new Float32Array([
  3704. matrix.m[0], matrix.m[1],
  3705. matrix.m[4], matrix.m[5]
  3706. ]);
  3707. };
  3708. /**
  3709. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3710. */
  3711. Matrix.GetAsMatrix3x3 = function (matrix) {
  3712. return new Float32Array([
  3713. matrix.m[0], matrix.m[1], matrix.m[2],
  3714. matrix.m[4], matrix.m[5], matrix.m[6],
  3715. matrix.m[8], matrix.m[9], matrix.m[10]
  3716. ]);
  3717. };
  3718. /**
  3719. * Compute the transpose of the passed Matrix.
  3720. * Returns a new Matrix.
  3721. */
  3722. Matrix.Transpose = function (matrix) {
  3723. var result = new Matrix();
  3724. result.m[0] = matrix.m[0];
  3725. result.m[1] = matrix.m[4];
  3726. result.m[2] = matrix.m[8];
  3727. result.m[3] = matrix.m[12];
  3728. result.m[4] = matrix.m[1];
  3729. result.m[5] = matrix.m[5];
  3730. result.m[6] = matrix.m[9];
  3731. result.m[7] = matrix.m[13];
  3732. result.m[8] = matrix.m[2];
  3733. result.m[9] = matrix.m[6];
  3734. result.m[10] = matrix.m[10];
  3735. result.m[11] = matrix.m[14];
  3736. result.m[12] = matrix.m[3];
  3737. result.m[13] = matrix.m[7];
  3738. result.m[14] = matrix.m[11];
  3739. result.m[15] = matrix.m[15];
  3740. return result;
  3741. };
  3742. /**
  3743. * Returns a new Matrix as the reflection matrix across the passed plane.
  3744. */
  3745. Matrix.Reflection = function (plane) {
  3746. var matrix = new Matrix();
  3747. Matrix.ReflectionToRef(plane, matrix);
  3748. return matrix;
  3749. };
  3750. /**
  3751. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3752. */
  3753. Matrix.ReflectionToRef = function (plane, result) {
  3754. plane.normalize();
  3755. var x = plane.normal.x;
  3756. var y = plane.normal.y;
  3757. var z = plane.normal.z;
  3758. var temp = -2 * x;
  3759. var temp2 = -2 * y;
  3760. var temp3 = -2 * z;
  3761. result.m[0] = (temp * x) + 1;
  3762. result.m[1] = temp2 * x;
  3763. result.m[2] = temp3 * x;
  3764. result.m[3] = 0.0;
  3765. result.m[4] = temp * y;
  3766. result.m[5] = (temp2 * y) + 1;
  3767. result.m[6] = temp3 * y;
  3768. result.m[7] = 0.0;
  3769. result.m[8] = temp * z;
  3770. result.m[9] = temp2 * z;
  3771. result.m[10] = (temp3 * z) + 1;
  3772. result.m[11] = 0.0;
  3773. result.m[12] = temp * plane.d;
  3774. result.m[13] = temp2 * plane.d;
  3775. result.m[14] = temp3 * plane.d;
  3776. result.m[15] = 1.0;
  3777. result._markAsUpdated();
  3778. };
  3779. /**
  3780. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3781. */
  3782. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3783. result.m[0] = xaxis.x;
  3784. result.m[1] = xaxis.y;
  3785. result.m[2] = xaxis.z;
  3786. result.m[3] = 0.0;
  3787. result.m[4] = yaxis.x;
  3788. result.m[5] = yaxis.y;
  3789. result.m[6] = yaxis.z;
  3790. result.m[7] = 0.0;
  3791. result.m[8] = zaxis.x;
  3792. result.m[9] = zaxis.y;
  3793. result.m[10] = zaxis.z;
  3794. result.m[11] = 0.0;
  3795. result.m[12] = 0.0;
  3796. result.m[13] = 0.0;
  3797. result.m[14] = 0.0;
  3798. result.m[15] = 1.0;
  3799. result._markAsUpdated();
  3800. };
  3801. /**
  3802. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3803. */
  3804. Matrix.FromQuaternionToRef = function (quat, result) {
  3805. var xx = quat.x * quat.x;
  3806. var yy = quat.y * quat.y;
  3807. var zz = quat.z * quat.z;
  3808. var xy = quat.x * quat.y;
  3809. var zw = quat.z * quat.w;
  3810. var zx = quat.z * quat.x;
  3811. var yw = quat.y * quat.w;
  3812. var yz = quat.y * quat.z;
  3813. var xw = quat.x * quat.w;
  3814. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3815. result.m[1] = 2.0 * (xy + zw);
  3816. result.m[2] = 2.0 * (zx - yw);
  3817. result.m[3] = 0.0;
  3818. result.m[4] = 2.0 * (xy - zw);
  3819. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3820. result.m[6] = 2.0 * (yz + xw);
  3821. result.m[7] = 0.0;
  3822. result.m[8] = 2.0 * (zx + yw);
  3823. result.m[9] = 2.0 * (yz - xw);
  3824. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3825. result.m[11] = 0.0;
  3826. result.m[12] = 0.0;
  3827. result.m[13] = 0.0;
  3828. result.m[14] = 0.0;
  3829. result.m[15] = 1.0;
  3830. result._markAsUpdated();
  3831. };
  3832. return Matrix;
  3833. }());
  3834. Matrix._tempQuaternion = new Quaternion();
  3835. Matrix._xAxis = Vector3.Zero();
  3836. Matrix._yAxis = Vector3.Zero();
  3837. Matrix._zAxis = Vector3.Zero();
  3838. Matrix._updateFlagSeed = 0;
  3839. BABYLON.Matrix = Matrix;
  3840. var Plane = (function () {
  3841. /**
  3842. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3843. */
  3844. function Plane(a, b, c, d) {
  3845. this.normal = new Vector3(a, b, c);
  3846. this.d = d;
  3847. }
  3848. /**
  3849. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  3850. */
  3851. Plane.prototype.asArray = function () {
  3852. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  3853. };
  3854. // Methods
  3855. /**
  3856. * Returns a new plane copied from the current Plane.
  3857. */
  3858. Plane.prototype.clone = function () {
  3859. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  3860. };
  3861. /**
  3862. * Returns the string "Plane".
  3863. */
  3864. Plane.prototype.getClassName = function () {
  3865. return "Plane";
  3866. };
  3867. /**
  3868. * Returns the Plane hash code.
  3869. */
  3870. Plane.prototype.getHashCode = function () {
  3871. var hash = this.normal.getHashCode();
  3872. hash = (hash * 397) ^ (this.d || 0);
  3873. return hash;
  3874. };
  3875. /**
  3876. * Normalize the current Plane in place.
  3877. * Returns the updated Plane.
  3878. */
  3879. Plane.prototype.normalize = function () {
  3880. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  3881. var magnitude = 0.0;
  3882. if (norm !== 0) {
  3883. magnitude = 1.0 / norm;
  3884. }
  3885. this.normal.x *= magnitude;
  3886. this.normal.y *= magnitude;
  3887. this.normal.z *= magnitude;
  3888. this.d *= magnitude;
  3889. return this;
  3890. };
  3891. /**
  3892. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  3893. */
  3894. Plane.prototype.transform = function (transformation) {
  3895. var transposedMatrix = Matrix.Transpose(transformation);
  3896. var x = this.normal.x;
  3897. var y = this.normal.y;
  3898. var z = this.normal.z;
  3899. var d = this.d;
  3900. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  3901. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  3902. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  3903. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  3904. return new Plane(normalX, normalY, normalZ, finalD);
  3905. };
  3906. /**
  3907. * Returns the dot product (float) of the point coordinates and the plane normal.
  3908. */
  3909. Plane.prototype.dotCoordinate = function (point) {
  3910. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  3911. };
  3912. /**
  3913. * Updates the current Plane from the plane defined by the three passed points.
  3914. * Returns the updated Plane.
  3915. */
  3916. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  3917. var x1 = point2.x - point1.x;
  3918. var y1 = point2.y - point1.y;
  3919. var z1 = point2.z - point1.z;
  3920. var x2 = point3.x - point1.x;
  3921. var y2 = point3.y - point1.y;
  3922. var z2 = point3.z - point1.z;
  3923. var yz = (y1 * z2) - (z1 * y2);
  3924. var xz = (z1 * x2) - (x1 * z2);
  3925. var xy = (x1 * y2) - (y1 * x2);
  3926. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  3927. var invPyth;
  3928. if (pyth !== 0) {
  3929. invPyth = 1.0 / pyth;
  3930. }
  3931. else {
  3932. invPyth = 0.0;
  3933. }
  3934. this.normal.x = yz * invPyth;
  3935. this.normal.y = xz * invPyth;
  3936. this.normal.z = xy * invPyth;
  3937. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  3938. return this;
  3939. };
  3940. /**
  3941. * Boolean : True is the vector "direction" is the same side than the plane normal.
  3942. */
  3943. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  3944. var dot = Vector3.Dot(this.normal, direction);
  3945. return (dot <= epsilon);
  3946. };
  3947. /**
  3948. * Returns the signed distance (float) from the passed point to the Plane.
  3949. */
  3950. Plane.prototype.signedDistanceTo = function (point) {
  3951. return Vector3.Dot(point, this.normal) + this.d;
  3952. };
  3953. // Statics
  3954. /**
  3955. * Returns a new Plane from the passed array.
  3956. */
  3957. Plane.FromArray = function (array) {
  3958. return new Plane(array[0], array[1], array[2], array[3]);
  3959. };
  3960. /**
  3961. * Returns a new Plane defined by the three passed points.
  3962. */
  3963. Plane.FromPoints = function (point1, point2, point3) {
  3964. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3965. result.copyFromPoints(point1, point2, point3);
  3966. return result;
  3967. };
  3968. /**
  3969. * Returns a new Plane the normal vector to this plane at the passed origin point.
  3970. * Note : the vector "normal" is updated because normalized.
  3971. */
  3972. Plane.FromPositionAndNormal = function (origin, normal) {
  3973. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3974. normal.normalize();
  3975. result.normal = normal;
  3976. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3977. return result;
  3978. };
  3979. /**
  3980. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  3981. */
  3982. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  3983. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3984. return Vector3.Dot(point, normal) + d;
  3985. };
  3986. return Plane;
  3987. }());
  3988. BABYLON.Plane = Plane;
  3989. var Viewport = (function () {
  3990. /**
  3991. * Creates a Viewport object located at (x, y) and sized (width, height).
  3992. */
  3993. function Viewport(x, y, width, height) {
  3994. this.x = x;
  3995. this.y = y;
  3996. this.width = width;
  3997. this.height = height;
  3998. }
  3999. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  4000. if (renderWidthOrEngine._gl) {
  4001. var engine = renderWidthOrEngine;
  4002. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  4003. }
  4004. var renderWidth = renderWidthOrEngine;
  4005. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  4006. };
  4007. /**
  4008. * Returns a new Viewport copied from the current one.
  4009. */
  4010. Viewport.prototype.clone = function () {
  4011. return new Viewport(this.x, this.y, this.width, this.height);
  4012. };
  4013. return Viewport;
  4014. }());
  4015. BABYLON.Viewport = Viewport;
  4016. var Frustum = (function () {
  4017. function Frustum() {
  4018. }
  4019. /**
  4020. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4021. */
  4022. Frustum.GetPlanes = function (transform) {
  4023. var frustumPlanes = [];
  4024. for (var index = 0; index < 6; index++) {
  4025. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4026. }
  4027. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4028. return frustumPlanes;
  4029. };
  4030. /**
  4031. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4032. */
  4033. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4034. // Near
  4035. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  4036. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  4037. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  4038. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  4039. frustumPlanes[0].normalize();
  4040. // Far
  4041. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  4042. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  4043. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  4044. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  4045. frustumPlanes[1].normalize();
  4046. // Left
  4047. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  4048. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  4049. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  4050. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  4051. frustumPlanes[2].normalize();
  4052. // Right
  4053. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  4054. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  4055. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  4056. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  4057. frustumPlanes[3].normalize();
  4058. // Top
  4059. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  4060. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  4061. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  4062. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  4063. frustumPlanes[4].normalize();
  4064. // Bottom
  4065. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  4066. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  4067. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  4068. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  4069. frustumPlanes[5].normalize();
  4070. };
  4071. return Frustum;
  4072. }());
  4073. BABYLON.Frustum = Frustum;
  4074. var Space;
  4075. (function (Space) {
  4076. Space[Space["LOCAL"] = 0] = "LOCAL";
  4077. Space[Space["WORLD"] = 1] = "WORLD";
  4078. Space[Space["BONE"] = 2] = "BONE";
  4079. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4080. var Axis = (function () {
  4081. function Axis() {
  4082. }
  4083. return Axis;
  4084. }());
  4085. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4086. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4087. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4088. BABYLON.Axis = Axis;
  4089. ;
  4090. var BezierCurve = (function () {
  4091. function BezierCurve() {
  4092. }
  4093. /**
  4094. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4095. */
  4096. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4097. // Extract X (which is equal to time here)
  4098. var f0 = 1 - 3 * x2 + 3 * x1;
  4099. var f1 = 3 * x2 - 6 * x1;
  4100. var f2 = 3 * x1;
  4101. var refinedT = t;
  4102. for (var i = 0; i < 5; i++) {
  4103. var refinedT2 = refinedT * refinedT;
  4104. var refinedT3 = refinedT2 * refinedT;
  4105. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4106. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4107. refinedT -= (x - t) * slope;
  4108. refinedT = Math.min(1, Math.max(0, refinedT));
  4109. }
  4110. // Resolve cubic bezier for the given x
  4111. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4112. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4113. Math.pow(refinedT, 3);
  4114. };
  4115. return BezierCurve;
  4116. }());
  4117. BABYLON.BezierCurve = BezierCurve;
  4118. var Orientation;
  4119. (function (Orientation) {
  4120. Orientation[Orientation["CW"] = 0] = "CW";
  4121. Orientation[Orientation["CCW"] = 1] = "CCW";
  4122. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4123. var Angle = (function () {
  4124. /**
  4125. * Creates an Angle object of "radians" radians (float).
  4126. */
  4127. function Angle(radians) {
  4128. var _this = this;
  4129. /**
  4130. * Returns the Angle value in degrees (float).
  4131. */
  4132. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4133. /**
  4134. * Returns the Angle value in radians (float).
  4135. */
  4136. this.radians = function () { return _this._radians; };
  4137. this._radians = radians;
  4138. if (this._radians < 0.0)
  4139. this._radians += (2.0 * Math.PI);
  4140. }
  4141. /**
  4142. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4143. */
  4144. Angle.BetweenTwoPoints = function (a, b) {
  4145. var delta = b.subtract(a);
  4146. var theta = Math.atan2(delta.y, delta.x);
  4147. return new Angle(theta);
  4148. };
  4149. /**
  4150. * Returns a new Angle object from the passed float in radians.
  4151. */
  4152. Angle.FromRadians = function (radians) {
  4153. return new Angle(radians);
  4154. };
  4155. /**
  4156. * Returns a new Angle object from the passed float in degrees.
  4157. */
  4158. Angle.FromDegrees = function (degrees) {
  4159. return new Angle(degrees * Math.PI / 180.0);
  4160. };
  4161. return Angle;
  4162. }());
  4163. BABYLON.Angle = Angle;
  4164. var Arc2 = (function () {
  4165. /**
  4166. * Creates an Arc object from the three passed points : start, middle and end.
  4167. */
  4168. function Arc2(startPoint, midPoint, endPoint) {
  4169. this.startPoint = startPoint;
  4170. this.midPoint = midPoint;
  4171. this.endPoint = endPoint;
  4172. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4173. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4174. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4175. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4176. 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);
  4177. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4178. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4179. var a1 = this.startAngle.degrees();
  4180. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4181. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4182. // angles correction
  4183. if (a2 - a1 > +180.0)
  4184. a2 -= 360.0;
  4185. if (a2 - a1 < -180.0)
  4186. a2 += 360.0;
  4187. if (a3 - a2 > +180.0)
  4188. a3 -= 360.0;
  4189. if (a3 - a2 < -180.0)
  4190. a3 += 360.0;
  4191. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4192. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4193. }
  4194. return Arc2;
  4195. }());
  4196. BABYLON.Arc2 = Arc2;
  4197. var Path2 = (function () {
  4198. /**
  4199. * Creates a Path2 object from the starting 2D coordinates x and y.
  4200. */
  4201. function Path2(x, y) {
  4202. this._points = new Array();
  4203. this._length = 0.0;
  4204. this.closed = false;
  4205. this._points.push(new Vector2(x, y));
  4206. }
  4207. /**
  4208. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4209. * Returns the updated Path2.
  4210. */
  4211. Path2.prototype.addLineTo = function (x, y) {
  4212. if (closed) {
  4213. //Tools.Error("cannot add lines to closed paths");
  4214. return this;
  4215. }
  4216. var newPoint = new Vector2(x, y);
  4217. var previousPoint = this._points[this._points.length - 1];
  4218. this._points.push(newPoint);
  4219. this._length += newPoint.subtract(previousPoint).length();
  4220. return this;
  4221. };
  4222. /**
  4223. * 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.
  4224. * Returns the updated Path2.
  4225. */
  4226. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4227. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4228. if (closed) {
  4229. //Tools.Error("cannot add arcs to closed paths");
  4230. return this;
  4231. }
  4232. var startPoint = this._points[this._points.length - 1];
  4233. var midPoint = new Vector2(midX, midY);
  4234. var endPoint = new Vector2(endX, endY);
  4235. var arc = new Arc2(startPoint, midPoint, endPoint);
  4236. var increment = arc.angle.radians() / numberOfSegments;
  4237. if (arc.orientation === Orientation.CW)
  4238. increment *= -1;
  4239. var currentAngle = arc.startAngle.radians() + increment;
  4240. for (var i = 0; i < numberOfSegments; i++) {
  4241. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4242. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4243. this.addLineTo(x, y);
  4244. currentAngle += increment;
  4245. }
  4246. return this;
  4247. };
  4248. /**
  4249. * Closes the Path2.
  4250. * Returns the Path2.
  4251. */
  4252. Path2.prototype.close = function () {
  4253. this.closed = true;
  4254. return this;
  4255. };
  4256. /**
  4257. * Returns the Path2 total length (float).
  4258. */
  4259. Path2.prototype.length = function () {
  4260. var result = this._length;
  4261. if (!this.closed) {
  4262. var lastPoint = this._points[this._points.length - 1];
  4263. var firstPoint = this._points[0];
  4264. result += (firstPoint.subtract(lastPoint).length());
  4265. }
  4266. return result;
  4267. };
  4268. /**
  4269. * Returns the Path2 internal array of points.
  4270. */
  4271. Path2.prototype.getPoints = function () {
  4272. return this._points;
  4273. };
  4274. /**
  4275. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4276. */
  4277. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4278. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4279. //Tools.Error("normalized length position should be between 0 and 1.");
  4280. return Vector2.Zero();
  4281. }
  4282. var lengthPosition = normalizedLengthPosition * this.length();
  4283. var previousOffset = 0;
  4284. for (var i = 0; i < this._points.length; i++) {
  4285. var j = (i + 1) % this._points.length;
  4286. var a = this._points[i];
  4287. var b = this._points[j];
  4288. var bToA = b.subtract(a);
  4289. var nextOffset = (bToA.length() + previousOffset);
  4290. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4291. var dir = bToA.normalize();
  4292. var localOffset = lengthPosition - previousOffset;
  4293. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4294. }
  4295. previousOffset = nextOffset;
  4296. }
  4297. //Tools.Error("internal error");
  4298. return Vector2.Zero();
  4299. };
  4300. /**
  4301. * Returns a new Path2 starting at the coordinates (x, y).
  4302. */
  4303. Path2.StartingAt = function (x, y) {
  4304. return new Path2(x, y);
  4305. };
  4306. return Path2;
  4307. }());
  4308. BABYLON.Path2 = Path2;
  4309. var Path3D = (function () {
  4310. /**
  4311. * new Path3D(path, normal, raw)
  4312. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4313. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4314. * path : an array of Vector3, the curve axis of the Path3D
  4315. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4316. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4317. */
  4318. function Path3D(path, firstNormal, raw) {
  4319. this.path = path;
  4320. this._curve = new Array();
  4321. this._distances = new Array();
  4322. this._tangents = new Array();
  4323. this._normals = new Array();
  4324. this._binormals = new Array();
  4325. for (var p = 0; p < path.length; p++) {
  4326. this._curve[p] = path[p].clone(); // hard copy
  4327. }
  4328. this._raw = raw || false;
  4329. this._compute(firstNormal);
  4330. }
  4331. /**
  4332. * Returns the Path3D array of successive Vector3 designing its curve.
  4333. */
  4334. Path3D.prototype.getCurve = function () {
  4335. return this._curve;
  4336. };
  4337. /**
  4338. * Returns an array populated with tangent vectors on each Path3D curve point.
  4339. */
  4340. Path3D.prototype.getTangents = function () {
  4341. return this._tangents;
  4342. };
  4343. /**
  4344. * Returns an array populated with normal vectors on each Path3D curve point.
  4345. */
  4346. Path3D.prototype.getNormals = function () {
  4347. return this._normals;
  4348. };
  4349. /**
  4350. * Returns an array populated with binormal vectors on each Path3D curve point.
  4351. */
  4352. Path3D.prototype.getBinormals = function () {
  4353. return this._binormals;
  4354. };
  4355. /**
  4356. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4357. */
  4358. Path3D.prototype.getDistances = function () {
  4359. return this._distances;
  4360. };
  4361. /**
  4362. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4363. * Returns the same object updated.
  4364. */
  4365. Path3D.prototype.update = function (path, firstNormal) {
  4366. for (var p = 0; p < path.length; p++) {
  4367. this._curve[p].x = path[p].x;
  4368. this._curve[p].y = path[p].y;
  4369. this._curve[p].z = path[p].z;
  4370. }
  4371. this._compute(firstNormal);
  4372. return this;
  4373. };
  4374. // private function compute() : computes tangents, normals and binormals
  4375. Path3D.prototype._compute = function (firstNormal) {
  4376. var l = this._curve.length;
  4377. // first and last tangents
  4378. this._tangents[0] = this._getFirstNonNullVector(0);
  4379. if (!this._raw) {
  4380. this._tangents[0].normalize();
  4381. }
  4382. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4383. if (!this._raw) {
  4384. this._tangents[l - 1].normalize();
  4385. }
  4386. // normals and binormals at first point : arbitrary vector with _normalVector()
  4387. var tg0 = this._tangents[0];
  4388. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4389. this._normals[0] = pp0;
  4390. if (!this._raw) {
  4391. this._normals[0].normalize();
  4392. }
  4393. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4394. if (!this._raw) {
  4395. this._binormals[0].normalize();
  4396. }
  4397. this._distances[0] = 0.0;
  4398. // normals and binormals : next points
  4399. var prev; // previous vector (segment)
  4400. var cur; // current vector (segment)
  4401. var curTang; // current tangent
  4402. // previous normal
  4403. var prevBinor; // previous binormal
  4404. for (var i = 1; i < l; i++) {
  4405. // tangents
  4406. prev = this._getLastNonNullVector(i);
  4407. if (i < l - 1) {
  4408. cur = this._getFirstNonNullVector(i);
  4409. this._tangents[i] = prev.add(cur);
  4410. this._tangents[i].normalize();
  4411. }
  4412. this._distances[i] = this._distances[i - 1] + prev.length();
  4413. // normals and binormals
  4414. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4415. curTang = this._tangents[i];
  4416. prevBinor = this._binormals[i - 1];
  4417. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4418. if (!this._raw) {
  4419. this._normals[i].normalize();
  4420. }
  4421. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4422. if (!this._raw) {
  4423. this._binormals[i].normalize();
  4424. }
  4425. }
  4426. };
  4427. // private function getFirstNonNullVector(index)
  4428. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4429. Path3D.prototype._getFirstNonNullVector = function (index) {
  4430. var i = 1;
  4431. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4432. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4433. i++;
  4434. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4435. }
  4436. return nNVector;
  4437. };
  4438. // private function getLastNonNullVector(index)
  4439. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4440. Path3D.prototype._getLastNonNullVector = function (index) {
  4441. var i = 1;
  4442. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4443. while (nLVector.length() === 0 && index > i + 1) {
  4444. i++;
  4445. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4446. }
  4447. return nLVector;
  4448. };
  4449. // private function normalVector(v0, vt, va) :
  4450. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4451. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4452. Path3D.prototype._normalVector = function (v0, vt, va) {
  4453. var normal0;
  4454. var tgl = vt.length();
  4455. if (tgl === 0.0) {
  4456. tgl = 1.0;
  4457. }
  4458. if (va === undefined || va === null) {
  4459. var point;
  4460. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4461. point = new Vector3(0.0, -1.0, 0.0);
  4462. }
  4463. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4464. point = new Vector3(1.0, 0.0, 0.0);
  4465. }
  4466. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4467. point = new Vector3(0.0, 0.0, 1.0);
  4468. }
  4469. normal0 = Vector3.Cross(vt, point);
  4470. }
  4471. else {
  4472. normal0 = Vector3.Cross(vt, va);
  4473. Vector3.CrossToRef(normal0, vt, normal0);
  4474. }
  4475. normal0.normalize();
  4476. return normal0;
  4477. };
  4478. return Path3D;
  4479. }());
  4480. BABYLON.Path3D = Path3D;
  4481. var Curve3 = (function () {
  4482. /**
  4483. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4484. * A Curve3 is designed from a series of successive Vector3.
  4485. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4486. */
  4487. function Curve3(points) {
  4488. this._length = 0.0;
  4489. this._points = points;
  4490. this._length = this._computeLength(points);
  4491. }
  4492. /**
  4493. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4494. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4495. * @param v1 (Vector3) the control point
  4496. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4497. * @param nbPoints (integer) the wanted number of points in the curve
  4498. */
  4499. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4500. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4501. var bez = new Array();
  4502. var equation = function (t, val0, val1, val2) {
  4503. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4504. return res;
  4505. };
  4506. for (var i = 0; i <= nbPoints; i++) {
  4507. 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)));
  4508. }
  4509. return new Curve3(bez);
  4510. };
  4511. /**
  4512. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4513. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4514. * @param v1 (Vector3) the first control point
  4515. * @param v2 (Vector3) the second control point
  4516. * @param v3 (Vector3) the end point of the Cubic Bezier
  4517. * @param nbPoints (integer) the wanted number of points in the curve
  4518. */
  4519. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4520. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4521. var bez = new Array();
  4522. var equation = function (t, val0, val1, val2, val3) {
  4523. 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;
  4524. return res;
  4525. };
  4526. for (var i = 0; i <= nbPoints; i++) {
  4527. 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)));
  4528. }
  4529. return new Curve3(bez);
  4530. };
  4531. /**
  4532. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4533. * @param p1 (Vector3) the origin point of the Hermite Spline
  4534. * @param t1 (Vector3) the tangent vector at the origin point
  4535. * @param p2 (Vector3) the end point of the Hermite Spline
  4536. * @param t2 (Vector3) the tangent vector at the end point
  4537. * @param nbPoints (integer) the wanted number of points in the curve
  4538. */
  4539. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4540. var hermite = new Array();
  4541. var step = 1.0 / nbPoints;
  4542. for (var i = 0; i <= nbPoints; i++) {
  4543. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4544. }
  4545. return new Curve3(hermite);
  4546. };
  4547. /**
  4548. * Returns a Curve3 object along a CatmullRom Spline curve :
  4549. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4550. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4551. */
  4552. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4553. var totalPoints = new Array();
  4554. totalPoints.push(points[0].clone());
  4555. Array.prototype.push.apply(totalPoints, points);
  4556. totalPoints.push(points[points.length - 1].clone());
  4557. var catmullRom = new Array();
  4558. var step = 1.0 / nbPoints;
  4559. for (var i = 0; i < totalPoints.length - 3; i++) {
  4560. var amount = 0.0;
  4561. for (var c = 0; c < nbPoints; c++) {
  4562. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4563. amount += step;
  4564. }
  4565. }
  4566. i--;
  4567. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4568. return new Curve3(catmullRom);
  4569. };
  4570. /**
  4571. * Returns the Curve3 stored array of successive Vector3
  4572. */
  4573. Curve3.prototype.getPoints = function () {
  4574. return this._points;
  4575. };
  4576. /**
  4577. * Returns the computed length (float) of the curve.
  4578. */
  4579. Curve3.prototype.length = function () {
  4580. return this._length;
  4581. };
  4582. /**
  4583. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4584. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4585. * curveA and curveB keep unchanged.
  4586. */
  4587. Curve3.prototype.continue = function (curve) {
  4588. var lastPoint = this._points[this._points.length - 1];
  4589. var continuedPoints = this._points.slice();
  4590. var curvePoints = curve.getPoints();
  4591. for (var i = 1; i < curvePoints.length; i++) {
  4592. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4593. }
  4594. var continuedCurve = new Curve3(continuedPoints);
  4595. return continuedCurve;
  4596. };
  4597. Curve3.prototype._computeLength = function (path) {
  4598. var l = 0;
  4599. for (var i = 1; i < path.length; i++) {
  4600. l += (path[i].subtract(path[i - 1])).length();
  4601. }
  4602. return l;
  4603. };
  4604. return Curve3;
  4605. }());
  4606. BABYLON.Curve3 = Curve3;
  4607. // Vertex formats
  4608. var PositionNormalVertex = (function () {
  4609. function PositionNormalVertex(position, normal) {
  4610. if (position === void 0) { position = Vector3.Zero(); }
  4611. if (normal === void 0) { normal = Vector3.Up(); }
  4612. this.position = position;
  4613. this.normal = normal;
  4614. }
  4615. PositionNormalVertex.prototype.clone = function () {
  4616. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4617. };
  4618. return PositionNormalVertex;
  4619. }());
  4620. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4621. var PositionNormalTextureVertex = (function () {
  4622. function PositionNormalTextureVertex(position, normal, uv) {
  4623. if (position === void 0) { position = Vector3.Zero(); }
  4624. if (normal === void 0) { normal = Vector3.Up(); }
  4625. if (uv === void 0) { uv = Vector2.Zero(); }
  4626. this.position = position;
  4627. this.normal = normal;
  4628. this.uv = uv;
  4629. }
  4630. PositionNormalTextureVertex.prototype.clone = function () {
  4631. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4632. };
  4633. return PositionNormalTextureVertex;
  4634. }());
  4635. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4636. // Temporary pre-allocated objects for engine internal use
  4637. // usage in any internal function :
  4638. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4639. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4640. var Tmp = (function () {
  4641. function Tmp() {
  4642. }
  4643. return Tmp;
  4644. }());
  4645. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4646. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4647. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4648. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4649. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4650. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4651. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4652. Matrix.Zero(), Matrix.Zero(),
  4653. Matrix.Zero(), Matrix.Zero(),
  4654. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4655. BABYLON.Tmp = Tmp;
  4656. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4657. var MathTmp = (function () {
  4658. function MathTmp() {
  4659. }
  4660. return MathTmp;
  4661. }());
  4662. MathTmp.Vector3 = [Vector3.Zero()];
  4663. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4664. MathTmp.Quaternion = [Quaternion.Zero()];
  4665. })(BABYLON || (BABYLON = {}));
  4666. //# sourceMappingURL=babylon.math.js.map
  4667. var BABYLON;
  4668. (function (BABYLON) {
  4669. var Scalar = (function () {
  4670. function Scalar() {
  4671. }
  4672. /**
  4673. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  4674. */
  4675. Scalar.WithinEpsilon = function (a, b, epsilon) {
  4676. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4677. var num = a - b;
  4678. return -epsilon <= num && num <= epsilon;
  4679. };
  4680. /**
  4681. * Returns a string : the upper case translation of the number i to hexadecimal.
  4682. */
  4683. Scalar.ToHex = function (i) {
  4684. var str = i.toString(16);
  4685. if (i <= 15) {
  4686. return ("0" + str).toUpperCase();
  4687. }
  4688. return str.toUpperCase();
  4689. };
  4690. /**
  4691. * Returns -1 if value is negative and +1 is value is positive.
  4692. * Returns the value itself if it's equal to zero.
  4693. */
  4694. Scalar.Sign = function (value) {
  4695. value = +value; // convert to a number
  4696. if (value === 0 || isNaN(value))
  4697. return value;
  4698. return value > 0 ? 1 : -1;
  4699. };
  4700. /**
  4701. * Returns the value itself if it's between min and max.
  4702. * Returns min if the value is lower than min.
  4703. * Returns max if the value is greater than max.
  4704. */
  4705. Scalar.Clamp = function (value, min, max) {
  4706. if (min === void 0) { min = 0; }
  4707. if (max === void 0) { max = 1; }
  4708. return Math.min(max, Math.max(min, value));
  4709. };
  4710. /**
  4711. * Returns the log2 of value.
  4712. */
  4713. Scalar.Log2 = function (value) {
  4714. return Math.log(value) * Math.LOG2E;
  4715. };
  4716. /**
  4717. * Loops the value, so that it is never larger than length and never smaller than 0.
  4718. *
  4719. * This is similar to the modulo operator but it works with floating point numbers.
  4720. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  4721. * With t = 5 and length = 2.5, the result would be 0.0.
  4722. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  4723. */
  4724. Scalar.Repeat = function (value, length) {
  4725. return value - Math.floor(value / length) * length;
  4726. };
  4727. /**
  4728. * Normalize the value between 0.0 and 1.0 using min and max values
  4729. */
  4730. Scalar.Normalize = function (value, min, max) {
  4731. return (value - min) / (max - min);
  4732. };
  4733. /**
  4734. * Denormalize the value from 0.0 and 1.0 using min and max values
  4735. */
  4736. Scalar.Denormalize = function (normalized, min, max) {
  4737. return (normalized * (max - min) + min);
  4738. };
  4739. /**
  4740. * Calculates the shortest difference between two given angles given in degrees.
  4741. */
  4742. Scalar.DeltaAngle = function (current, target) {
  4743. var num = Scalar.Repeat(target - current, 360.0);
  4744. if (num > 180.0) {
  4745. num -= 360.0;
  4746. }
  4747. return num;
  4748. };
  4749. /**
  4750. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  4751. *
  4752. * The returned value will move back and forth between 0 and length
  4753. */
  4754. Scalar.PingPong = function (tx, length) {
  4755. var t = Scalar.Repeat(tx, length * 2.0);
  4756. return length - Math.abs(t - length);
  4757. };
  4758. /**
  4759. * Interpolates between min and max with smoothing at the limits.
  4760. *
  4761. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  4762. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  4763. */
  4764. Scalar.SmoothStep = function (from, to, tx) {
  4765. var t = Scalar.Clamp(tx);
  4766. t = -2.0 * t * t * t + 3.0 * t * t;
  4767. return to * t + from * (1.0 - t);
  4768. };
  4769. /**
  4770. * Moves a value current towards target.
  4771. *
  4772. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  4773. * Negative values of maxDelta pushes the value away from target.
  4774. */
  4775. Scalar.MoveTowards = function (current, target, maxDelta) {
  4776. var result = 0;
  4777. if (Math.abs(target - current) <= maxDelta) {
  4778. result = target;
  4779. }
  4780. else {
  4781. result = current + Scalar.Sign(target - current) * maxDelta;
  4782. }
  4783. return result;
  4784. };
  4785. /**
  4786. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  4787. *
  4788. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  4789. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  4790. */
  4791. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  4792. var num = Scalar.DeltaAngle(current, target);
  4793. var result = 0;
  4794. if (-maxDelta < num && num < maxDelta) {
  4795. result = target;
  4796. }
  4797. else {
  4798. target = current + num;
  4799. result = Scalar.MoveTowards(current, target, maxDelta);
  4800. }
  4801. return result;
  4802. };
  4803. /**
  4804. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  4805. */
  4806. Scalar.Lerp = function (start, end, amount) {
  4807. return start + ((end - start) * amount);
  4808. };
  4809. /**
  4810. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  4811. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  4812. */
  4813. Scalar.LerpAngle = function (start, end, amount) {
  4814. var num = Scalar.Repeat(end - start, 360.0);
  4815. if (num > 180.0) {
  4816. num -= 360.0;
  4817. }
  4818. return start + num * Scalar.Clamp(amount);
  4819. };
  4820. /**
  4821. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  4822. */
  4823. Scalar.InverseLerp = function (a, b, value) {
  4824. var result = 0;
  4825. if (a != b) {
  4826. result = Scalar.Clamp((value - a) / (b - a));
  4827. }
  4828. else {
  4829. result = 0.0;
  4830. }
  4831. return result;
  4832. };
  4833. /**
  4834. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  4835. */
  4836. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4837. var squared = amount * amount;
  4838. var cubed = amount * squared;
  4839. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4840. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4841. var part3 = (cubed - (2.0 * squared)) + amount;
  4842. var part4 = cubed - squared;
  4843. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  4844. };
  4845. /**
  4846. * Returns a random float number between and min and max values
  4847. */
  4848. Scalar.RandomRange = function (min, max) {
  4849. if (min === max)
  4850. return min;
  4851. return ((Math.random() * (max - min)) + min);
  4852. };
  4853. /**
  4854. * This function returns percentage of a number in a given range.
  4855. *
  4856. * RangeToPercent(40,20,60) will return 0.5 (50%)
  4857. * RangeToPercent(34,0,100) will return 0.34 (34%)
  4858. */
  4859. Scalar.RangeToPercent = function (number, min, max) {
  4860. return ((number - min) / (max - min));
  4861. };
  4862. /**
  4863. * This function returns number that corresponds to the percentage in a given range.
  4864. *
  4865. * PercentToRange(0.34,0,100) will return 34.
  4866. */
  4867. Scalar.PercentToRange = function (percent, min, max) {
  4868. return ((max - min) * percent + min);
  4869. };
  4870. return Scalar;
  4871. }());
  4872. BABYLON.Scalar = Scalar;
  4873. })(BABYLON || (BABYLON = {}));
  4874. //# sourceMappingURL=babylon.math.scalar.js.map
  4875. //# sourceMappingURL=babylon.mixins.js.map
  4876. var BABYLON;
  4877. (function (BABYLON) {
  4878. var __decoratorInitialStore = {};
  4879. var __mergedStore = {};
  4880. var _copySource = function (creationFunction, source, instanciate) {
  4881. var destination = creationFunction();
  4882. // Tags
  4883. if (BABYLON.Tags) {
  4884. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4885. }
  4886. var classStore = getMergedStore(destination);
  4887. // Properties
  4888. for (var property in classStore) {
  4889. var propertyDescriptor = classStore[property];
  4890. var sourceProperty = source[property];
  4891. var propertyType = propertyDescriptor.type;
  4892. if (sourceProperty !== undefined && sourceProperty !== null) {
  4893. switch (propertyType) {
  4894. case 0: // Value
  4895. case 6:
  4896. destination[property] = sourceProperty;
  4897. break;
  4898. case 1: // Texture
  4899. case 2: // Color3
  4900. case 3: // FresnelParameters
  4901. case 4: // Vector2
  4902. case 5: // Vector3
  4903. case 7:
  4904. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  4905. break;
  4906. }
  4907. }
  4908. }
  4909. return destination;
  4910. };
  4911. function getDirectStore(target) {
  4912. var classKey = target.getClassName();
  4913. if (!__decoratorInitialStore[classKey]) {
  4914. __decoratorInitialStore[classKey] = {};
  4915. }
  4916. return __decoratorInitialStore[classKey];
  4917. }
  4918. /**
  4919. * Return the list of properties flagged as serializable
  4920. * @param target: host object
  4921. */
  4922. function getMergedStore(target) {
  4923. var classKey = target.getClassName();
  4924. if (__mergedStore[classKey]) {
  4925. return __mergedStore[classKey];
  4926. }
  4927. __mergedStore[classKey] = {};
  4928. var store = __mergedStore[classKey];
  4929. var currentTarget = target;
  4930. var currentKey = classKey;
  4931. while (currentKey) {
  4932. var initialStore = __decoratorInitialStore[currentKey];
  4933. for (var property in initialStore) {
  4934. store[property] = initialStore[property];
  4935. }
  4936. var parent_1 = void 0;
  4937. var done = false;
  4938. do {
  4939. parent_1 = Object.getPrototypeOf(currentTarget);
  4940. if (!parent_1.getClassName) {
  4941. done = true;
  4942. break;
  4943. }
  4944. if (parent_1.getClassName() !== currentKey) {
  4945. break;
  4946. }
  4947. currentTarget = parent_1;
  4948. } while (parent_1);
  4949. if (done) {
  4950. break;
  4951. }
  4952. currentKey = parent_1.getClassName();
  4953. currentTarget = parent_1;
  4954. }
  4955. return store;
  4956. }
  4957. function generateSerializableMember(type, sourceName) {
  4958. return function (target, propertyKey) {
  4959. var classStore = getDirectStore(target);
  4960. if (!classStore[propertyKey]) {
  4961. classStore[propertyKey] = { type: type, sourceName: sourceName };
  4962. }
  4963. };
  4964. }
  4965. function generateExpandMember(setCallback, targetKey) {
  4966. return function (target, propertyKey) {
  4967. var key = targetKey || ("_" + propertyKey);
  4968. Object.defineProperty(target, propertyKey, {
  4969. get: function () {
  4970. return this[key];
  4971. },
  4972. set: function (value) {
  4973. if (this[key] === value) {
  4974. return;
  4975. }
  4976. this[key] = value;
  4977. target[setCallback].apply(this);
  4978. },
  4979. enumerable: true,
  4980. configurable: true
  4981. });
  4982. };
  4983. }
  4984. function expandToProperty(callback, targetKey) {
  4985. return generateExpandMember(callback, targetKey);
  4986. }
  4987. BABYLON.expandToProperty = expandToProperty;
  4988. function serialize(sourceName) {
  4989. return generateSerializableMember(0, sourceName); // value member
  4990. }
  4991. BABYLON.serialize = serialize;
  4992. function serializeAsTexture(sourceName) {
  4993. return generateSerializableMember(1, sourceName); // texture member
  4994. }
  4995. BABYLON.serializeAsTexture = serializeAsTexture;
  4996. function serializeAsColor3(sourceName) {
  4997. return generateSerializableMember(2, sourceName); // color3 member
  4998. }
  4999. BABYLON.serializeAsColor3 = serializeAsColor3;
  5000. function serializeAsFresnelParameters(sourceName) {
  5001. return generateSerializableMember(3, sourceName); // fresnel parameters member
  5002. }
  5003. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  5004. function serializeAsVector2(sourceName) {
  5005. return generateSerializableMember(4, sourceName); // vector2 member
  5006. }
  5007. BABYLON.serializeAsVector2 = serializeAsVector2;
  5008. function serializeAsVector3(sourceName) {
  5009. return generateSerializableMember(5, sourceName); // vector3 member
  5010. }
  5011. BABYLON.serializeAsVector3 = serializeAsVector3;
  5012. function serializeAsMeshReference(sourceName) {
  5013. return generateSerializableMember(6, sourceName); // mesh reference member
  5014. }
  5015. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  5016. function serializeAsColorCurves(sourceName) {
  5017. return generateSerializableMember(7, sourceName); // color curves
  5018. }
  5019. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  5020. function serializeAsColor4(sourceName) {
  5021. return generateSerializableMember(8, sourceName); // color 4
  5022. }
  5023. BABYLON.serializeAsColor4 = serializeAsColor4;
  5024. function serializeAsImageProcessingConfiguration(sourceName) {
  5025. return generateSerializableMember(9, sourceName); // image processing
  5026. }
  5027. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  5028. var SerializationHelper = (function () {
  5029. function SerializationHelper() {
  5030. }
  5031. SerializationHelper.Serialize = function (entity, serializationObject) {
  5032. if (!serializationObject) {
  5033. serializationObject = {};
  5034. }
  5035. // Tags
  5036. if (BABYLON.Tags) {
  5037. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  5038. }
  5039. var serializedProperties = getMergedStore(entity);
  5040. // Properties
  5041. for (var property in serializedProperties) {
  5042. var propertyDescriptor = serializedProperties[property];
  5043. var targetPropertyName = propertyDescriptor.sourceName || property;
  5044. var propertyType = propertyDescriptor.type;
  5045. var sourceProperty = entity[property];
  5046. if (sourceProperty !== undefined && sourceProperty !== null) {
  5047. switch (propertyType) {
  5048. case 0:
  5049. serializationObject[targetPropertyName] = sourceProperty;
  5050. break;
  5051. case 1:
  5052. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5053. break;
  5054. case 2:
  5055. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5056. break;
  5057. case 3:
  5058. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5059. break;
  5060. case 4:
  5061. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5062. break;
  5063. case 5:
  5064. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5065. break;
  5066. case 6:
  5067. serializationObject[targetPropertyName] = sourceProperty.id;
  5068. break;
  5069. case 7:
  5070. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5071. break;
  5072. case 8:
  5073. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5074. break;
  5075. case 9:
  5076. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5077. break;
  5078. }
  5079. }
  5080. }
  5081. return serializationObject;
  5082. };
  5083. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  5084. var destination = creationFunction();
  5085. // Tags
  5086. if (BABYLON.Tags) {
  5087. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5088. }
  5089. var classStore = getMergedStore(destination);
  5090. // Properties
  5091. for (var property in classStore) {
  5092. var propertyDescriptor = classStore[property];
  5093. var sourceProperty = source[propertyDescriptor.sourceName || property];
  5094. var propertyType = propertyDescriptor.type;
  5095. if (sourceProperty !== undefined && sourceProperty !== null) {
  5096. switch (propertyType) {
  5097. case 0:
  5098. destination[property] = sourceProperty;
  5099. break;
  5100. case 1:
  5101. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  5102. break;
  5103. case 2:
  5104. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  5105. break;
  5106. case 3:
  5107. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  5108. break;
  5109. case 4:
  5110. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  5111. break;
  5112. case 5:
  5113. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  5114. break;
  5115. case 6:
  5116. destination[property] = scene.getLastMeshByID(sourceProperty);
  5117. break;
  5118. case 7:
  5119. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  5120. break;
  5121. case 8:
  5122. destination[property] = BABYLON.Color4.FromArray(sourceProperty);
  5123. break;
  5124. case 9:
  5125. destination[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  5126. break;
  5127. }
  5128. }
  5129. }
  5130. return destination;
  5131. };
  5132. SerializationHelper.Clone = function (creationFunction, source) {
  5133. return _copySource(creationFunction, source, false);
  5134. };
  5135. SerializationHelper.Instanciate = function (creationFunction, source) {
  5136. return _copySource(creationFunction, source, true);
  5137. };
  5138. return SerializationHelper;
  5139. }());
  5140. BABYLON.SerializationHelper = SerializationHelper;
  5141. })(BABYLON || (BABYLON = {}));
  5142. //# sourceMappingURL=babylon.decorators.js.map
  5143. var BABYLON;
  5144. (function (BABYLON) {
  5145. /**
  5146. * A class serves as a medium between the observable and its observers
  5147. */
  5148. var EventState = (function () {
  5149. /**
  5150. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  5151. */
  5152. function EventState(mask, skipNextObservers) {
  5153. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5154. this.initalize(mask, skipNextObservers);
  5155. }
  5156. EventState.prototype.initalize = function (mask, skipNextObservers) {
  5157. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5158. this.mask = mask;
  5159. this.skipNextObservers = skipNextObservers;
  5160. return this;
  5161. };
  5162. return EventState;
  5163. }());
  5164. BABYLON.EventState = EventState;
  5165. /**
  5166. * Represent an Observer registered to a given Observable object.
  5167. */
  5168. var Observer = (function () {
  5169. function Observer(callback, mask) {
  5170. this.callback = callback;
  5171. this.mask = mask;
  5172. }
  5173. return Observer;
  5174. }());
  5175. BABYLON.Observer = Observer;
  5176. /**
  5177. * The Observable class is a simple implementation of the Observable pattern.
  5178. * 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.
  5179. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  5180. * 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).
  5181. * 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.
  5182. */
  5183. var Observable = (function () {
  5184. function Observable() {
  5185. this._observers = new Array();
  5186. this._eventState = new EventState(0);
  5187. }
  5188. /**
  5189. * Create a new Observer with the specified callback
  5190. * @param callback the callback that will be executed for that Observer
  5191. * @param mask the mask used to filter observers
  5192. * @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.
  5193. */
  5194. Observable.prototype.add = function (callback, mask, insertFirst) {
  5195. if (mask === void 0) { mask = -1; }
  5196. if (insertFirst === void 0) { insertFirst = false; }
  5197. if (!callback) {
  5198. return null;
  5199. }
  5200. var observer = new Observer(callback, mask);
  5201. if (insertFirst) {
  5202. this._observers.unshift(observer);
  5203. }
  5204. else {
  5205. this._observers.push(observer);
  5206. }
  5207. return observer;
  5208. };
  5209. /**
  5210. * Remove an Observer from the Observable object
  5211. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5212. */
  5213. Observable.prototype.remove = function (observer) {
  5214. var index = this._observers.indexOf(observer);
  5215. if (index !== -1) {
  5216. this._observers.splice(index, 1);
  5217. return true;
  5218. }
  5219. return false;
  5220. };
  5221. /**
  5222. * Remove a callback from the Observable object
  5223. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5224. */
  5225. Observable.prototype.removeCallback = function (callback) {
  5226. for (var index = 0; index < this._observers.length; index++) {
  5227. if (this._observers[index].callback === callback) {
  5228. this._observers.splice(index, 1);
  5229. return true;
  5230. }
  5231. }
  5232. return false;
  5233. };
  5234. /**
  5235. * Notify all Observers by calling their respective callback with the given data
  5236. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5237. * @param eventData
  5238. * @param mask
  5239. */
  5240. Observable.prototype.notifyObservers = function (eventData, mask) {
  5241. if (mask === void 0) { mask = -1; }
  5242. var state = this._eventState;
  5243. state.mask = mask;
  5244. state.skipNextObservers = false;
  5245. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5246. var obs = _a[_i];
  5247. if (obs.mask & mask) {
  5248. obs.callback(eventData, state);
  5249. }
  5250. if (state.skipNextObservers) {
  5251. return false;
  5252. }
  5253. }
  5254. return true;
  5255. };
  5256. /**
  5257. * return true is the Observable has at least one Observer registered
  5258. */
  5259. Observable.prototype.hasObservers = function () {
  5260. return this._observers.length > 0;
  5261. };
  5262. /**
  5263. * Clear the list of observers
  5264. */
  5265. Observable.prototype.clear = function () {
  5266. this._observers = new Array();
  5267. };
  5268. /**
  5269. * Clone the current observable
  5270. */
  5271. Observable.prototype.clone = function () {
  5272. var result = new Observable();
  5273. result._observers = this._observers.slice(0);
  5274. return result;
  5275. };
  5276. /**
  5277. * Does this observable handles observer registered with a given mask
  5278. * @param {number} trigger - the mask to be tested
  5279. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5280. **/
  5281. Observable.prototype.hasSpecificMask = function (mask) {
  5282. if (mask === void 0) { mask = -1; }
  5283. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5284. var obs = _a[_i];
  5285. if (obs.mask & mask && obs.mask === mask) {
  5286. return true;
  5287. }
  5288. }
  5289. return false;
  5290. };
  5291. return Observable;
  5292. }());
  5293. BABYLON.Observable = Observable;
  5294. })(BABYLON || (BABYLON = {}));
  5295. //# sourceMappingURL=babylon.observable.js.map
  5296. var BABYLON;
  5297. (function (BABYLON) {
  5298. var SmartArray = (function () {
  5299. function SmartArray(capacity) {
  5300. this.length = 0;
  5301. this._duplicateId = 0;
  5302. this.data = new Array(capacity);
  5303. this._id = SmartArray._GlobalId++;
  5304. }
  5305. SmartArray.prototype.push = function (value) {
  5306. this.data[this.length++] = value;
  5307. if (this.length > this.data.length) {
  5308. this.data.length *= 2;
  5309. }
  5310. if (!value.__smartArrayFlags) {
  5311. value.__smartArrayFlags = {};
  5312. }
  5313. value.__smartArrayFlags[this._id] = this._duplicateId;
  5314. };
  5315. SmartArray.prototype.forEach = function (func) {
  5316. for (var index = 0; index < this.length; index++) {
  5317. func(this.data[index]);
  5318. }
  5319. };
  5320. SmartArray.prototype.pushNoDuplicate = function (value) {
  5321. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5322. return false;
  5323. }
  5324. this.push(value);
  5325. return true;
  5326. };
  5327. SmartArray.prototype.sort = function (compareFn) {
  5328. this.data.sort(compareFn);
  5329. };
  5330. SmartArray.prototype.reset = function () {
  5331. this.length = 0;
  5332. this._duplicateId++;
  5333. };
  5334. SmartArray.prototype.dispose = function () {
  5335. this.reset();
  5336. if (this.data) {
  5337. this.data.length = 0;
  5338. this.data = null;
  5339. }
  5340. };
  5341. SmartArray.prototype.concat = function (array) {
  5342. if (array.length === 0) {
  5343. return;
  5344. }
  5345. if (this.length + array.length > this.data.length) {
  5346. this.data.length = (this.length + array.length) * 2;
  5347. }
  5348. for (var index = 0; index < array.length; index++) {
  5349. this.data[this.length++] = (array.data || array)[index];
  5350. }
  5351. };
  5352. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5353. if (array.length === 0) {
  5354. return;
  5355. }
  5356. if (this.length + array.length > this.data.length) {
  5357. this.data.length = (this.length + array.length) * 2;
  5358. }
  5359. for (var index = 0; index < array.length; index++) {
  5360. var item = (array.data || array)[index];
  5361. this.pushNoDuplicate(item);
  5362. }
  5363. };
  5364. SmartArray.prototype.indexOf = function (value) {
  5365. var position = this.data.indexOf(value);
  5366. if (position >= this.length) {
  5367. return -1;
  5368. }
  5369. return position;
  5370. };
  5371. SmartArray.prototype.contains = function (value) {
  5372. return this.data.indexOf(value) !== -1;
  5373. };
  5374. return SmartArray;
  5375. }());
  5376. // Statics
  5377. SmartArray._GlobalId = 0;
  5378. BABYLON.SmartArray = SmartArray;
  5379. })(BABYLON || (BABYLON = {}));
  5380. //# sourceMappingURL=babylon.smartArray.js.map
  5381. var BABYLON;
  5382. (function (BABYLON) {
  5383. // Screenshots
  5384. var screenshotCanvas;
  5385. var cloneValue = function (source, destinationObject) {
  5386. if (!source)
  5387. return null;
  5388. if (source instanceof BABYLON.Mesh) {
  5389. return null;
  5390. }
  5391. if (source instanceof BABYLON.SubMesh) {
  5392. return source.clone(destinationObject);
  5393. }
  5394. else if (source.clone) {
  5395. return source.clone();
  5396. }
  5397. return null;
  5398. };
  5399. var Tools = (function () {
  5400. function Tools() {
  5401. }
  5402. ;
  5403. /**
  5404. * Interpolates between a and b via alpha
  5405. * @param a The lower value (returned when alpha = 0)
  5406. * @param b The upper value (returned when alpha = 1)
  5407. * @param alpha The interpolation-factor
  5408. * @return The mixed value
  5409. */
  5410. Tools.Mix = function (a, b, alpha) {
  5411. return a * (1 - alpha) + b * alpha;
  5412. };
  5413. Tools.Instantiate = function (className) {
  5414. var arr = className.split(".");
  5415. var fn = (window || this);
  5416. for (var i = 0, len = arr.length; i < len; i++) {
  5417. fn = fn[arr[i]];
  5418. }
  5419. if (typeof fn !== "function") {
  5420. return null;
  5421. }
  5422. return fn;
  5423. };
  5424. Tools.SetImmediate = function (action) {
  5425. if (window.setImmediate) {
  5426. window.setImmediate(action);
  5427. }
  5428. else {
  5429. setTimeout(action, 1);
  5430. }
  5431. };
  5432. Tools.IsExponentOfTwo = function (value) {
  5433. var count = 1;
  5434. do {
  5435. count *= 2;
  5436. } while (count < value);
  5437. return count === value;
  5438. };
  5439. /**
  5440. * Find the next highest power of two.
  5441. * @param x Number to start search from.
  5442. * @return Next highest power of two.
  5443. */
  5444. Tools.CeilingPOT = function (x) {
  5445. x--;
  5446. x |= x >> 1;
  5447. x |= x >> 2;
  5448. x |= x >> 4;
  5449. x |= x >> 8;
  5450. x |= x >> 16;
  5451. x++;
  5452. return x;
  5453. };
  5454. /**
  5455. * Find the next lowest power of two.
  5456. * @param x Number to start search from.
  5457. * @return Next lowest power of two.
  5458. */
  5459. Tools.FloorPOT = function (x) {
  5460. x = x | (x >> 1);
  5461. x = x | (x >> 2);
  5462. x = x | (x >> 4);
  5463. x = x | (x >> 8);
  5464. x = x | (x >> 16);
  5465. return x - (x >> 1);
  5466. };
  5467. /**
  5468. * Find the nearest power of two.
  5469. * @param x Number to start search from.
  5470. * @return Next nearest power of two.
  5471. */
  5472. Tools.NearestPOT = function (x) {
  5473. var c = Tools.CeilingPOT(x);
  5474. var f = Tools.FloorPOT(x);
  5475. return (c - x) > (x - f) ? f : c;
  5476. };
  5477. Tools.GetExponentOfTwo = function (value, max, mode) {
  5478. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5479. var pot;
  5480. switch (mode) {
  5481. case BABYLON.Engine.SCALEMODE_FLOOR:
  5482. pot = Tools.FloorPOT(value);
  5483. break;
  5484. case BABYLON.Engine.SCALEMODE_NEAREST:
  5485. pot = Tools.NearestPOT(value);
  5486. break;
  5487. case BABYLON.Engine.SCALEMODE_CEILING:
  5488. pot = Tools.CeilingPOT(value);
  5489. break;
  5490. }
  5491. return Math.min(pot, max);
  5492. };
  5493. Tools.GetFilename = function (path) {
  5494. var index = path.lastIndexOf("/");
  5495. if (index < 0)
  5496. return path;
  5497. return path.substring(index + 1);
  5498. };
  5499. Tools.GetDOMTextContent = function (element) {
  5500. var result = "";
  5501. var child = element.firstChild;
  5502. while (child) {
  5503. if (child.nodeType === 3) {
  5504. result += child.textContent;
  5505. }
  5506. child = child.nextSibling;
  5507. }
  5508. return result;
  5509. };
  5510. Tools.ToDegrees = function (angle) {
  5511. return angle * 180 / Math.PI;
  5512. };
  5513. Tools.ToRadians = function (angle) {
  5514. return angle * Math.PI / 180;
  5515. };
  5516. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5517. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5518. var output = "";
  5519. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5520. var i = 0;
  5521. var bytes = new Uint8Array(buffer);
  5522. while (i < bytes.length) {
  5523. chr1 = bytes[i++];
  5524. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5525. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5526. enc1 = chr1 >> 2;
  5527. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5528. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5529. enc4 = chr3 & 63;
  5530. if (isNaN(chr2)) {
  5531. enc3 = enc4 = 64;
  5532. }
  5533. else if (isNaN(chr3)) {
  5534. enc4 = 64;
  5535. }
  5536. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5537. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5538. }
  5539. return "data:image/png;base64," + output;
  5540. };
  5541. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5542. if (bias === void 0) { bias = null; }
  5543. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5544. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5545. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5546. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5547. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5548. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5549. }
  5550. if (bias) {
  5551. minimum.x -= minimum.x * bias.x + bias.y;
  5552. minimum.y -= minimum.y * bias.x + bias.y;
  5553. minimum.z -= minimum.z * bias.x + bias.y;
  5554. maximum.x += maximum.x * bias.x + bias.y;
  5555. maximum.y += maximum.y * bias.x + bias.y;
  5556. maximum.z += maximum.z * bias.x + bias.y;
  5557. }
  5558. return {
  5559. minimum: minimum,
  5560. maximum: maximum
  5561. };
  5562. };
  5563. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5564. if (bias === void 0) { bias = null; }
  5565. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5566. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5567. if (!stride) {
  5568. stride = 3;
  5569. }
  5570. for (var index = start; index < start + count; index++) {
  5571. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5572. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5573. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5574. }
  5575. if (bias) {
  5576. minimum.x -= minimum.x * bias.x + bias.y;
  5577. minimum.y -= minimum.y * bias.x + bias.y;
  5578. minimum.z -= minimum.z * bias.x + bias.y;
  5579. maximum.x += maximum.x * bias.x + bias.y;
  5580. maximum.y += maximum.y * bias.x + bias.y;
  5581. maximum.z += maximum.z * bias.x + bias.y;
  5582. }
  5583. return {
  5584. minimum: minimum,
  5585. maximum: maximum
  5586. };
  5587. };
  5588. Tools.Vector2ArrayFeeder = function (array) {
  5589. return function (index) {
  5590. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5591. var length = isFloatArray ? array.length / 2 : array.length;
  5592. if (index >= length) {
  5593. return null;
  5594. }
  5595. if (isFloatArray) {
  5596. var fa = array;
  5597. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5598. }
  5599. var a = array;
  5600. return a[index];
  5601. };
  5602. };
  5603. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5604. if (bias === void 0) { bias = null; }
  5605. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5606. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5607. var i = 0;
  5608. var cur = feeder(i++);
  5609. while (cur) {
  5610. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5611. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5612. cur = feeder(i++);
  5613. }
  5614. if (bias) {
  5615. minimum.x -= minimum.x * bias.x + bias.y;
  5616. minimum.y -= minimum.y * bias.x + bias.y;
  5617. maximum.x += maximum.x * bias.x + bias.y;
  5618. maximum.y += maximum.y * bias.x + bias.y;
  5619. }
  5620. return {
  5621. minimum: minimum,
  5622. maximum: maximum
  5623. };
  5624. };
  5625. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5626. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5627. return undefined;
  5628. return Array.isArray(obj) ? obj : [obj];
  5629. };
  5630. // Misc.
  5631. Tools.GetPointerPrefix = function () {
  5632. var eventPrefix = "pointer";
  5633. // Check if pointer events are supported
  5634. if (!window.PointerEvent && !navigator.pointerEnabled) {
  5635. eventPrefix = "mouse";
  5636. }
  5637. return eventPrefix;
  5638. };
  5639. /**
  5640. * @param func - the function to be called
  5641. * @param requester - the object that will request the next frame. Falls back to window.
  5642. */
  5643. Tools.QueueNewFrame = function (func, requester) {
  5644. if (requester === void 0) { requester = window; }
  5645. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  5646. /*if(requester.isPresenting) {
  5647. return;
  5648. } else*/ if (requester.requestAnimationFrame)
  5649. requester.requestAnimationFrame(func);
  5650. else if (requester.msRequestAnimationFrame)
  5651. requester.msRequestAnimationFrame(func);
  5652. else if (requester.webkitRequestAnimationFrame)
  5653. requester.webkitRequestAnimationFrame(func);
  5654. else if (requester.mozRequestAnimationFrame)
  5655. requester.mozRequestAnimationFrame(func);
  5656. else if (requester.oRequestAnimationFrame)
  5657. requester.oRequestAnimationFrame(func);
  5658. else {
  5659. window.setTimeout(func, 16);
  5660. }
  5661. };
  5662. Tools.RequestFullscreen = function (element) {
  5663. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5664. if (!requestFunction)
  5665. return;
  5666. requestFunction.call(element);
  5667. };
  5668. Tools.ExitFullscreen = function () {
  5669. if (document.exitFullscreen) {
  5670. document.exitFullscreen();
  5671. }
  5672. else if (document.mozCancelFullScreen) {
  5673. document.mozCancelFullScreen();
  5674. }
  5675. else if (document.webkitCancelFullScreen) {
  5676. document.webkitCancelFullScreen();
  5677. }
  5678. else if (document.msCancelFullScreen) {
  5679. document.msCancelFullScreen();
  5680. }
  5681. };
  5682. Tools.SetCorsBehavior = function (url, img) {
  5683. if (Tools.CorsBehavior) {
  5684. switch (typeof (Tools.CorsBehavior)) {
  5685. case "function":
  5686. var result = Tools.CorsBehavior(url);
  5687. if (result) {
  5688. img.crossOrigin = result;
  5689. }
  5690. break;
  5691. case "string":
  5692. default:
  5693. img.crossOrigin = Tools.CorsBehavior;
  5694. break;
  5695. }
  5696. }
  5697. };
  5698. // External files
  5699. Tools.CleanUrl = function (url) {
  5700. url = url.replace(/#/mg, "%23");
  5701. return url;
  5702. };
  5703. Tools.LoadImage = function (url, onload, onerror, database) {
  5704. if (url instanceof ArrayBuffer) {
  5705. url = Tools.EncodeArrayBufferTobase64(url);
  5706. }
  5707. url = Tools.CleanUrl(url);
  5708. var img = new Image();
  5709. if (url.substr(0, 5) !== "data:") {
  5710. Tools.SetCorsBehavior(url, img);
  5711. }
  5712. img.onload = function () {
  5713. onload(img);
  5714. };
  5715. img.onerror = function (err) {
  5716. Tools.Error("Error while trying to load image: " + url);
  5717. if (Tools.UseFallbackTexture) {
  5718. img.src = Tools.fallbackTexture;
  5719. onload(img);
  5720. }
  5721. else {
  5722. onerror();
  5723. }
  5724. };
  5725. var noIndexedDB = function () {
  5726. img.src = url;
  5727. };
  5728. var loadFromIndexedDB = function () {
  5729. database.loadImageFromDB(url, img);
  5730. };
  5731. //ANY database to do!
  5732. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  5733. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5734. }
  5735. else {
  5736. if (url.indexOf("file:") !== 0) {
  5737. noIndexedDB();
  5738. }
  5739. else {
  5740. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  5741. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  5742. try {
  5743. var blobURL;
  5744. try {
  5745. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  5746. }
  5747. catch (ex) {
  5748. // Chrome doesn't support oneTimeOnly parameter
  5749. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  5750. }
  5751. img.src = blobURL;
  5752. }
  5753. catch (e) {
  5754. img.src = null;
  5755. }
  5756. }
  5757. else {
  5758. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  5759. img.src = Tools.fallbackTexture;
  5760. }
  5761. }
  5762. }
  5763. return img;
  5764. };
  5765. //ANY
  5766. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  5767. url = Tools.CleanUrl(url);
  5768. var noIndexedDB = function () {
  5769. var request = new XMLHttpRequest();
  5770. var loadUrl = Tools.BaseUrl + url;
  5771. request.open('GET', loadUrl, true);
  5772. if (useArrayBuffer) {
  5773. request.responseType = "arraybuffer";
  5774. }
  5775. request.onprogress = progressCallBack;
  5776. request.onreadystatechange = function () {
  5777. // In case of undefined state in some browsers.
  5778. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  5779. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  5780. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  5781. callback(!useArrayBuffer ? request.responseText : request.response);
  5782. }
  5783. else {
  5784. if (onError) {
  5785. onError(request);
  5786. }
  5787. else {
  5788. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  5789. }
  5790. }
  5791. }
  5792. };
  5793. request.send(null);
  5794. };
  5795. var loadFromIndexedDB = function () {
  5796. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5797. };
  5798. if (url.indexOf("file:") !== -1) {
  5799. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  5800. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  5801. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5802. }
  5803. else {
  5804. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  5805. }
  5806. }
  5807. else {
  5808. // Caching all files
  5809. if (database && database.enableSceneOffline) {
  5810. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5811. }
  5812. else {
  5813. noIndexedDB();
  5814. }
  5815. }
  5816. };
  5817. /**
  5818. * Load a script (identified by an url). When the url returns, the
  5819. * content of this file is added into a new script element, attached to the DOM (body element)
  5820. */
  5821. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5822. var head = document.getElementsByTagName('head')[0];
  5823. var script = document.createElement('script');
  5824. script.type = 'text/javascript';
  5825. script.src = scriptUrl;
  5826. var self = this;
  5827. script.onload = function () {
  5828. if (onSuccess) {
  5829. onSuccess();
  5830. }
  5831. };
  5832. script.onerror = function () {
  5833. if (onError) {
  5834. onError();
  5835. }
  5836. };
  5837. head.appendChild(script);
  5838. };
  5839. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5840. var reader = new FileReader();
  5841. reader.onload = function (e) {
  5842. //target doesn't have result from ts 1.3
  5843. callback(e.target['result']);
  5844. };
  5845. reader.onprogress = progressCallback;
  5846. reader.readAsDataURL(fileToLoad);
  5847. };
  5848. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  5849. var reader = new FileReader();
  5850. reader.onerror = function (e) {
  5851. Tools.Log("Error while reading file: " + fileToLoad.name);
  5852. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  5853. };
  5854. reader.onload = function (e) {
  5855. //target doesn't have result from ts 1.3
  5856. callback(e.target['result']);
  5857. };
  5858. reader.onprogress = progressCallBack;
  5859. if (!useArrayBuffer) {
  5860. // Asynchronous read
  5861. reader.readAsText(fileToLoad);
  5862. }
  5863. else {
  5864. reader.readAsArrayBuffer(fileToLoad);
  5865. }
  5866. };
  5867. //returns a downloadable url to a file content.
  5868. Tools.FileAsURL = function (content) {
  5869. var fileBlob = new Blob([content]);
  5870. var url = window.URL || window.webkitURL;
  5871. var link = url.createObjectURL(fileBlob);
  5872. return link;
  5873. };
  5874. // Misc.
  5875. Tools.Format = function (value, decimals) {
  5876. if (decimals === void 0) { decimals = 2; }
  5877. return value.toFixed(decimals);
  5878. };
  5879. Tools.CheckExtends = function (v, min, max) {
  5880. if (v.x < min.x)
  5881. min.x = v.x;
  5882. if (v.y < min.y)
  5883. min.y = v.y;
  5884. if (v.z < min.z)
  5885. min.z = v.z;
  5886. if (v.x > max.x)
  5887. max.x = v.x;
  5888. if (v.y > max.y)
  5889. max.y = v.y;
  5890. if (v.z > max.z)
  5891. max.z = v.z;
  5892. };
  5893. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5894. for (var prop in source) {
  5895. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5896. continue;
  5897. }
  5898. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5899. continue;
  5900. }
  5901. var sourceValue = source[prop];
  5902. var typeOfSourceValue = typeof sourceValue;
  5903. if (typeOfSourceValue === "function") {
  5904. continue;
  5905. }
  5906. if (typeOfSourceValue === "object") {
  5907. if (sourceValue instanceof Array) {
  5908. destination[prop] = [];
  5909. if (sourceValue.length > 0) {
  5910. if (typeof sourceValue[0] == "object") {
  5911. for (var index = 0; index < sourceValue.length; index++) {
  5912. var clonedValue = cloneValue(sourceValue[index], destination);
  5913. if (destination[prop].indexOf(clonedValue) === -1) {
  5914. destination[prop].push(clonedValue);
  5915. }
  5916. }
  5917. }
  5918. else {
  5919. destination[prop] = sourceValue.slice(0);
  5920. }
  5921. }
  5922. }
  5923. else {
  5924. destination[prop] = cloneValue(sourceValue, destination);
  5925. }
  5926. }
  5927. else {
  5928. destination[prop] = sourceValue;
  5929. }
  5930. }
  5931. };
  5932. Tools.IsEmpty = function (obj) {
  5933. for (var i in obj) {
  5934. return false;
  5935. }
  5936. return true;
  5937. };
  5938. Tools.RegisterTopRootEvents = function (events) {
  5939. for (var index = 0; index < events.length; index++) {
  5940. var event = events[index];
  5941. window.addEventListener(event.name, event.handler, false);
  5942. try {
  5943. if (window.parent) {
  5944. window.parent.addEventListener(event.name, event.handler, false);
  5945. }
  5946. }
  5947. catch (e) {
  5948. // Silently fails...
  5949. }
  5950. }
  5951. };
  5952. Tools.UnregisterTopRootEvents = function (events) {
  5953. for (var index = 0; index < events.length; index++) {
  5954. var event = events[index];
  5955. window.removeEventListener(event.name, event.handler);
  5956. try {
  5957. if (window.parent) {
  5958. window.parent.removeEventListener(event.name, event.handler);
  5959. }
  5960. }
  5961. catch (e) {
  5962. // Silently fails...
  5963. }
  5964. }
  5965. };
  5966. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5967. if (mimeType === void 0) { mimeType = "image/png"; }
  5968. // Read the contents of the framebuffer
  5969. var numberOfChannelsByLine = width * 4;
  5970. var halfHeight = height / 2;
  5971. //Reading datas from WebGL
  5972. var data = engine.readPixels(0, 0, width, height);
  5973. //To flip image on Y axis.
  5974. for (var i = 0; i < halfHeight; i++) {
  5975. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5976. var currentCell = j + i * numberOfChannelsByLine;
  5977. var targetLine = height - i - 1;
  5978. var targetCell = j + targetLine * numberOfChannelsByLine;
  5979. var temp = data[currentCell];
  5980. data[currentCell] = data[targetCell];
  5981. data[targetCell] = temp;
  5982. }
  5983. }
  5984. // Create a 2D canvas to store the result
  5985. if (!screenshotCanvas) {
  5986. screenshotCanvas = document.createElement('canvas');
  5987. }
  5988. screenshotCanvas.width = width;
  5989. screenshotCanvas.height = height;
  5990. var context = screenshotCanvas.getContext('2d');
  5991. // Copy the pixels to a 2D canvas
  5992. var imageData = context.createImageData(width, height);
  5993. var castData = (imageData.data);
  5994. castData.set(data);
  5995. context.putImageData(imageData, 0, 0);
  5996. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5997. };
  5998. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5999. if (mimeType === void 0) { mimeType = "image/png"; }
  6000. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6001. if (successCallback) {
  6002. successCallback(base64Image);
  6003. }
  6004. else {
  6005. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6006. if (("download" in document.createElement("a"))) {
  6007. var a = window.document.createElement("a");
  6008. a.href = base64Image;
  6009. var date = new Date();
  6010. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6011. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6012. window.document.body.appendChild(a);
  6013. a.addEventListener("click", function () {
  6014. a.parentElement.removeChild(a);
  6015. });
  6016. a.click();
  6017. //Or opening a new tab with the image if it is not possible to automatically start download.
  6018. }
  6019. else {
  6020. var newWindow = window.open("");
  6021. var img = newWindow.document.createElement("img");
  6022. img.src = base64Image;
  6023. newWindow.document.body.appendChild(img);
  6024. }
  6025. }
  6026. };
  6027. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6028. if (mimeType === void 0) { mimeType = "image/png"; }
  6029. var width;
  6030. var height;
  6031. // If a precision value is specified
  6032. if (size.precision) {
  6033. width = Math.round(engine.getRenderWidth() * size.precision);
  6034. height = Math.round(width / engine.getAspectRatio(camera));
  6035. }
  6036. else if (size.width && size.height) {
  6037. width = size.width;
  6038. height = size.height;
  6039. }
  6040. else if (size.width && !size.height) {
  6041. width = size.width;
  6042. height = Math.round(width / engine.getAspectRatio(camera));
  6043. }
  6044. else if (size.height && !size.width) {
  6045. height = size.height;
  6046. width = Math.round(height * engine.getAspectRatio(camera));
  6047. }
  6048. else if (!isNaN(size)) {
  6049. height = size;
  6050. width = size;
  6051. }
  6052. else {
  6053. Tools.Error("Invalid 'size' parameter !");
  6054. return;
  6055. }
  6056. if (!screenshotCanvas) {
  6057. screenshotCanvas = document.createElement('canvas');
  6058. }
  6059. screenshotCanvas.width = width;
  6060. screenshotCanvas.height = height;
  6061. var renderContext = screenshotCanvas.getContext("2d");
  6062. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6063. var newWidth = width;
  6064. var newHeight = newWidth / ratio;
  6065. if (newHeight > height) {
  6066. newHeight = height;
  6067. newWidth = newHeight * ratio;
  6068. }
  6069. var offsetX = Math.max(0, width - newWidth) / 2;
  6070. var offsetY = Math.max(0, height - newHeight) / 2;
  6071. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  6072. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6073. };
  6074. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  6075. if (mimeType === void 0) { mimeType = "image/png"; }
  6076. if (samples === void 0) { samples = 1; }
  6077. var width;
  6078. var height;
  6079. //If a precision value is specified
  6080. if (size.precision) {
  6081. width = Math.round(engine.getRenderWidth() * size.precision);
  6082. height = Math.round(width / engine.getAspectRatio(camera));
  6083. size = { width: width, height: height };
  6084. }
  6085. else if (size.width && size.height) {
  6086. width = size.width;
  6087. height = size.height;
  6088. }
  6089. else if (size.width && !size.height) {
  6090. width = size.width;
  6091. height = Math.round(width / engine.getAspectRatio(camera));
  6092. size = { width: width, height: height };
  6093. }
  6094. else if (size.height && !size.width) {
  6095. height = size.height;
  6096. width = Math.round(height * engine.getAspectRatio(camera));
  6097. size = { width: width, height: height };
  6098. }
  6099. else if (!isNaN(size)) {
  6100. height = size;
  6101. width = size;
  6102. }
  6103. else {
  6104. Tools.Error("Invalid 'size' parameter !");
  6105. return;
  6106. }
  6107. var scene = camera.getScene();
  6108. var previousCamera = null;
  6109. if (scene.activeCamera !== camera) {
  6110. previousCamera = scene.activeCamera;
  6111. scene.activeCamera = camera;
  6112. }
  6113. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6114. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6115. texture.renderList = null;
  6116. texture.samples = samples;
  6117. texture.onAfterRenderObservable.add(function () {
  6118. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6119. });
  6120. scene.incrementRenderId();
  6121. scene.resetCachedMaterial();
  6122. texture.render(true);
  6123. texture.dispose();
  6124. if (previousCamera) {
  6125. scene.activeCamera = previousCamera;
  6126. }
  6127. camera.getProjectionMatrix(true); // Force cache refresh;
  6128. };
  6129. // XHR response validator for local file scenario
  6130. Tools.ValidateXHRData = function (xhr, dataType) {
  6131. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6132. if (dataType === void 0) { dataType = 7; }
  6133. try {
  6134. if (dataType & 1) {
  6135. if (xhr.responseText && xhr.responseText.length > 0) {
  6136. return true;
  6137. }
  6138. else if (dataType === 1) {
  6139. return false;
  6140. }
  6141. }
  6142. if (dataType & 2) {
  6143. // Check header width and height since there is no "TGA" magic number
  6144. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6145. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6146. return true;
  6147. }
  6148. else if (dataType === 2) {
  6149. return false;
  6150. }
  6151. }
  6152. if (dataType & 4) {
  6153. // Check for the "DDS" magic number
  6154. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6155. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6156. return true;
  6157. }
  6158. else {
  6159. return false;
  6160. }
  6161. }
  6162. }
  6163. catch (e) {
  6164. // Global protection
  6165. }
  6166. return false;
  6167. };
  6168. /**
  6169. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6170. * Be aware Math.random() could cause collisions, but:
  6171. * "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"
  6172. */
  6173. Tools.RandomId = function () {
  6174. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6175. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6176. return v.toString(16);
  6177. });
  6178. };
  6179. Object.defineProperty(Tools, "NoneLogLevel", {
  6180. get: function () {
  6181. return Tools._NoneLogLevel;
  6182. },
  6183. enumerable: true,
  6184. configurable: true
  6185. });
  6186. Object.defineProperty(Tools, "MessageLogLevel", {
  6187. get: function () {
  6188. return Tools._MessageLogLevel;
  6189. },
  6190. enumerable: true,
  6191. configurable: true
  6192. });
  6193. Object.defineProperty(Tools, "WarningLogLevel", {
  6194. get: function () {
  6195. return Tools._WarningLogLevel;
  6196. },
  6197. enumerable: true,
  6198. configurable: true
  6199. });
  6200. Object.defineProperty(Tools, "ErrorLogLevel", {
  6201. get: function () {
  6202. return Tools._ErrorLogLevel;
  6203. },
  6204. enumerable: true,
  6205. configurable: true
  6206. });
  6207. Object.defineProperty(Tools, "AllLogLevel", {
  6208. get: function () {
  6209. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6210. },
  6211. enumerable: true,
  6212. configurable: true
  6213. });
  6214. Tools._AddLogEntry = function (entry) {
  6215. Tools._LogCache = entry + Tools._LogCache;
  6216. if (Tools.OnNewCacheEntry) {
  6217. Tools.OnNewCacheEntry(entry);
  6218. }
  6219. };
  6220. Tools._FormatMessage = function (message) {
  6221. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6222. var date = new Date();
  6223. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6224. };
  6225. Tools._LogDisabled = function (message) {
  6226. // nothing to do
  6227. };
  6228. Tools._LogEnabled = function (message) {
  6229. var formattedMessage = Tools._FormatMessage(message);
  6230. console.log("BJS - " + formattedMessage);
  6231. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6232. Tools._AddLogEntry(entry);
  6233. };
  6234. Tools._WarnDisabled = function (message) {
  6235. // nothing to do
  6236. };
  6237. Tools._WarnEnabled = function (message) {
  6238. var formattedMessage = Tools._FormatMessage(message);
  6239. console.warn("BJS - " + formattedMessage);
  6240. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6241. Tools._AddLogEntry(entry);
  6242. };
  6243. Tools._ErrorDisabled = function (message) {
  6244. // nothing to do
  6245. };
  6246. Tools._ErrorEnabled = function (message) {
  6247. Tools.errorsCount++;
  6248. var formattedMessage = Tools._FormatMessage(message);
  6249. console.error("BJS - " + formattedMessage);
  6250. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6251. Tools._AddLogEntry(entry);
  6252. };
  6253. Object.defineProperty(Tools, "LogCache", {
  6254. get: function () {
  6255. return Tools._LogCache;
  6256. },
  6257. enumerable: true,
  6258. configurable: true
  6259. });
  6260. Tools.ClearLogCache = function () {
  6261. Tools._LogCache = "";
  6262. Tools.errorsCount = 0;
  6263. };
  6264. Object.defineProperty(Tools, "LogLevels", {
  6265. set: function (level) {
  6266. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6267. Tools.Log = Tools._LogEnabled;
  6268. }
  6269. else {
  6270. Tools.Log = Tools._LogDisabled;
  6271. }
  6272. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6273. Tools.Warn = Tools._WarnEnabled;
  6274. }
  6275. else {
  6276. Tools.Warn = Tools._WarnDisabled;
  6277. }
  6278. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6279. Tools.Error = Tools._ErrorEnabled;
  6280. }
  6281. else {
  6282. Tools.Error = Tools._ErrorDisabled;
  6283. }
  6284. },
  6285. enumerable: true,
  6286. configurable: true
  6287. });
  6288. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6289. get: function () {
  6290. return Tools._PerformanceNoneLogLevel;
  6291. },
  6292. enumerable: true,
  6293. configurable: true
  6294. });
  6295. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6296. get: function () {
  6297. return Tools._PerformanceUserMarkLogLevel;
  6298. },
  6299. enumerable: true,
  6300. configurable: true
  6301. });
  6302. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6303. get: function () {
  6304. return Tools._PerformanceConsoleLogLevel;
  6305. },
  6306. enumerable: true,
  6307. configurable: true
  6308. });
  6309. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6310. set: function (level) {
  6311. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6312. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6313. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6314. return;
  6315. }
  6316. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6317. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6318. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6319. return;
  6320. }
  6321. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6322. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6323. },
  6324. enumerable: true,
  6325. configurable: true
  6326. });
  6327. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6328. };
  6329. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6330. };
  6331. Tools._StartUserMark = function (counterName, condition) {
  6332. if (condition === void 0) { condition = true; }
  6333. if (!condition || !Tools._performance.mark) {
  6334. return;
  6335. }
  6336. Tools._performance.mark(counterName + "-Begin");
  6337. };
  6338. Tools._EndUserMark = function (counterName, condition) {
  6339. if (condition === void 0) { condition = true; }
  6340. if (!condition || !Tools._performance.mark) {
  6341. return;
  6342. }
  6343. Tools._performance.mark(counterName + "-End");
  6344. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6345. };
  6346. Tools._StartPerformanceConsole = function (counterName, condition) {
  6347. if (condition === void 0) { condition = true; }
  6348. if (!condition) {
  6349. return;
  6350. }
  6351. Tools._StartUserMark(counterName, condition);
  6352. if (console.time) {
  6353. console.time(counterName);
  6354. }
  6355. };
  6356. Tools._EndPerformanceConsole = function (counterName, condition) {
  6357. if (condition === void 0) { condition = true; }
  6358. if (!condition) {
  6359. return;
  6360. }
  6361. Tools._EndUserMark(counterName, condition);
  6362. if (console.time) {
  6363. console.timeEnd(counterName);
  6364. }
  6365. };
  6366. Object.defineProperty(Tools, "Now", {
  6367. get: function () {
  6368. if (window.performance && window.performance.now) {
  6369. return window.performance.now();
  6370. }
  6371. return new Date().getTime();
  6372. },
  6373. enumerable: true,
  6374. configurable: true
  6375. });
  6376. /**
  6377. * This method will return the name of the class used to create the instance of the given object.
  6378. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6379. * @param object the object to get the class name from
  6380. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6381. */
  6382. Tools.GetClassName = function (object, isType) {
  6383. if (isType === void 0) { isType = false; }
  6384. var name = null;
  6385. if (!isType && object.getClassName) {
  6386. name = object.getClassName();
  6387. }
  6388. else {
  6389. if (object instanceof Object) {
  6390. var classObj = isType ? object : Object.getPrototypeOf(object);
  6391. name = classObj.constructor["__bjsclassName__"];
  6392. }
  6393. if (!name) {
  6394. name = typeof object;
  6395. }
  6396. }
  6397. return name;
  6398. };
  6399. Tools.first = function (array, predicate) {
  6400. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6401. var el = array_1[_i];
  6402. if (predicate(el)) {
  6403. return el;
  6404. }
  6405. }
  6406. };
  6407. /**
  6408. * This method will return the name of the full name of the class, including its owning module (if any).
  6409. * 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).
  6410. * @param object the object to get the class name from
  6411. * @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.
  6412. */
  6413. Tools.getFullClassName = function (object, isType) {
  6414. if (isType === void 0) { isType = false; }
  6415. var className = null;
  6416. var moduleName = null;
  6417. if (!isType && object.getClassName) {
  6418. className = object.getClassName();
  6419. }
  6420. else {
  6421. if (object instanceof Object) {
  6422. var classObj = isType ? object : Object.getPrototypeOf(object);
  6423. className = classObj.constructor["__bjsclassName__"];
  6424. moduleName = classObj.constructor["__bjsmoduleName__"];
  6425. }
  6426. if (!className) {
  6427. className = typeof object;
  6428. }
  6429. }
  6430. if (!className) {
  6431. return null;
  6432. }
  6433. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6434. };
  6435. /**
  6436. * 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.
  6437. * @param array
  6438. */
  6439. Tools.arrayOrStringFeeder = function (array) {
  6440. return function (index) {
  6441. if (index >= array.length) {
  6442. return null;
  6443. }
  6444. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6445. if (val && val.getHashCode) {
  6446. val = val.getHashCode();
  6447. }
  6448. if (typeof val === "string") {
  6449. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6450. }
  6451. return val;
  6452. };
  6453. };
  6454. /**
  6455. * Compute the hashCode of a stream of number
  6456. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6457. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6458. * @return the hash code computed
  6459. */
  6460. Tools.hashCodeFromStream = function (feeder) {
  6461. // Based from here: http://stackoverflow.com/a/7616484/802124
  6462. var hash = 0;
  6463. var index = 0;
  6464. var chr = feeder(index++);
  6465. while (chr != null) {
  6466. hash = ((hash << 5) - hash) + chr;
  6467. hash |= 0; // Convert to 32bit integer
  6468. chr = feeder(index++);
  6469. }
  6470. return hash;
  6471. };
  6472. return Tools;
  6473. }());
  6474. Tools.BaseUrl = "";
  6475. Tools.CorsBehavior = "anonymous";
  6476. Tools.UseFallbackTexture = true;
  6477. // Used in case of a texture loading problem
  6478. 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";
  6479. // Logs
  6480. Tools._NoneLogLevel = 0;
  6481. Tools._MessageLogLevel = 1;
  6482. Tools._WarningLogLevel = 2;
  6483. Tools._ErrorLogLevel = 4;
  6484. Tools._LogCache = "";
  6485. Tools.errorsCount = 0;
  6486. Tools.Log = Tools._LogEnabled;
  6487. Tools.Warn = Tools._WarnEnabled;
  6488. Tools.Error = Tools._ErrorEnabled;
  6489. // Performances
  6490. Tools._PerformanceNoneLogLevel = 0;
  6491. Tools._PerformanceUserMarkLogLevel = 1;
  6492. Tools._PerformanceConsoleLogLevel = 2;
  6493. Tools._performance = window.performance;
  6494. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6495. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6496. BABYLON.Tools = Tools;
  6497. /**
  6498. * This class is used to track a performance counter which is number based.
  6499. * The user has access to many properties which give statistics of different nature
  6500. *
  6501. * The implementer can track two kinds of Performance Counter: time and count
  6502. * 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.
  6503. * 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.
  6504. */
  6505. var PerfCounter = (function () {
  6506. function PerfCounter() {
  6507. this._startMonitoringTime = 0;
  6508. this._min = 0;
  6509. this._max = 0;
  6510. this._average = 0;
  6511. this._lastSecAverage = 0;
  6512. this._current = 0;
  6513. this._totalValueCount = 0;
  6514. this._totalAccumulated = 0;
  6515. this._lastSecAccumulated = 0;
  6516. this._lastSecTime = 0;
  6517. this._lastSecValueCount = 0;
  6518. }
  6519. Object.defineProperty(PerfCounter.prototype, "min", {
  6520. /**
  6521. * Returns the smallest value ever
  6522. */
  6523. get: function () {
  6524. return this._min;
  6525. },
  6526. enumerable: true,
  6527. configurable: true
  6528. });
  6529. Object.defineProperty(PerfCounter.prototype, "max", {
  6530. /**
  6531. * Returns the biggest value ever
  6532. */
  6533. get: function () {
  6534. return this._max;
  6535. },
  6536. enumerable: true,
  6537. configurable: true
  6538. });
  6539. Object.defineProperty(PerfCounter.prototype, "average", {
  6540. /**
  6541. * Returns the average value since the performance counter is running
  6542. */
  6543. get: function () {
  6544. return this._average;
  6545. },
  6546. enumerable: true,
  6547. configurable: true
  6548. });
  6549. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6550. /**
  6551. * Returns the average value of the last second the counter was monitored
  6552. */
  6553. get: function () {
  6554. return this._lastSecAverage;
  6555. },
  6556. enumerable: true,
  6557. configurable: true
  6558. });
  6559. Object.defineProperty(PerfCounter.prototype, "current", {
  6560. /**
  6561. * Returns the current value
  6562. */
  6563. get: function () {
  6564. return this._current;
  6565. },
  6566. enumerable: true,
  6567. configurable: true
  6568. });
  6569. Object.defineProperty(PerfCounter.prototype, "total", {
  6570. get: function () {
  6571. return this._totalAccumulated;
  6572. },
  6573. enumerable: true,
  6574. configurable: true
  6575. });
  6576. /**
  6577. * Call this method to start monitoring a new frame.
  6578. * 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.
  6579. */
  6580. PerfCounter.prototype.fetchNewFrame = function () {
  6581. this._totalValueCount++;
  6582. this._current = 0;
  6583. this._lastSecValueCount++;
  6584. };
  6585. /**
  6586. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6587. * @param newCount the count value to add to the monitored count
  6588. * @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.
  6589. */
  6590. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6591. if (!PerfCounter.Enabled) {
  6592. return;
  6593. }
  6594. this._current += newCount;
  6595. if (fetchResult) {
  6596. this._fetchResult();
  6597. }
  6598. };
  6599. /**
  6600. * Start monitoring this performance counter
  6601. */
  6602. PerfCounter.prototype.beginMonitoring = function () {
  6603. if (!PerfCounter.Enabled) {
  6604. return;
  6605. }
  6606. this._startMonitoringTime = Tools.Now;
  6607. };
  6608. /**
  6609. * Compute the time lapsed since the previous beginMonitoring() call.
  6610. * @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
  6611. */
  6612. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6613. if (newFrame === void 0) { newFrame = true; }
  6614. if (!PerfCounter.Enabled) {
  6615. return;
  6616. }
  6617. if (newFrame) {
  6618. this.fetchNewFrame();
  6619. }
  6620. var currentTime = Tools.Now;
  6621. this._current = currentTime - this._startMonitoringTime;
  6622. if (newFrame) {
  6623. this._fetchResult();
  6624. }
  6625. };
  6626. PerfCounter.prototype._fetchResult = function () {
  6627. this._totalAccumulated += this._current;
  6628. this._lastSecAccumulated += this._current;
  6629. // Min/Max update
  6630. this._min = Math.min(this._min, this._current);
  6631. this._max = Math.max(this._max, this._current);
  6632. this._average = this._totalAccumulated / this._totalValueCount;
  6633. // Reset last sec?
  6634. var now = Tools.Now;
  6635. if ((now - this._lastSecTime) > 1000) {
  6636. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6637. this._lastSecTime = now;
  6638. this._lastSecAccumulated = 0;
  6639. this._lastSecValueCount = 0;
  6640. }
  6641. };
  6642. return PerfCounter;
  6643. }());
  6644. PerfCounter.Enabled = true;
  6645. BABYLON.PerfCounter = PerfCounter;
  6646. /**
  6647. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6648. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6649. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6650. * @param name The name of the class, case should be preserved
  6651. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6652. */
  6653. function className(name, module) {
  6654. return function (target) {
  6655. target["__bjsclassName__"] = name;
  6656. target["__bjsmoduleName__"] = (module != null) ? module : null;
  6657. };
  6658. }
  6659. BABYLON.className = className;
  6660. /**
  6661. * An implementation of a loop for asynchronous functions.
  6662. */
  6663. var AsyncLoop = (function () {
  6664. /**
  6665. * Constroctor.
  6666. * @param iterations the number of iterations.
  6667. * @param _fn the function to run each iteration
  6668. * @param _successCallback the callback that will be called upon succesful execution
  6669. * @param offset starting offset.
  6670. */
  6671. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  6672. if (offset === void 0) { offset = 0; }
  6673. this.iterations = iterations;
  6674. this._fn = _fn;
  6675. this._successCallback = _successCallback;
  6676. this.index = offset - 1;
  6677. this._done = false;
  6678. }
  6679. /**
  6680. * Execute the next iteration. Must be called after the last iteration was finished.
  6681. */
  6682. AsyncLoop.prototype.executeNext = function () {
  6683. if (!this._done) {
  6684. if (this.index + 1 < this.iterations) {
  6685. ++this.index;
  6686. this._fn(this);
  6687. }
  6688. else {
  6689. this.breakLoop();
  6690. }
  6691. }
  6692. };
  6693. /**
  6694. * Break the loop and run the success callback.
  6695. */
  6696. AsyncLoop.prototype.breakLoop = function () {
  6697. this._done = true;
  6698. this._successCallback();
  6699. };
  6700. /**
  6701. * Helper function
  6702. */
  6703. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  6704. if (offset === void 0) { offset = 0; }
  6705. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  6706. loop.executeNext();
  6707. return loop;
  6708. };
  6709. /**
  6710. * A for-loop that will run a given number of iterations synchronous and the rest async.
  6711. * @param iterations total number of iterations
  6712. * @param syncedIterations number of synchronous iterations in each async iteration.
  6713. * @param fn the function to call each iteration.
  6714. * @param callback a success call back that will be called when iterating stops.
  6715. * @param breakFunction a break condition (optional)
  6716. * @param timeout timeout settings for the setTimeout function. default - 0.
  6717. * @constructor
  6718. */
  6719. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  6720. if (timeout === void 0) { timeout = 0; }
  6721. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  6722. if (breakFunction && breakFunction())
  6723. loop.breakLoop();
  6724. else {
  6725. setTimeout(function () {
  6726. for (var i = 0; i < syncedIterations; ++i) {
  6727. var iteration = (loop.index * syncedIterations) + i;
  6728. if (iteration >= iterations)
  6729. break;
  6730. fn(iteration);
  6731. if (breakFunction && breakFunction()) {
  6732. loop.breakLoop();
  6733. break;
  6734. }
  6735. }
  6736. loop.executeNext();
  6737. }, timeout);
  6738. }
  6739. }, callback);
  6740. };
  6741. return AsyncLoop;
  6742. }());
  6743. BABYLON.AsyncLoop = AsyncLoop;
  6744. })(BABYLON || (BABYLON = {}));
  6745. //# sourceMappingURL=babylon.tools.js.map
  6746. var BABYLON;
  6747. (function (BABYLON) {
  6748. var Internals;
  6749. (function (Internals) {
  6750. var _AlphaState = (function () {
  6751. /**
  6752. * Initializes the state.
  6753. */
  6754. function _AlphaState() {
  6755. this._isAlphaBlendDirty = false;
  6756. this._isBlendFunctionParametersDirty = false;
  6757. this._isBlendEquationParametersDirty = false;
  6758. this._isBlendConstantsDirty = false;
  6759. this._alphaBlend = false;
  6760. this._blendFunctionParameters = new Array(4);
  6761. this._blendEquationParameters = new Array(2);
  6762. this._blendConstants = new Array(4);
  6763. this.reset();
  6764. }
  6765. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  6766. get: function () {
  6767. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  6768. },
  6769. enumerable: true,
  6770. configurable: true
  6771. });
  6772. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  6773. get: function () {
  6774. return this._alphaBlend;
  6775. },
  6776. set: function (value) {
  6777. if (this._alphaBlend === value) {
  6778. return;
  6779. }
  6780. this._alphaBlend = value;
  6781. this._isAlphaBlendDirty = true;
  6782. },
  6783. enumerable: true,
  6784. configurable: true
  6785. });
  6786. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  6787. if (this._blendConstants[0] === r &&
  6788. this._blendConstants[1] === g &&
  6789. this._blendConstants[2] === b &&
  6790. this._blendConstants[3] === a) {
  6791. return;
  6792. }
  6793. this._blendConstants[0] = r;
  6794. this._blendConstants[1] = g;
  6795. this._blendConstants[2] = b;
  6796. this._blendConstants[3] = a;
  6797. this._isBlendConstantsDirty = true;
  6798. };
  6799. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  6800. if (this._blendFunctionParameters[0] === value0 &&
  6801. this._blendFunctionParameters[1] === value1 &&
  6802. this._blendFunctionParameters[2] === value2 &&
  6803. this._blendFunctionParameters[3] === value3) {
  6804. return;
  6805. }
  6806. this._blendFunctionParameters[0] = value0;
  6807. this._blendFunctionParameters[1] = value1;
  6808. this._blendFunctionParameters[2] = value2;
  6809. this._blendFunctionParameters[3] = value3;
  6810. this._isBlendFunctionParametersDirty = true;
  6811. };
  6812. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  6813. if (this._blendEquationParameters[0] === rgb &&
  6814. this._blendEquationParameters[1] === alpha) {
  6815. return;
  6816. }
  6817. this._blendEquationParameters[0] = rgb;
  6818. this._blendEquationParameters[1] = alpha;
  6819. this._isBlendEquationParametersDirty = true;
  6820. };
  6821. _AlphaState.prototype.reset = function () {
  6822. this._alphaBlend = false;
  6823. this._blendFunctionParameters[0] = null;
  6824. this._blendFunctionParameters[1] = null;
  6825. this._blendFunctionParameters[2] = null;
  6826. this._blendFunctionParameters[3] = null;
  6827. this._blendEquationParameters[0] = null;
  6828. this._blendEquationParameters[1] = null;
  6829. this._blendConstants[0] = null;
  6830. this._blendConstants[1] = null;
  6831. this._blendConstants[2] = null;
  6832. this._blendConstants[3] = null;
  6833. this._isAlphaBlendDirty = true;
  6834. this._isBlendFunctionParametersDirty = false;
  6835. this._isBlendEquationParametersDirty = false;
  6836. this._isBlendConstantsDirty = false;
  6837. };
  6838. _AlphaState.prototype.apply = function (gl) {
  6839. if (!this.isDirty) {
  6840. return;
  6841. }
  6842. // Alpha blend
  6843. if (this._isAlphaBlendDirty) {
  6844. if (this._alphaBlend) {
  6845. gl.enable(gl.BLEND);
  6846. }
  6847. else {
  6848. gl.disable(gl.BLEND);
  6849. }
  6850. this._isAlphaBlendDirty = false;
  6851. }
  6852. // Alpha function
  6853. if (this._isBlendFunctionParametersDirty) {
  6854. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  6855. this._isBlendFunctionParametersDirty = false;
  6856. }
  6857. // Alpha equation
  6858. if (this._isBlendEquationParametersDirty) {
  6859. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  6860. this._isBlendEquationParametersDirty = false;
  6861. }
  6862. // Constants
  6863. if (this._isBlendConstantsDirty) {
  6864. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  6865. this._isBlendConstantsDirty = false;
  6866. }
  6867. };
  6868. return _AlphaState;
  6869. }());
  6870. Internals._AlphaState = _AlphaState;
  6871. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6872. })(BABYLON || (BABYLON = {}));
  6873. //# sourceMappingURL=babylon.alphaCullingState.js.map
  6874. var BABYLON;
  6875. (function (BABYLON) {
  6876. var Internals;
  6877. (function (Internals) {
  6878. var _DepthCullingState = (function () {
  6879. /**
  6880. * Initializes the state.
  6881. */
  6882. function _DepthCullingState() {
  6883. this._isDepthTestDirty = false;
  6884. this._isDepthMaskDirty = false;
  6885. this._isDepthFuncDirty = false;
  6886. this._isCullFaceDirty = false;
  6887. this._isCullDirty = false;
  6888. this._isZOffsetDirty = false;
  6889. this.reset();
  6890. }
  6891. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  6892. get: function () {
  6893. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  6894. },
  6895. enumerable: true,
  6896. configurable: true
  6897. });
  6898. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  6899. get: function () {
  6900. return this._zOffset;
  6901. },
  6902. set: function (value) {
  6903. if (this._zOffset === value) {
  6904. return;
  6905. }
  6906. this._zOffset = value;
  6907. this._isZOffsetDirty = true;
  6908. },
  6909. enumerable: true,
  6910. configurable: true
  6911. });
  6912. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  6913. get: function () {
  6914. return this._cullFace;
  6915. },
  6916. set: function (value) {
  6917. if (this._cullFace === value) {
  6918. return;
  6919. }
  6920. this._cullFace = value;
  6921. this._isCullFaceDirty = true;
  6922. },
  6923. enumerable: true,
  6924. configurable: true
  6925. });
  6926. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6927. get: function () {
  6928. return this._cull;
  6929. },
  6930. set: function (value) {
  6931. if (this._cull === value) {
  6932. return;
  6933. }
  6934. this._cull = value;
  6935. this._isCullDirty = true;
  6936. },
  6937. enumerable: true,
  6938. configurable: true
  6939. });
  6940. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6941. get: function () {
  6942. return this._depthFunc;
  6943. },
  6944. set: function (value) {
  6945. if (this._depthFunc === value) {
  6946. return;
  6947. }
  6948. this._depthFunc = value;
  6949. this._isDepthFuncDirty = true;
  6950. },
  6951. enumerable: true,
  6952. configurable: true
  6953. });
  6954. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6955. get: function () {
  6956. return this._depthMask;
  6957. },
  6958. set: function (value) {
  6959. if (this._depthMask === value) {
  6960. return;
  6961. }
  6962. this._depthMask = value;
  6963. this._isDepthMaskDirty = true;
  6964. },
  6965. enumerable: true,
  6966. configurable: true
  6967. });
  6968. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6969. get: function () {
  6970. return this._depthTest;
  6971. },
  6972. set: function (value) {
  6973. if (this._depthTest === value) {
  6974. return;
  6975. }
  6976. this._depthTest = value;
  6977. this._isDepthTestDirty = true;
  6978. },
  6979. enumerable: true,
  6980. configurable: true
  6981. });
  6982. _DepthCullingState.prototype.reset = function () {
  6983. this._depthMask = true;
  6984. this._depthTest = true;
  6985. this._depthFunc = null;
  6986. this._cullFace = null;
  6987. this._cull = null;
  6988. this._zOffset = 0;
  6989. this._isDepthTestDirty = true;
  6990. this._isDepthMaskDirty = true;
  6991. this._isDepthFuncDirty = false;
  6992. this._isCullFaceDirty = false;
  6993. this._isCullDirty = false;
  6994. this._isZOffsetDirty = false;
  6995. };
  6996. _DepthCullingState.prototype.apply = function (gl) {
  6997. if (!this.isDirty) {
  6998. return;
  6999. }
  7000. // Cull
  7001. if (this._isCullDirty) {
  7002. if (this.cull) {
  7003. gl.enable(gl.CULL_FACE);
  7004. }
  7005. else {
  7006. gl.disable(gl.CULL_FACE);
  7007. }
  7008. this._isCullDirty = false;
  7009. }
  7010. // Cull face
  7011. if (this._isCullFaceDirty) {
  7012. gl.cullFace(this.cullFace);
  7013. this._isCullFaceDirty = false;
  7014. }
  7015. // Depth mask
  7016. if (this._isDepthMaskDirty) {
  7017. gl.depthMask(this.depthMask);
  7018. this._isDepthMaskDirty = false;
  7019. }
  7020. // Depth test
  7021. if (this._isDepthTestDirty) {
  7022. if (this.depthTest) {
  7023. gl.enable(gl.DEPTH_TEST);
  7024. }
  7025. else {
  7026. gl.disable(gl.DEPTH_TEST);
  7027. }
  7028. this._isDepthTestDirty = false;
  7029. }
  7030. // Depth func
  7031. if (this._isDepthFuncDirty) {
  7032. gl.depthFunc(this.depthFunc);
  7033. this._isDepthFuncDirty = false;
  7034. }
  7035. // zOffset
  7036. if (this._isZOffsetDirty) {
  7037. if (this.zOffset) {
  7038. gl.enable(gl.POLYGON_OFFSET_FILL);
  7039. gl.polygonOffset(this.zOffset, 0);
  7040. }
  7041. else {
  7042. gl.disable(gl.POLYGON_OFFSET_FILL);
  7043. }
  7044. this._isZOffsetDirty = false;
  7045. }
  7046. };
  7047. return _DepthCullingState;
  7048. }());
  7049. Internals._DepthCullingState = _DepthCullingState;
  7050. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7051. })(BABYLON || (BABYLON = {}));
  7052. //# sourceMappingURL=babylon.depthCullingState.js.map
  7053. var BABYLON;
  7054. (function (BABYLON) {
  7055. var Internals;
  7056. (function (Internals) {
  7057. var _StencilState = (function () {
  7058. function _StencilState() {
  7059. this._isStencilTestDirty = false;
  7060. this._isStencilMaskDirty = false;
  7061. this._isStencilFuncDirty = false;
  7062. this._isStencilOpDirty = false;
  7063. this.reset();
  7064. }
  7065. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7066. get: function () {
  7067. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7068. },
  7069. enumerable: true,
  7070. configurable: true
  7071. });
  7072. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7073. get: function () {
  7074. return this._stencilFunc;
  7075. },
  7076. set: function (value) {
  7077. if (this._stencilFunc === value) {
  7078. return;
  7079. }
  7080. this._stencilFunc = value;
  7081. this._isStencilFuncDirty = true;
  7082. },
  7083. enumerable: true,
  7084. configurable: true
  7085. });
  7086. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7087. get: function () {
  7088. return this._stencilFuncRef;
  7089. },
  7090. set: function (value) {
  7091. if (this._stencilFuncRef === value) {
  7092. return;
  7093. }
  7094. this._stencilFuncRef = value;
  7095. this._isStencilFuncDirty = true;
  7096. },
  7097. enumerable: true,
  7098. configurable: true
  7099. });
  7100. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7101. get: function () {
  7102. return this._stencilFuncMask;
  7103. },
  7104. set: function (value) {
  7105. if (this._stencilFuncMask === value) {
  7106. return;
  7107. }
  7108. this._stencilFuncMask = value;
  7109. this._isStencilFuncDirty = true;
  7110. },
  7111. enumerable: true,
  7112. configurable: true
  7113. });
  7114. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7115. get: function () {
  7116. return this._stencilOpStencilFail;
  7117. },
  7118. set: function (value) {
  7119. if (this._stencilOpStencilFail === value) {
  7120. return;
  7121. }
  7122. this._stencilOpStencilFail = value;
  7123. this._isStencilOpDirty = true;
  7124. },
  7125. enumerable: true,
  7126. configurable: true
  7127. });
  7128. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7129. get: function () {
  7130. return this._stencilOpDepthFail;
  7131. },
  7132. set: function (value) {
  7133. if (this._stencilOpDepthFail === value) {
  7134. return;
  7135. }
  7136. this._stencilOpDepthFail = value;
  7137. this._isStencilOpDirty = true;
  7138. },
  7139. enumerable: true,
  7140. configurable: true
  7141. });
  7142. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7143. get: function () {
  7144. return this._stencilOpStencilDepthPass;
  7145. },
  7146. set: function (value) {
  7147. if (this._stencilOpStencilDepthPass === value) {
  7148. return;
  7149. }
  7150. this._stencilOpStencilDepthPass = value;
  7151. this._isStencilOpDirty = true;
  7152. },
  7153. enumerable: true,
  7154. configurable: true
  7155. });
  7156. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7157. get: function () {
  7158. return this._stencilMask;
  7159. },
  7160. set: function (value) {
  7161. if (this._stencilMask === value) {
  7162. return;
  7163. }
  7164. this._stencilMask = value;
  7165. this._isStencilMaskDirty = true;
  7166. },
  7167. enumerable: true,
  7168. configurable: true
  7169. });
  7170. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7171. get: function () {
  7172. return this._stencilTest;
  7173. },
  7174. set: function (value) {
  7175. if (this._stencilTest === value) {
  7176. return;
  7177. }
  7178. this._stencilTest = value;
  7179. this._isStencilTestDirty = true;
  7180. },
  7181. enumerable: true,
  7182. configurable: true
  7183. });
  7184. _StencilState.prototype.reset = function () {
  7185. this._stencilTest = false;
  7186. this._stencilMask = 0xFF;
  7187. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7188. this._stencilFuncRef = 1;
  7189. this._stencilFuncMask = 0xFF;
  7190. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7191. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7192. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7193. this._isStencilTestDirty = true;
  7194. this._isStencilMaskDirty = true;
  7195. this._isStencilFuncDirty = true;
  7196. this._isStencilOpDirty = true;
  7197. };
  7198. _StencilState.prototype.apply = function (gl) {
  7199. if (!this.isDirty) {
  7200. return;
  7201. }
  7202. // Stencil test
  7203. if (this._isStencilTestDirty) {
  7204. if (this.stencilTest) {
  7205. gl.enable(gl.STENCIL_TEST);
  7206. }
  7207. else {
  7208. gl.disable(gl.STENCIL_TEST);
  7209. }
  7210. this._isStencilTestDirty = false;
  7211. }
  7212. // Stencil mask
  7213. if (this._isStencilMaskDirty) {
  7214. gl.stencilMask(this.stencilMask);
  7215. this._isStencilMaskDirty = false;
  7216. }
  7217. // Stencil func
  7218. if (this._isStencilFuncDirty) {
  7219. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7220. this._isStencilFuncDirty = false;
  7221. }
  7222. // Stencil op
  7223. if (this._isStencilOpDirty) {
  7224. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7225. this._isStencilOpDirty = false;
  7226. }
  7227. };
  7228. return _StencilState;
  7229. }());
  7230. Internals._StencilState = _StencilState;
  7231. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7232. })(BABYLON || (BABYLON = {}));
  7233. //# sourceMappingURL=babylon.stencilState.js.map
  7234. var BABYLON;
  7235. (function (BABYLON) {
  7236. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7237. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7238. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7239. gl.compileShader(shader);
  7240. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7241. throw new Error(gl.getShaderInfoLog(shader));
  7242. }
  7243. return shader;
  7244. };
  7245. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7246. var magFilter = gl.NEAREST;
  7247. var minFilter = gl.NEAREST;
  7248. switch (samplingMode) {
  7249. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7250. magFilter = gl.LINEAR;
  7251. if (generateMipMaps) {
  7252. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7253. }
  7254. else {
  7255. minFilter = gl.LINEAR;
  7256. }
  7257. break;
  7258. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7259. magFilter = gl.LINEAR;
  7260. if (generateMipMaps) {
  7261. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7262. }
  7263. else {
  7264. minFilter = gl.LINEAR;
  7265. }
  7266. break;
  7267. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7268. magFilter = gl.NEAREST;
  7269. if (generateMipMaps) {
  7270. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7271. }
  7272. else {
  7273. minFilter = gl.NEAREST;
  7274. }
  7275. break;
  7276. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7277. magFilter = gl.NEAREST;
  7278. if (generateMipMaps) {
  7279. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7280. }
  7281. else {
  7282. minFilter = gl.NEAREST;
  7283. }
  7284. break;
  7285. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7286. magFilter = gl.NEAREST;
  7287. if (generateMipMaps) {
  7288. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7289. }
  7290. else {
  7291. minFilter = gl.LINEAR;
  7292. }
  7293. break;
  7294. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7295. magFilter = gl.NEAREST;
  7296. if (generateMipMaps) {
  7297. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7298. }
  7299. else {
  7300. minFilter = gl.LINEAR;
  7301. }
  7302. break;
  7303. case BABYLON.Texture.NEAREST_LINEAR:
  7304. magFilter = gl.NEAREST;
  7305. minFilter = gl.LINEAR;
  7306. break;
  7307. case BABYLON.Texture.NEAREST_NEAREST:
  7308. magFilter = gl.NEAREST;
  7309. minFilter = gl.NEAREST;
  7310. break;
  7311. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7312. magFilter = gl.LINEAR;
  7313. if (generateMipMaps) {
  7314. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7315. }
  7316. else {
  7317. minFilter = gl.NEAREST;
  7318. }
  7319. break;
  7320. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7321. magFilter = gl.LINEAR;
  7322. if (generateMipMaps) {
  7323. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7324. }
  7325. else {
  7326. minFilter = gl.NEAREST;
  7327. }
  7328. break;
  7329. case BABYLON.Texture.LINEAR_LINEAR:
  7330. magFilter = gl.LINEAR;
  7331. minFilter = gl.LINEAR;
  7332. break;
  7333. case BABYLON.Texture.LINEAR_NEAREST:
  7334. magFilter = gl.LINEAR;
  7335. minFilter = gl.NEAREST;
  7336. break;
  7337. }
  7338. return {
  7339. min: minFilter,
  7340. mag: magFilter
  7341. };
  7342. };
  7343. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7344. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7345. var img;
  7346. var onload = function () {
  7347. loadedImages[index] = img;
  7348. loadedImages._internalCount++;
  7349. scene._removePendingData(img);
  7350. if (loadedImages._internalCount === 6) {
  7351. onfinish(loadedImages);
  7352. }
  7353. };
  7354. var onerror = function () {
  7355. scene._removePendingData(img);
  7356. if (onErrorCallBack) {
  7357. onErrorCallBack();
  7358. }
  7359. };
  7360. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7361. scene._addPendingData(img);
  7362. };
  7363. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7364. if (onError === void 0) { onError = null; }
  7365. var loadedImages = [];
  7366. loadedImages._internalCount = 0;
  7367. for (var index = 0; index < 6; index++) {
  7368. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7369. }
  7370. };
  7371. var BufferPointer = (function () {
  7372. function BufferPointer() {
  7373. }
  7374. return BufferPointer;
  7375. }());
  7376. var InstancingAttributeInfo = (function () {
  7377. function InstancingAttributeInfo() {
  7378. }
  7379. return InstancingAttributeInfo;
  7380. }());
  7381. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7382. /**
  7383. * Regroup several parameters relative to the browser in use
  7384. */
  7385. var EngineCapabilities = (function () {
  7386. function EngineCapabilities() {
  7387. }
  7388. return EngineCapabilities;
  7389. }());
  7390. BABYLON.EngineCapabilities = EngineCapabilities;
  7391. /**
  7392. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7393. */
  7394. var Engine = (function () {
  7395. /**
  7396. * @constructor
  7397. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7398. * @param {boolean} [antialias] - enable antialias
  7399. * @param options - further options to be sent to the getContext function
  7400. */
  7401. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7402. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7403. var _this = this;
  7404. // Public members
  7405. this.forcePOTTextures = false;
  7406. this.isFullscreen = false;
  7407. this.isPointerLock = false;
  7408. this.cullBackFaces = true;
  7409. this.renderEvenInBackground = true;
  7410. this.preventCacheWipeBetweenFrames = false;
  7411. // To enable/disable IDB support and avoid XHR on .manifest
  7412. this.enableOfflineSupport = false;
  7413. this.scenes = new Array();
  7414. // Observables
  7415. /**
  7416. * Observable event triggered each time the rendering canvas is resized
  7417. */
  7418. this.onResizeObservable = new BABYLON.Observable();
  7419. /**
  7420. * Observable event triggered each time the canvas lost focus
  7421. */
  7422. this.onCanvasBlurObservable = new BABYLON.Observable();
  7423. this._windowIsBackground = false;
  7424. this._webGLVersion = 1.0;
  7425. this._badOS = false;
  7426. this._badDesktopOS = false;
  7427. this._drawCalls = new BABYLON.PerfCounter();
  7428. this._renderingQueueLaunched = false;
  7429. this._activeRenderLoops = [];
  7430. // Deterministic lockstepMaxSteps
  7431. this._deterministicLockstep = false;
  7432. this._lockstepMaxSteps = 4;
  7433. // FPS
  7434. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  7435. this._fps = 60;
  7436. this._deltaTime = 0;
  7437. // States
  7438. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7439. this._stencilState = new BABYLON.Internals._StencilState();
  7440. this._alphaState = new BABYLON.Internals._AlphaState();
  7441. this._alphaMode = Engine.ALPHA_DISABLE;
  7442. // Cache
  7443. this._loadedTexturesCache = new Array();
  7444. this._maxTextureChannels = 16;
  7445. this._activeTexturesCache = new Array(this._maxTextureChannels);
  7446. this._compiledEffects = {};
  7447. this._vertexAttribArraysEnabled = [];
  7448. this._uintIndicesCurrentlySet = false;
  7449. this._currentBoundBuffer = new Array();
  7450. this._currentBufferPointers = new Array();
  7451. this._currentInstanceLocations = new Array();
  7452. this._currentInstanceBuffers = new Array();
  7453. this._vaoRecordInProgress = false;
  7454. this._mustWipeVertexAttributes = false;
  7455. // Hardware supported Compressed Textures
  7456. this._texturesSupported = new Array();
  7457. this._onVRFullScreenTriggered = function () {
  7458. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7459. //get the old size before we change
  7460. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7461. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7462. //get the width and height, change the render size
  7463. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7464. var width, height;
  7465. _this.setHardwareScalingLevel(1);
  7466. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7467. }
  7468. else {
  7469. //When the specs are implemented, need to uncomment this.
  7470. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7471. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7472. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7473. _this._vrDisplayEnabled = undefined;
  7474. }
  7475. };
  7476. var canvas;
  7477. Engine.Instances.push(this);
  7478. options = options || {};
  7479. if (canvasOrContext.getContext) {
  7480. canvas = canvasOrContext;
  7481. this._renderingCanvas = canvas;
  7482. if (antialias != null) {
  7483. options.antialias = antialias;
  7484. }
  7485. if (options.deterministicLockstep === undefined) {
  7486. options.deterministicLockstep = false;
  7487. }
  7488. if (options.lockstepMaxSteps === undefined) {
  7489. options.lockstepMaxSteps = 4;
  7490. }
  7491. if (options.preserveDrawingBuffer === undefined) {
  7492. options.preserveDrawingBuffer = false;
  7493. }
  7494. if (options.audioEngine === undefined) {
  7495. options.audioEngine = true;
  7496. }
  7497. if (options.stencil === undefined) {
  7498. options.stencil = true;
  7499. }
  7500. this._deterministicLockstep = options.deterministicLockstep;
  7501. this._lockstepMaxSteps = options.lockstepMaxSteps;
  7502. // GL
  7503. if (!options.disableWebGL2Support) {
  7504. try {
  7505. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7506. if (this._gl) {
  7507. this._webGLVersion = 2.0;
  7508. }
  7509. }
  7510. catch (e) {
  7511. // Do nothing
  7512. }
  7513. }
  7514. if (!this._gl) {
  7515. if (!canvas) {
  7516. throw new Error("The provided canvas is null or undefined.");
  7517. }
  7518. try {
  7519. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7520. }
  7521. catch (e) {
  7522. throw new Error("WebGL not supported");
  7523. }
  7524. }
  7525. if (!this._gl) {
  7526. throw new Error("WebGL not supported");
  7527. }
  7528. this._onBlur = function () {
  7529. _this._performanceMonitor.disable();
  7530. _this._windowIsBackground = true;
  7531. };
  7532. this._onFocus = function () {
  7533. _this._performanceMonitor.enable();
  7534. _this._windowIsBackground = false;
  7535. };
  7536. this._onCanvasBlur = function () {
  7537. _this.onCanvasBlurObservable.notifyObservers(_this);
  7538. };
  7539. window.addEventListener("blur", this._onBlur);
  7540. window.addEventListener("focus", this._onFocus);
  7541. canvas.addEventListener("pointerout", this._onCanvasBlur);
  7542. }
  7543. else {
  7544. this._gl = canvasOrContext;
  7545. this._renderingCanvas = this._gl.canvas;
  7546. if (this._gl.renderbufferStorageMultisample) {
  7547. this._webGLVersion = 2.0;
  7548. }
  7549. options.stencil = this._gl.getContextAttributes().stencil;
  7550. }
  7551. // Viewport
  7552. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7553. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7554. this.resize();
  7555. // Caps
  7556. this._isStencilEnable = options.stencil;
  7557. this._caps = new EngineCapabilities();
  7558. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  7559. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  7560. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  7561. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  7562. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  7563. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  7564. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  7565. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  7566. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  7567. // Infos
  7568. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  7569. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  7570. if (rendererInfo != null) {
  7571. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  7572. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  7573. }
  7574. if (!this._glVendor) {
  7575. this._glVendor = "Unknown vendor";
  7576. }
  7577. if (!this._glRenderer) {
  7578. this._glRenderer = "Unknown renderer";
  7579. }
  7580. // Constants
  7581. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  7582. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  7583. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  7584. this._gl.DEPTH24_STENCIL8 = 35056;
  7585. // Extensions
  7586. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  7587. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  7588. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  7589. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  7590. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  7591. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  7592. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  7593. 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');
  7594. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  7595. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  7596. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  7597. this._caps.highPrecisionShaderSupported = true;
  7598. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  7599. // Checks if some of the format renders first to allow the use of webgl inspector.
  7600. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  7601. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  7602. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  7603. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  7604. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  7605. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  7606. if (this._webGLVersion > 1) {
  7607. this._gl.HALF_FLOAT_OES = 0x140B;
  7608. }
  7609. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  7610. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  7611. // Vertex array object
  7612. if (this._webGLVersion > 1) {
  7613. this._caps.vertexArrayObject = true;
  7614. }
  7615. else {
  7616. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  7617. if (vertexArrayObjectExtension != null) {
  7618. this._caps.vertexArrayObject = true;
  7619. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  7620. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  7621. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  7622. }
  7623. else {
  7624. this._caps.vertexArrayObject = false;
  7625. }
  7626. }
  7627. // Instances count
  7628. if (this._webGLVersion > 1) {
  7629. this._caps.instancedArrays = true;
  7630. }
  7631. else {
  7632. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  7633. if (instanceExtension != null) {
  7634. this._caps.instancedArrays = true;
  7635. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  7636. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  7637. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  7638. }
  7639. else {
  7640. this._caps.instancedArrays = false;
  7641. }
  7642. }
  7643. // Intelligently add supported compressed formats in order to check for.
  7644. // Check for ASTC support first as it is most powerful and to be very cross platform.
  7645. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  7646. // Likely no hardware which supports both PVR & DXT, so order matters little.
  7647. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  7648. if (this._caps.astc)
  7649. this.texturesSupported.push('-astc.ktx');
  7650. if (this._caps.s3tc)
  7651. this.texturesSupported.push('-dxt.ktx');
  7652. if (this._caps.pvrtc)
  7653. this.texturesSupported.push('-pvrtc.ktx');
  7654. if (this._caps.etc2)
  7655. this.texturesSupported.push('-etc2.ktx');
  7656. if (this._caps.etc1)
  7657. this.texturesSupported.push('-etc1.ktx');
  7658. if (this._gl.getShaderPrecisionFormat) {
  7659. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  7660. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  7661. }
  7662. // Depth buffer
  7663. this.setDepthBuffer(true);
  7664. this.setDepthFunctionToLessOrEqual();
  7665. this.setDepthWrite(true);
  7666. if (canvas) {
  7667. // Fullscreen
  7668. this._onFullscreenChange = function () {
  7669. if (document.fullscreen !== undefined) {
  7670. _this.isFullscreen = document.fullscreen;
  7671. }
  7672. else if (document.mozFullScreen !== undefined) {
  7673. _this.isFullscreen = document.mozFullScreen;
  7674. }
  7675. else if (document.webkitIsFullScreen !== undefined) {
  7676. _this.isFullscreen = document.webkitIsFullScreen;
  7677. }
  7678. else if (document.msIsFullScreen !== undefined) {
  7679. _this.isFullscreen = document.msIsFullScreen;
  7680. }
  7681. // Pointer lock
  7682. if (_this.isFullscreen && _this._pointerLockRequested) {
  7683. canvas.requestPointerLock = canvas.requestPointerLock ||
  7684. canvas.msRequestPointerLock ||
  7685. canvas.mozRequestPointerLock ||
  7686. canvas.webkitRequestPointerLock;
  7687. if (canvas.requestPointerLock) {
  7688. canvas.requestPointerLock();
  7689. }
  7690. }
  7691. };
  7692. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7693. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7694. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7695. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7696. // Pointer lock
  7697. this._onPointerLockChange = function () {
  7698. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7699. document.webkitPointerLockElement === canvas ||
  7700. document.msPointerLockElement === canvas ||
  7701. document.pointerLockElement === canvas);
  7702. };
  7703. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7704. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7705. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7706. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7707. }
  7708. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7709. Engine.audioEngine = new BABYLON.AudioEngine();
  7710. }
  7711. // Prepare buffer pointers
  7712. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  7713. this._currentBufferPointers[i] = new BufferPointer();
  7714. }
  7715. // Load WebVR Devices
  7716. if (options.autoEnableWebVR) {
  7717. this.initWebVR();
  7718. }
  7719. // Detect if we are running on a faulty buggy OS.
  7720. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  7721. // Detect if we are running on a faulty buggy desktop OS.
  7722. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  7723. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7724. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  7725. }
  7726. Object.defineProperty(Engine, "LastCreatedEngine", {
  7727. get: function () {
  7728. if (Engine.Instances.length === 0) {
  7729. return null;
  7730. }
  7731. return Engine.Instances[Engine.Instances.length - 1];
  7732. },
  7733. enumerable: true,
  7734. configurable: true
  7735. });
  7736. Object.defineProperty(Engine, "LastCreatedScene", {
  7737. get: function () {
  7738. var lastCreatedEngine = Engine.LastCreatedEngine;
  7739. if (!lastCreatedEngine) {
  7740. return null;
  7741. }
  7742. if (lastCreatedEngine.scenes.length === 0) {
  7743. return null;
  7744. }
  7745. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7746. },
  7747. enumerable: true,
  7748. configurable: true
  7749. });
  7750. /**
  7751. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  7752. */
  7753. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  7754. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  7755. var engine = Engine.Instances[engineIndex];
  7756. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  7757. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  7758. }
  7759. }
  7760. };
  7761. Object.defineProperty(Engine, "NEVER", {
  7762. get: function () {
  7763. return Engine._NEVER;
  7764. },
  7765. enumerable: true,
  7766. configurable: true
  7767. });
  7768. Object.defineProperty(Engine, "ALWAYS", {
  7769. get: function () {
  7770. return Engine._ALWAYS;
  7771. },
  7772. enumerable: true,
  7773. configurable: true
  7774. });
  7775. Object.defineProperty(Engine, "LESS", {
  7776. get: function () {
  7777. return Engine._LESS;
  7778. },
  7779. enumerable: true,
  7780. configurable: true
  7781. });
  7782. Object.defineProperty(Engine, "EQUAL", {
  7783. get: function () {
  7784. return Engine._EQUAL;
  7785. },
  7786. enumerable: true,
  7787. configurable: true
  7788. });
  7789. Object.defineProperty(Engine, "LEQUAL", {
  7790. get: function () {
  7791. return Engine._LEQUAL;
  7792. },
  7793. enumerable: true,
  7794. configurable: true
  7795. });
  7796. Object.defineProperty(Engine, "GREATER", {
  7797. get: function () {
  7798. return Engine._GREATER;
  7799. },
  7800. enumerable: true,
  7801. configurable: true
  7802. });
  7803. Object.defineProperty(Engine, "GEQUAL", {
  7804. get: function () {
  7805. return Engine._GEQUAL;
  7806. },
  7807. enumerable: true,
  7808. configurable: true
  7809. });
  7810. Object.defineProperty(Engine, "NOTEQUAL", {
  7811. get: function () {
  7812. return Engine._NOTEQUAL;
  7813. },
  7814. enumerable: true,
  7815. configurable: true
  7816. });
  7817. Object.defineProperty(Engine, "KEEP", {
  7818. get: function () {
  7819. return Engine._KEEP;
  7820. },
  7821. enumerable: true,
  7822. configurable: true
  7823. });
  7824. Object.defineProperty(Engine, "REPLACE", {
  7825. get: function () {
  7826. return Engine._REPLACE;
  7827. },
  7828. enumerable: true,
  7829. configurable: true
  7830. });
  7831. Object.defineProperty(Engine, "INCR", {
  7832. get: function () {
  7833. return Engine._INCR;
  7834. },
  7835. enumerable: true,
  7836. configurable: true
  7837. });
  7838. Object.defineProperty(Engine, "DECR", {
  7839. get: function () {
  7840. return Engine._DECR;
  7841. },
  7842. enumerable: true,
  7843. configurable: true
  7844. });
  7845. Object.defineProperty(Engine, "INVERT", {
  7846. get: function () {
  7847. return Engine._INVERT;
  7848. },
  7849. enumerable: true,
  7850. configurable: true
  7851. });
  7852. Object.defineProperty(Engine, "INCR_WRAP", {
  7853. get: function () {
  7854. return Engine._INCR_WRAP;
  7855. },
  7856. enumerable: true,
  7857. configurable: true
  7858. });
  7859. Object.defineProperty(Engine, "DECR_WRAP", {
  7860. get: function () {
  7861. return Engine._DECR_WRAP;
  7862. },
  7863. enumerable: true,
  7864. configurable: true
  7865. });
  7866. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  7867. get: function () {
  7868. return Engine._ALPHA_DISABLE;
  7869. },
  7870. enumerable: true,
  7871. configurable: true
  7872. });
  7873. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  7874. get: function () {
  7875. return Engine._ALPHA_ONEONE;
  7876. },
  7877. enumerable: true,
  7878. configurable: true
  7879. });
  7880. Object.defineProperty(Engine, "ALPHA_ADD", {
  7881. get: function () {
  7882. return Engine._ALPHA_ADD;
  7883. },
  7884. enumerable: true,
  7885. configurable: true
  7886. });
  7887. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  7888. get: function () {
  7889. return Engine._ALPHA_COMBINE;
  7890. },
  7891. enumerable: true,
  7892. configurable: true
  7893. });
  7894. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  7895. get: function () {
  7896. return Engine._ALPHA_SUBTRACT;
  7897. },
  7898. enumerable: true,
  7899. configurable: true
  7900. });
  7901. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  7902. get: function () {
  7903. return Engine._ALPHA_MULTIPLY;
  7904. },
  7905. enumerable: true,
  7906. configurable: true
  7907. });
  7908. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  7909. get: function () {
  7910. return Engine._ALPHA_MAXIMIZED;
  7911. },
  7912. enumerable: true,
  7913. configurable: true
  7914. });
  7915. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  7916. get: function () {
  7917. return Engine._ALPHA_PREMULTIPLIED;
  7918. },
  7919. enumerable: true,
  7920. configurable: true
  7921. });
  7922. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  7923. get: function () {
  7924. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  7925. },
  7926. enumerable: true,
  7927. configurable: true
  7928. });
  7929. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  7930. get: function () {
  7931. return Engine._ALPHA_INTERPOLATE;
  7932. },
  7933. enumerable: true,
  7934. configurable: true
  7935. });
  7936. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  7937. get: function () {
  7938. return Engine._ALPHA_SCREENMODE;
  7939. },
  7940. enumerable: true,
  7941. configurable: true
  7942. });
  7943. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  7944. get: function () {
  7945. return Engine._DELAYLOADSTATE_NONE;
  7946. },
  7947. enumerable: true,
  7948. configurable: true
  7949. });
  7950. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  7951. get: function () {
  7952. return Engine._DELAYLOADSTATE_LOADED;
  7953. },
  7954. enumerable: true,
  7955. configurable: true
  7956. });
  7957. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  7958. get: function () {
  7959. return Engine._DELAYLOADSTATE_LOADING;
  7960. },
  7961. enumerable: true,
  7962. configurable: true
  7963. });
  7964. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  7965. get: function () {
  7966. return Engine._DELAYLOADSTATE_NOTLOADED;
  7967. },
  7968. enumerable: true,
  7969. configurable: true
  7970. });
  7971. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  7972. get: function () {
  7973. return Engine._TEXTUREFORMAT_ALPHA;
  7974. },
  7975. enumerable: true,
  7976. configurable: true
  7977. });
  7978. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  7979. get: function () {
  7980. return Engine._TEXTUREFORMAT_LUMINANCE;
  7981. },
  7982. enumerable: true,
  7983. configurable: true
  7984. });
  7985. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  7986. get: function () {
  7987. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  7988. },
  7989. enumerable: true,
  7990. configurable: true
  7991. });
  7992. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  7993. get: function () {
  7994. return Engine._TEXTUREFORMAT_RGB;
  7995. },
  7996. enumerable: true,
  7997. configurable: true
  7998. });
  7999. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8000. get: function () {
  8001. return Engine._TEXTUREFORMAT_RGBA;
  8002. },
  8003. enumerable: true,
  8004. configurable: true
  8005. });
  8006. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8007. get: function () {
  8008. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8009. },
  8010. enumerable: true,
  8011. configurable: true
  8012. });
  8013. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8014. get: function () {
  8015. return Engine._TEXTURETYPE_FLOAT;
  8016. },
  8017. enumerable: true,
  8018. configurable: true
  8019. });
  8020. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8021. get: function () {
  8022. return Engine._TEXTURETYPE_HALF_FLOAT;
  8023. },
  8024. enumerable: true,
  8025. configurable: true
  8026. });
  8027. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  8028. get: function () {
  8029. return Engine._SCALEMODE_FLOOR;
  8030. },
  8031. enumerable: true,
  8032. configurable: true
  8033. });
  8034. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  8035. get: function () {
  8036. return Engine._SCALEMODE_NEAREST;
  8037. },
  8038. enumerable: true,
  8039. configurable: true
  8040. });
  8041. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  8042. get: function () {
  8043. return Engine._SCALEMODE_CEILING;
  8044. },
  8045. enumerable: true,
  8046. configurable: true
  8047. });
  8048. Object.defineProperty(Engine, "Version", {
  8049. get: function () {
  8050. return "3.1-alpha";
  8051. },
  8052. enumerable: true,
  8053. configurable: true
  8054. });
  8055. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8056. get: function () {
  8057. return this._webGLVersion < 2 || this.forcePOTTextures;
  8058. },
  8059. enumerable: true,
  8060. configurable: true
  8061. });
  8062. Object.defineProperty(Engine.prototype, "badOS", {
  8063. get: function () {
  8064. return this._badOS;
  8065. },
  8066. enumerable: true,
  8067. configurable: true
  8068. });
  8069. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8070. get: function () {
  8071. return this._badDesktopOS;
  8072. },
  8073. enumerable: true,
  8074. configurable: true
  8075. });
  8076. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8077. get: function () {
  8078. return this._performanceMonitor;
  8079. },
  8080. enumerable: true,
  8081. configurable: true
  8082. });
  8083. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8084. get: function () {
  8085. return this._texturesSupported;
  8086. },
  8087. enumerable: true,
  8088. configurable: true
  8089. });
  8090. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8091. get: function () {
  8092. return this._textureFormatInUse;
  8093. },
  8094. enumerable: true,
  8095. configurable: true
  8096. });
  8097. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8098. // Empty texture
  8099. get: function () {
  8100. if (!this._emptyTexture) {
  8101. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8102. }
  8103. return this._emptyTexture;
  8104. },
  8105. enumerable: true,
  8106. configurable: true
  8107. });
  8108. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8109. get: function () {
  8110. if (!this._emptyCubeTexture) {
  8111. var faceData = new Uint8Array(4);
  8112. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8113. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8114. }
  8115. return this._emptyCubeTexture;
  8116. },
  8117. enumerable: true,
  8118. configurable: true
  8119. });
  8120. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8121. get: function () {
  8122. return this._webGLVersion;
  8123. },
  8124. enumerable: true,
  8125. configurable: true
  8126. });
  8127. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8128. /**
  8129. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8130. */
  8131. get: function () {
  8132. return this._isStencilEnable;
  8133. },
  8134. enumerable: true,
  8135. configurable: true
  8136. });
  8137. Engine.prototype._prepareWorkingCanvas = function () {
  8138. if (this._workingCanvas) {
  8139. return;
  8140. }
  8141. this._workingCanvas = document.createElement("canvas");
  8142. this._workingContext = this._workingCanvas.getContext("2d");
  8143. };
  8144. Engine.prototype.resetTextureCache = function () {
  8145. for (var index = 0; index < this._maxTextureChannels; index++) {
  8146. this._activeTexturesCache[index] = null;
  8147. }
  8148. };
  8149. Engine.prototype.isDeterministicLockStep = function () {
  8150. return this._deterministicLockstep;
  8151. };
  8152. Engine.prototype.getLockstepMaxSteps = function () {
  8153. return this._lockstepMaxSteps;
  8154. };
  8155. Engine.prototype.getGlInfo = function () {
  8156. return {
  8157. vendor: this._glVendor,
  8158. renderer: this._glRenderer,
  8159. version: this._glVersion
  8160. };
  8161. };
  8162. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8163. if (useScreen === void 0) { useScreen = false; }
  8164. var viewport = camera.viewport;
  8165. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8166. };
  8167. Engine.prototype.getRenderWidth = function (useScreen) {
  8168. if (useScreen === void 0) { useScreen = false; }
  8169. if (!useScreen && this._currentRenderTarget) {
  8170. return this._currentRenderTarget._width;
  8171. }
  8172. return this._gl.drawingBufferWidth;
  8173. };
  8174. Engine.prototype.getRenderHeight = function (useScreen) {
  8175. if (useScreen === void 0) { useScreen = false; }
  8176. if (!useScreen && this._currentRenderTarget) {
  8177. return this._currentRenderTarget._height;
  8178. }
  8179. return this._gl.drawingBufferHeight;
  8180. };
  8181. Engine.prototype.getRenderingCanvas = function () {
  8182. return this._renderingCanvas;
  8183. };
  8184. Engine.prototype.getRenderingCanvasClientRect = function () {
  8185. return this._renderingCanvas.getBoundingClientRect();
  8186. };
  8187. Engine.prototype.setHardwareScalingLevel = function (level) {
  8188. this._hardwareScalingLevel = level;
  8189. this.resize();
  8190. };
  8191. Engine.prototype.getHardwareScalingLevel = function () {
  8192. return this._hardwareScalingLevel;
  8193. };
  8194. Engine.prototype.getLoadedTexturesCache = function () {
  8195. return this._loadedTexturesCache;
  8196. };
  8197. Engine.prototype.getCaps = function () {
  8198. return this._caps;
  8199. };
  8200. Object.defineProperty(Engine.prototype, "drawCalls", {
  8201. /** The number of draw calls submitted last frame */
  8202. get: function () {
  8203. return this._drawCalls.current;
  8204. },
  8205. enumerable: true,
  8206. configurable: true
  8207. });
  8208. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8209. get: function () {
  8210. return this._drawCalls;
  8211. },
  8212. enumerable: true,
  8213. configurable: true
  8214. });
  8215. Engine.prototype.getDepthFunction = function () {
  8216. return this._depthCullingState.depthFunc;
  8217. };
  8218. Engine.prototype.setDepthFunction = function (depthFunc) {
  8219. this._depthCullingState.depthFunc = depthFunc;
  8220. };
  8221. Engine.prototype.setDepthFunctionToGreater = function () {
  8222. this._depthCullingState.depthFunc = this._gl.GREATER;
  8223. };
  8224. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8225. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8226. };
  8227. Engine.prototype.setDepthFunctionToLess = function () {
  8228. this._depthCullingState.depthFunc = this._gl.LESS;
  8229. };
  8230. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8231. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8232. };
  8233. Engine.prototype.getStencilBuffer = function () {
  8234. return this._stencilState.stencilTest;
  8235. };
  8236. Engine.prototype.setStencilBuffer = function (enable) {
  8237. this._stencilState.stencilTest = enable;
  8238. };
  8239. Engine.prototype.getStencilMask = function () {
  8240. return this._stencilState.stencilMask;
  8241. };
  8242. Engine.prototype.setStencilMask = function (mask) {
  8243. this._stencilState.stencilMask = mask;
  8244. };
  8245. Engine.prototype.getStencilFunction = function () {
  8246. return this._stencilState.stencilFunc;
  8247. };
  8248. Engine.prototype.getStencilFunctionReference = function () {
  8249. return this._stencilState.stencilFuncRef;
  8250. };
  8251. Engine.prototype.getStencilFunctionMask = function () {
  8252. return this._stencilState.stencilFuncMask;
  8253. };
  8254. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8255. this._stencilState.stencilFunc = stencilFunc;
  8256. };
  8257. Engine.prototype.setStencilFunctionReference = function (reference) {
  8258. this._stencilState.stencilFuncRef = reference;
  8259. };
  8260. Engine.prototype.setStencilFunctionMask = function (mask) {
  8261. this._stencilState.stencilFuncMask = mask;
  8262. };
  8263. Engine.prototype.getStencilOperationFail = function () {
  8264. return this._stencilState.stencilOpStencilFail;
  8265. };
  8266. Engine.prototype.getStencilOperationDepthFail = function () {
  8267. return this._stencilState.stencilOpDepthFail;
  8268. };
  8269. Engine.prototype.getStencilOperationPass = function () {
  8270. return this._stencilState.stencilOpStencilDepthPass;
  8271. };
  8272. Engine.prototype.setStencilOperationFail = function (operation) {
  8273. this._stencilState.stencilOpStencilFail = operation;
  8274. };
  8275. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8276. this._stencilState.stencilOpDepthFail = operation;
  8277. };
  8278. Engine.prototype.setStencilOperationPass = function (operation) {
  8279. this._stencilState.stencilOpStencilDepthPass = operation;
  8280. };
  8281. Engine.prototype.setDitheringState = function (value) {
  8282. if (value) {
  8283. this._gl.enable(this._gl.DITHER);
  8284. }
  8285. else {
  8286. this._gl.disable(this._gl.DITHER);
  8287. }
  8288. };
  8289. /**
  8290. * stop executing a render loop function and remove it from the execution array
  8291. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8292. */
  8293. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8294. if (!renderFunction) {
  8295. this._activeRenderLoops = [];
  8296. return;
  8297. }
  8298. var index = this._activeRenderLoops.indexOf(renderFunction);
  8299. if (index >= 0) {
  8300. this._activeRenderLoops.splice(index, 1);
  8301. }
  8302. };
  8303. Engine.prototype._renderLoop = function () {
  8304. var shouldRender = true;
  8305. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8306. shouldRender = false;
  8307. }
  8308. if (shouldRender) {
  8309. // Start new frame
  8310. this.beginFrame();
  8311. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8312. var renderFunction = this._activeRenderLoops[index];
  8313. renderFunction();
  8314. }
  8315. // Present
  8316. this.endFrame();
  8317. }
  8318. if (this._activeRenderLoops.length > 0) {
  8319. // Register new frame
  8320. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  8321. }
  8322. else {
  8323. this._renderingQueueLaunched = false;
  8324. }
  8325. };
  8326. /**
  8327. * Register and execute a render loop. The engine can have more than one render function.
  8328. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8329. * @example
  8330. * engine.runRenderLoop(function () {
  8331. * scene.render()
  8332. * })
  8333. */
  8334. Engine.prototype.runRenderLoop = function (renderFunction) {
  8335. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8336. return;
  8337. }
  8338. this._activeRenderLoops.push(renderFunction);
  8339. if (!this._renderingQueueLaunched) {
  8340. this._renderingQueueLaunched = true;
  8341. this._bindedRenderFunction = this._renderLoop.bind(this);
  8342. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8343. }
  8344. };
  8345. /**
  8346. * Toggle full screen mode.
  8347. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8348. * @param {any} options - an options object to be sent to the requestFullscreen function
  8349. */
  8350. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8351. if (this.isFullscreen) {
  8352. BABYLON.Tools.ExitFullscreen();
  8353. }
  8354. else {
  8355. this._pointerLockRequested = requestPointerLock;
  8356. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8357. }
  8358. };
  8359. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8360. if (stencil === void 0) { stencil = false; }
  8361. this.applyStates();
  8362. var mode = 0;
  8363. if (backBuffer && color) {
  8364. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8365. mode |= this._gl.COLOR_BUFFER_BIT;
  8366. }
  8367. if (depth) {
  8368. this._gl.clearDepth(1.0);
  8369. mode |= this._gl.DEPTH_BUFFER_BIT;
  8370. }
  8371. if (stencil) {
  8372. this._gl.clearStencil(0);
  8373. mode |= this._gl.STENCIL_BUFFER_BIT;
  8374. }
  8375. this._gl.clear(mode);
  8376. };
  8377. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8378. var gl = this._gl;
  8379. // Save state
  8380. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8381. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8382. // Change state
  8383. gl.enable(gl.SCISSOR_TEST);
  8384. gl.scissor(x, y, width, height);
  8385. // Clear
  8386. this.clear(clearColor, true, true, true);
  8387. // Restore state
  8388. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8389. if (curScissor === true) {
  8390. gl.enable(gl.SCISSOR_TEST);
  8391. }
  8392. else {
  8393. gl.disable(gl.SCISSOR_TEST);
  8394. }
  8395. };
  8396. /**
  8397. * Set the WebGL's viewport
  8398. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8399. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8400. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8401. */
  8402. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8403. var width = requiredWidth || this.getRenderWidth();
  8404. var height = requiredHeight || this.getRenderHeight();
  8405. var x = viewport.x || 0;
  8406. var y = viewport.y || 0;
  8407. this._cachedViewport = viewport;
  8408. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8409. };
  8410. /**
  8411. * Directly set the WebGL Viewport
  8412. * The x, y, width & height are directly passed to the WebGL call
  8413. * @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.
  8414. */
  8415. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8416. var currentViewport = this._cachedViewport;
  8417. this._cachedViewport = null;
  8418. this._gl.viewport(x, y, width, height);
  8419. return currentViewport;
  8420. };
  8421. Engine.prototype.beginFrame = function () {
  8422. this._measureFps();
  8423. };
  8424. Engine.prototype.endFrame = function () {
  8425. //force a flush in case we are using a bad OS.
  8426. if (this._badOS) {
  8427. this.flushFramebuffer();
  8428. }
  8429. //submit frame to the vr device, if enabled
  8430. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8431. this._vrDisplayEnabled.submitFrame();
  8432. }
  8433. };
  8434. /**
  8435. * resize the view according to the canvas' size.
  8436. * @example
  8437. * window.addEventListener("resize", function () {
  8438. * engine.resize();
  8439. * });
  8440. */
  8441. Engine.prototype.resize = function () {
  8442. // We're not resizing the size of the canvas while in VR mode & presenting
  8443. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  8444. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8445. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8446. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8447. }
  8448. };
  8449. /**
  8450. * force a specific size of the canvas
  8451. * @param {number} width - the new canvas' width
  8452. * @param {number} height - the new canvas' height
  8453. */
  8454. Engine.prototype.setSize = function (width, height) {
  8455. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  8456. return;
  8457. }
  8458. this._renderingCanvas.width = width;
  8459. this._renderingCanvas.height = height;
  8460. for (var index = 0; index < this.scenes.length; index++) {
  8461. var scene = this.scenes[index];
  8462. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8463. var cam = scene.cameras[camIndex];
  8464. cam._currentRenderId = 0;
  8465. }
  8466. }
  8467. if (this.onResizeObservable.hasObservers) {
  8468. this.onResizeObservable.notifyObservers(this);
  8469. }
  8470. };
  8471. //WebVR functions
  8472. Engine.prototype.isVRDevicePresent = function (callback) {
  8473. this.getVRDevice(null, function (device) {
  8474. callback(device !== null);
  8475. });
  8476. };
  8477. Engine.prototype.getVRDevice = function (name, callback) {
  8478. if (!this.vrDisplaysPromise) {
  8479. callback(null);
  8480. return;
  8481. }
  8482. this.vrDisplaysPromise.then(function (devices) {
  8483. if (devices.length > 0) {
  8484. if (name) {
  8485. var found = devices.some(function (device) {
  8486. if (device.displayName === name) {
  8487. callback(device);
  8488. return true;
  8489. }
  8490. else {
  8491. return false;
  8492. }
  8493. });
  8494. if (!found) {
  8495. BABYLON.Tools.Warn("Display " + name + " was not found. Using " + devices[0].displayName);
  8496. callback(devices[0]);
  8497. }
  8498. }
  8499. else {
  8500. //choose the first one
  8501. callback(devices[0]);
  8502. }
  8503. }
  8504. else {
  8505. BABYLON.Tools.Error("No WebVR devices found!");
  8506. callback(null);
  8507. }
  8508. });
  8509. };
  8510. Engine.prototype.initWebVR = function () {
  8511. if (!this.vrDisplaysPromise) {
  8512. this._getVRDisplays();
  8513. }
  8514. };
  8515. Engine.prototype.enableVR = function (vrDevice) {
  8516. this._vrDisplayEnabled = vrDevice;
  8517. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8518. };
  8519. Engine.prototype.disableVR = function () {
  8520. if (this._vrDisplayEnabled) {
  8521. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8522. }
  8523. };
  8524. Engine.prototype._getVRDisplays = function () {
  8525. var _this = this;
  8526. var getWebVRDevices = function (devices) {
  8527. var size = devices.length;
  8528. var i = 0;
  8529. _this._vrDisplays = devices.filter(function (device) {
  8530. return devices[i] instanceof VRDisplay;
  8531. });
  8532. return _this._vrDisplays;
  8533. };
  8534. //using a key due to typescript
  8535. if (navigator.getVRDisplays) {
  8536. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8537. }
  8538. };
  8539. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  8540. if (this._currentRenderTarget) {
  8541. this.unBindFramebuffer(this._currentRenderTarget);
  8542. }
  8543. this._currentRenderTarget = texture;
  8544. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8545. var gl = this._gl;
  8546. if (texture.isCube) {
  8547. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  8548. }
  8549. if (this._cachedViewport && !forceFullscreenViewport) {
  8550. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  8551. }
  8552. else {
  8553. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  8554. }
  8555. this.wipeCaches();
  8556. };
  8557. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8558. if (this._currentFramebuffer !== framebuffer) {
  8559. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8560. this._currentFramebuffer = framebuffer;
  8561. }
  8562. };
  8563. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8564. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8565. this._currentRenderTarget = null;
  8566. // If MSAA, we need to bitblt back to main texture
  8567. var gl = this._gl;
  8568. if (texture._MSAAFramebuffer) {
  8569. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8570. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8571. gl.blitFramebuffer(0, 0, texture._width, texture._height, 0, 0, texture._width, texture._height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8572. }
  8573. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  8574. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8575. gl.generateMipmap(gl.TEXTURE_2D);
  8576. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8577. }
  8578. if (onBeforeUnbind) {
  8579. if (texture._MSAAFramebuffer) {
  8580. // Bind the correct framebuffer
  8581. this.bindUnboundFramebuffer(texture._framebuffer);
  8582. }
  8583. onBeforeUnbind();
  8584. }
  8585. this.bindUnboundFramebuffer(null);
  8586. };
  8587. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8588. if (texture.generateMipMaps) {
  8589. var gl = this._gl;
  8590. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8591. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8592. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8593. }
  8594. };
  8595. Engine.prototype.flushFramebuffer = function () {
  8596. this._gl.flush();
  8597. };
  8598. Engine.prototype.restoreDefaultFramebuffer = function () {
  8599. if (this._currentRenderTarget) {
  8600. this.unBindFramebuffer(this._currentRenderTarget);
  8601. }
  8602. else {
  8603. this.bindUnboundFramebuffer(null);
  8604. }
  8605. if (this._cachedViewport) {
  8606. this.setViewport(this._cachedViewport);
  8607. }
  8608. this.wipeCaches();
  8609. };
  8610. // UBOs
  8611. Engine.prototype.createUniformBuffer = function (elements) {
  8612. var ubo = this._gl.createBuffer();
  8613. this.bindUniformBuffer(ubo);
  8614. if (elements instanceof Float32Array) {
  8615. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  8616. }
  8617. else {
  8618. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  8619. }
  8620. this.bindUniformBuffer(null);
  8621. ubo.references = 1;
  8622. return ubo;
  8623. };
  8624. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  8625. var ubo = this._gl.createBuffer();
  8626. this.bindUniformBuffer(ubo);
  8627. if (elements instanceof Float32Array) {
  8628. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  8629. }
  8630. else {
  8631. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  8632. }
  8633. this.bindUniformBuffer(null);
  8634. ubo.references = 1;
  8635. return ubo;
  8636. };
  8637. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  8638. this.bindUniformBuffer(uniformBuffer);
  8639. if (offset === undefined) {
  8640. offset = 0;
  8641. }
  8642. if (count === undefined) {
  8643. if (elements instanceof Float32Array) {
  8644. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  8645. }
  8646. else {
  8647. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  8648. }
  8649. }
  8650. else {
  8651. if (elements instanceof Float32Array) {
  8652. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  8653. }
  8654. else {
  8655. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  8656. }
  8657. }
  8658. this.bindUniformBuffer(null);
  8659. };
  8660. // VBOs
  8661. Engine.prototype._resetVertexBufferBinding = function () {
  8662. this.bindArrayBuffer(null);
  8663. this._cachedVertexBuffers = null;
  8664. };
  8665. Engine.prototype.createVertexBuffer = function (vertices) {
  8666. var vbo = this._gl.createBuffer();
  8667. this.bindArrayBuffer(vbo);
  8668. if (vertices instanceof Float32Array) {
  8669. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8670. }
  8671. else {
  8672. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8673. }
  8674. this._resetVertexBufferBinding();
  8675. vbo.references = 1;
  8676. return vbo;
  8677. };
  8678. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8679. var vbo = this._gl.createBuffer();
  8680. this.bindArrayBuffer(vbo);
  8681. if (vertices instanceof Float32Array) {
  8682. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8683. }
  8684. else {
  8685. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8686. }
  8687. this._resetVertexBufferBinding();
  8688. vbo.references = 1;
  8689. return vbo;
  8690. };
  8691. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8692. this.bindArrayBuffer(vertexBuffer);
  8693. if (offset === undefined) {
  8694. offset = 0;
  8695. }
  8696. if (count === undefined) {
  8697. if (vertices instanceof Float32Array) {
  8698. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8699. }
  8700. else {
  8701. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8702. }
  8703. }
  8704. else {
  8705. if (vertices instanceof Float32Array) {
  8706. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8707. }
  8708. else {
  8709. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8710. }
  8711. }
  8712. this._resetVertexBufferBinding();
  8713. };
  8714. Engine.prototype._resetIndexBufferBinding = function () {
  8715. this.bindIndexBuffer(null);
  8716. this._cachedIndexBuffer = null;
  8717. };
  8718. Engine.prototype.createIndexBuffer = function (indices) {
  8719. var vbo = this._gl.createBuffer();
  8720. this.bindIndexBuffer(vbo);
  8721. // Check for 32 bits indices
  8722. var arrayBuffer;
  8723. var need32Bits = false;
  8724. if (indices instanceof Uint16Array) {
  8725. arrayBuffer = indices;
  8726. }
  8727. else {
  8728. //check 32 bit support
  8729. if (this._caps.uintIndices) {
  8730. if (indices instanceof Uint32Array) {
  8731. arrayBuffer = indices;
  8732. need32Bits = true;
  8733. }
  8734. else {
  8735. //number[] or Int32Array, check if 32 bit is necessary
  8736. for (var index = 0; index < indices.length; index++) {
  8737. if (indices[index] > 65535) {
  8738. need32Bits = true;
  8739. break;
  8740. }
  8741. }
  8742. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8743. }
  8744. }
  8745. else {
  8746. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8747. arrayBuffer = new Uint16Array(indices);
  8748. }
  8749. }
  8750. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8751. this._resetIndexBufferBinding();
  8752. vbo.references = 1;
  8753. vbo.is32Bits = need32Bits;
  8754. return vbo;
  8755. };
  8756. Engine.prototype.bindArrayBuffer = function (buffer) {
  8757. if (!this._vaoRecordInProgress) {
  8758. this._unbindVertexArrayObject();
  8759. }
  8760. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8761. };
  8762. Engine.prototype.bindUniformBuffer = function (buffer) {
  8763. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  8764. };
  8765. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  8766. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  8767. };
  8768. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  8769. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  8770. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  8771. };
  8772. ;
  8773. Engine.prototype.bindIndexBuffer = function (buffer) {
  8774. if (!this._vaoRecordInProgress) {
  8775. this._unbindVertexArrayObject();
  8776. }
  8777. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8778. };
  8779. Engine.prototype.bindBuffer = function (buffer, target) {
  8780. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8781. this._gl.bindBuffer(target, buffer);
  8782. this._currentBoundBuffer[target] = buffer;
  8783. }
  8784. };
  8785. Engine.prototype.updateArrayBuffer = function (data) {
  8786. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8787. };
  8788. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  8789. var pointer = this._currentBufferPointers[indx];
  8790. var changed = false;
  8791. if (!pointer.active) {
  8792. changed = true;
  8793. pointer.active = true;
  8794. pointer.index = indx;
  8795. pointer.size = size;
  8796. pointer.type = type;
  8797. pointer.normalized = normalized;
  8798. pointer.stride = stride;
  8799. pointer.offset = offset;
  8800. pointer.buffer = buffer;
  8801. }
  8802. else {
  8803. if (pointer.buffer !== buffer) {
  8804. pointer.buffer = buffer;
  8805. changed = true;
  8806. }
  8807. if (pointer.size !== size) {
  8808. pointer.size = size;
  8809. changed = true;
  8810. }
  8811. if (pointer.type !== type) {
  8812. pointer.type = type;
  8813. changed = true;
  8814. }
  8815. if (pointer.normalized !== normalized) {
  8816. pointer.normalized = normalized;
  8817. changed = true;
  8818. }
  8819. if (pointer.stride !== stride) {
  8820. pointer.stride = stride;
  8821. changed = true;
  8822. }
  8823. if (pointer.offset !== offset) {
  8824. pointer.offset = offset;
  8825. changed = true;
  8826. }
  8827. }
  8828. if (changed || this._vaoRecordInProgress) {
  8829. this.bindArrayBuffer(buffer);
  8830. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  8831. }
  8832. };
  8833. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  8834. if (indexBuffer == null) {
  8835. return;
  8836. }
  8837. if (this._cachedIndexBuffer !== indexBuffer) {
  8838. this._cachedIndexBuffer = indexBuffer;
  8839. this.bindIndexBuffer(indexBuffer);
  8840. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  8841. }
  8842. };
  8843. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  8844. var attributes = effect.getAttributesNames();
  8845. if (!this._vaoRecordInProgress) {
  8846. this._unbindVertexArrayObject();
  8847. }
  8848. this.unbindAllAttributes();
  8849. for (var index = 0; index < attributes.length; index++) {
  8850. var order = effect.getAttributeLocation(index);
  8851. if (order >= 0) {
  8852. var vertexBuffer = vertexBuffers[attributes[index]];
  8853. if (!vertexBuffer) {
  8854. continue;
  8855. }
  8856. this._gl.enableVertexAttribArray(order);
  8857. if (!this._vaoRecordInProgress) {
  8858. this._vertexAttribArraysEnabled[order] = true;
  8859. }
  8860. var buffer = vertexBuffer.getBuffer();
  8861. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  8862. if (vertexBuffer.getIsInstanced()) {
  8863. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  8864. if (!this._vaoRecordInProgress) {
  8865. this._currentInstanceLocations.push(order);
  8866. this._currentInstanceBuffers.push(buffer);
  8867. }
  8868. }
  8869. }
  8870. }
  8871. };
  8872. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  8873. var vao = this._gl.createVertexArray();
  8874. this._vaoRecordInProgress = true;
  8875. this._gl.bindVertexArray(vao);
  8876. this._mustWipeVertexAttributes = true;
  8877. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8878. this.bindIndexBuffer(indexBuffer);
  8879. this._vaoRecordInProgress = false;
  8880. this._gl.bindVertexArray(null);
  8881. return vao;
  8882. };
  8883. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  8884. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  8885. this._cachedVertexArrayObject = vertexArrayObject;
  8886. this._gl.bindVertexArray(vertexArrayObject);
  8887. this._cachedVertexBuffers = null;
  8888. this._cachedIndexBuffer = null;
  8889. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  8890. this._mustWipeVertexAttributes = true;
  8891. }
  8892. };
  8893. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  8894. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  8895. this._cachedVertexBuffers = vertexBuffer;
  8896. this._cachedEffectForVertexBuffers = effect;
  8897. var attributesCount = effect.getAttributesCount();
  8898. this._unbindVertexArrayObject();
  8899. this.unbindAllAttributes();
  8900. var offset = 0;
  8901. for (var index = 0; index < attributesCount; index++) {
  8902. if (index < vertexDeclaration.length) {
  8903. var order = effect.getAttributeLocation(index);
  8904. if (order >= 0) {
  8905. this._gl.enableVertexAttribArray(order);
  8906. this._vertexAttribArraysEnabled[order] = true;
  8907. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  8908. }
  8909. offset += vertexDeclaration[index] * 4;
  8910. }
  8911. }
  8912. }
  8913. this._bindIndexBufferWithCache(indexBuffer);
  8914. };
  8915. Engine.prototype._unbindVertexArrayObject = function () {
  8916. if (!this._cachedVertexArrayObject) {
  8917. return;
  8918. }
  8919. this._cachedVertexArrayObject = null;
  8920. this._gl.bindVertexArray(null);
  8921. };
  8922. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  8923. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  8924. this._cachedVertexBuffers = vertexBuffers;
  8925. this._cachedEffectForVertexBuffers = effect;
  8926. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8927. }
  8928. this._bindIndexBufferWithCache(indexBuffer);
  8929. };
  8930. Engine.prototype.unbindInstanceAttributes = function () {
  8931. var boundBuffer;
  8932. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  8933. var instancesBuffer = this._currentInstanceBuffers[i];
  8934. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  8935. boundBuffer = instancesBuffer;
  8936. this.bindArrayBuffer(instancesBuffer);
  8937. }
  8938. var offsetLocation = this._currentInstanceLocations[i];
  8939. this._gl.vertexAttribDivisor(offsetLocation, 0);
  8940. }
  8941. this._currentInstanceBuffers.length = 0;
  8942. this._currentInstanceLocations.length = 0;
  8943. };
  8944. Engine.prototype.releaseVertexArrayObject = function (vao) {
  8945. this._gl.deleteVertexArray(vao);
  8946. };
  8947. Engine.prototype._releaseBuffer = function (buffer) {
  8948. buffer.references--;
  8949. if (buffer.references === 0) {
  8950. this._gl.deleteBuffer(buffer);
  8951. return true;
  8952. }
  8953. return false;
  8954. };
  8955. Engine.prototype.createInstancesBuffer = function (capacity) {
  8956. var buffer = this._gl.createBuffer();
  8957. buffer.capacity = capacity;
  8958. this.bindArrayBuffer(buffer);
  8959. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  8960. return buffer;
  8961. };
  8962. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  8963. this._gl.deleteBuffer(buffer);
  8964. };
  8965. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  8966. this.bindArrayBuffer(instancesBuffer);
  8967. if (data) {
  8968. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8969. }
  8970. if (offsetLocations[0].index !== undefined) {
  8971. var stride = 0;
  8972. for (var i = 0; i < offsetLocations.length; i++) {
  8973. var ai = offsetLocations[i];
  8974. stride += ai.attributeSize * 4;
  8975. }
  8976. for (var i = 0; i < offsetLocations.length; i++) {
  8977. var ai = offsetLocations[i];
  8978. if (!this._vertexAttribArraysEnabled[ai.index]) {
  8979. this._gl.enableVertexAttribArray(ai.index);
  8980. this._vertexAttribArraysEnabled[ai.index] = true;
  8981. }
  8982. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  8983. this._gl.vertexAttribDivisor(ai.index, 1);
  8984. this._currentInstanceLocations.push(ai.index);
  8985. this._currentInstanceBuffers.push(instancesBuffer);
  8986. }
  8987. }
  8988. else {
  8989. for (var index = 0; index < 4; index++) {
  8990. var offsetLocation = offsetLocations[index];
  8991. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  8992. this._gl.enableVertexAttribArray(offsetLocation);
  8993. this._vertexAttribArraysEnabled[offsetLocation] = true;
  8994. }
  8995. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  8996. this._gl.vertexAttribDivisor(offsetLocation, 1);
  8997. this._currentInstanceLocations.push(offsetLocation);
  8998. this._currentInstanceBuffers.push(instancesBuffer);
  8999. }
  9000. }
  9001. };
  9002. Engine.prototype.applyStates = function () {
  9003. this._depthCullingState.apply(this._gl);
  9004. this._stencilState.apply(this._gl);
  9005. this._alphaState.apply(this._gl);
  9006. };
  9007. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9008. // Apply states
  9009. this.applyStates();
  9010. this._drawCalls.addCount(1, false);
  9011. // Render
  9012. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9013. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9014. if (instancesCount) {
  9015. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9016. return;
  9017. }
  9018. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9019. };
  9020. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9021. // Apply states
  9022. this.applyStates();
  9023. this._drawCalls.addCount(1, false);
  9024. if (instancesCount) {
  9025. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9026. return;
  9027. }
  9028. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9029. };
  9030. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9031. // Apply states
  9032. this.applyStates();
  9033. this._drawCalls.addCount(1, false);
  9034. if (instancesCount) {
  9035. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9036. return;
  9037. }
  9038. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9039. };
  9040. // Shaders
  9041. Engine.prototype._releaseEffect = function (effect) {
  9042. if (this._compiledEffects[effect._key]) {
  9043. delete this._compiledEffects[effect._key];
  9044. if (effect.getProgram()) {
  9045. this._gl.deleteProgram(effect.getProgram());
  9046. }
  9047. }
  9048. };
  9049. /**
  9050. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9051. * @param samplers An array of string used to represent textures
  9052. */
  9053. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9054. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9055. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9056. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9057. if (this._compiledEffects[name]) {
  9058. var compiledEffect = this._compiledEffects[name];
  9059. if (onCompiled && compiledEffect.isReady()) {
  9060. onCompiled(compiledEffect);
  9061. }
  9062. return compiledEffect;
  9063. }
  9064. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9065. effect._key = name;
  9066. this._compiledEffects[name] = effect;
  9067. return effect;
  9068. };
  9069. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9070. if (uniformsNames === void 0) { uniformsNames = []; }
  9071. if (samplers === void 0) { samplers = []; }
  9072. if (defines === void 0) { defines = ""; }
  9073. return this.createEffect({
  9074. vertex: "particles",
  9075. fragmentElement: fragmentName
  9076. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9077. };
  9078. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  9079. context = context || this._gl;
  9080. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9081. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9082. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9083. var shaderProgram = context.createProgram();
  9084. context.attachShader(shaderProgram, vertexShader);
  9085. context.attachShader(shaderProgram, fragmentShader);
  9086. context.linkProgram(shaderProgram);
  9087. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9088. if (!linked) {
  9089. context.validateProgram(shaderProgram);
  9090. var error = context.getProgramInfoLog(shaderProgram);
  9091. if (error) {
  9092. throw new Error(error);
  9093. }
  9094. }
  9095. context.deleteShader(vertexShader);
  9096. context.deleteShader(fragmentShader);
  9097. return shaderProgram;
  9098. };
  9099. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9100. var results = [];
  9101. for (var index = 0; index < uniformsNames.length; index++) {
  9102. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9103. }
  9104. return results;
  9105. };
  9106. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9107. var results = [];
  9108. for (var index = 0; index < attributesNames.length; index++) {
  9109. try {
  9110. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9111. }
  9112. catch (e) {
  9113. results.push(-1);
  9114. }
  9115. }
  9116. return results;
  9117. };
  9118. Engine.prototype.enableEffect = function (effect) {
  9119. // Use program
  9120. this.setProgram(effect.getProgram());
  9121. this._currentEffect = effect;
  9122. if (effect.onBind) {
  9123. effect.onBind(effect);
  9124. }
  9125. effect.onBindObservable.notifyObservers(effect);
  9126. };
  9127. Engine.prototype.setIntArray = function (uniform, array) {
  9128. if (!uniform)
  9129. return;
  9130. this._gl.uniform1iv(uniform, array);
  9131. };
  9132. Engine.prototype.setIntArray2 = function (uniform, array) {
  9133. if (!uniform || array.length % 2 !== 0)
  9134. return;
  9135. this._gl.uniform2iv(uniform, array);
  9136. };
  9137. Engine.prototype.setIntArray3 = function (uniform, array) {
  9138. if (!uniform || array.length % 3 !== 0)
  9139. return;
  9140. this._gl.uniform3iv(uniform, array);
  9141. };
  9142. Engine.prototype.setIntArray4 = function (uniform, array) {
  9143. if (!uniform || array.length % 4 !== 0)
  9144. return;
  9145. this._gl.uniform4iv(uniform, array);
  9146. };
  9147. Engine.prototype.setFloatArray = function (uniform, array) {
  9148. if (!uniform)
  9149. return;
  9150. this._gl.uniform1fv(uniform, array);
  9151. };
  9152. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9153. if (!uniform || array.length % 2 !== 0)
  9154. return;
  9155. this._gl.uniform2fv(uniform, array);
  9156. };
  9157. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9158. if (!uniform || array.length % 3 !== 0)
  9159. return;
  9160. this._gl.uniform3fv(uniform, array);
  9161. };
  9162. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9163. if (!uniform || array.length % 4 !== 0)
  9164. return;
  9165. this._gl.uniform4fv(uniform, array);
  9166. };
  9167. Engine.prototype.setArray = function (uniform, array) {
  9168. if (!uniform)
  9169. return;
  9170. this._gl.uniform1fv(uniform, array);
  9171. };
  9172. Engine.prototype.setArray2 = function (uniform, array) {
  9173. if (!uniform || array.length % 2 !== 0)
  9174. return;
  9175. this._gl.uniform2fv(uniform, array);
  9176. };
  9177. Engine.prototype.setArray3 = function (uniform, array) {
  9178. if (!uniform || array.length % 3 !== 0)
  9179. return;
  9180. this._gl.uniform3fv(uniform, array);
  9181. };
  9182. Engine.prototype.setArray4 = function (uniform, array) {
  9183. if (!uniform || array.length % 4 !== 0)
  9184. return;
  9185. this._gl.uniform4fv(uniform, array);
  9186. };
  9187. Engine.prototype.setMatrices = function (uniform, matrices) {
  9188. if (!uniform)
  9189. return;
  9190. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9191. };
  9192. Engine.prototype.setMatrix = function (uniform, matrix) {
  9193. if (!uniform)
  9194. return;
  9195. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9196. };
  9197. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9198. if (!uniform)
  9199. return;
  9200. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9201. };
  9202. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9203. if (!uniform)
  9204. return;
  9205. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9206. };
  9207. Engine.prototype.setFloat = function (uniform, value) {
  9208. if (!uniform)
  9209. return;
  9210. this._gl.uniform1f(uniform, value);
  9211. };
  9212. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9213. if (!uniform)
  9214. return;
  9215. this._gl.uniform2f(uniform, x, y);
  9216. };
  9217. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9218. if (!uniform)
  9219. return;
  9220. this._gl.uniform3f(uniform, x, y, z);
  9221. };
  9222. Engine.prototype.setBool = function (uniform, bool) {
  9223. if (!uniform)
  9224. return;
  9225. this._gl.uniform1i(uniform, bool);
  9226. };
  9227. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9228. if (!uniform)
  9229. return;
  9230. this._gl.uniform4f(uniform, x, y, z, w);
  9231. };
  9232. Engine.prototype.setColor3 = function (uniform, color3) {
  9233. if (!uniform)
  9234. return;
  9235. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9236. };
  9237. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9238. if (!uniform)
  9239. return;
  9240. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9241. };
  9242. // States
  9243. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9244. if (zOffset === void 0) { zOffset = 0; }
  9245. if (reverseSide === void 0) { reverseSide = false; }
  9246. // Culling
  9247. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9248. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9249. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9250. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9251. if (culling) {
  9252. this._depthCullingState.cullFace = cullFace;
  9253. this._depthCullingState.cull = true;
  9254. }
  9255. else {
  9256. this._depthCullingState.cull = false;
  9257. }
  9258. }
  9259. // Z offset
  9260. this.setZOffset(zOffset);
  9261. };
  9262. Engine.prototype.setZOffset = function (value) {
  9263. this._depthCullingState.zOffset = value;
  9264. };
  9265. Engine.prototype.getZOffset = function () {
  9266. return this._depthCullingState.zOffset;
  9267. };
  9268. Engine.prototype.setDepthBuffer = function (enable) {
  9269. this._depthCullingState.depthTest = enable;
  9270. };
  9271. Engine.prototype.getDepthWrite = function () {
  9272. return this._depthCullingState.depthMask;
  9273. };
  9274. Engine.prototype.setDepthWrite = function (enable) {
  9275. this._depthCullingState.depthMask = enable;
  9276. };
  9277. Engine.prototype.setColorWrite = function (enable) {
  9278. this._gl.colorMask(enable, enable, enable, enable);
  9279. };
  9280. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  9281. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  9282. };
  9283. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  9284. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  9285. if (this._alphaMode === mode) {
  9286. return;
  9287. }
  9288. switch (mode) {
  9289. case Engine.ALPHA_DISABLE:
  9290. this._alphaState.alphaBlend = false;
  9291. break;
  9292. case Engine.ALPHA_PREMULTIPLIED:
  9293. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9294. this._alphaState.alphaBlend = true;
  9295. break;
  9296. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  9297. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9298. this._alphaState.alphaBlend = true;
  9299. break;
  9300. case Engine.ALPHA_COMBINE:
  9301. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9302. this._alphaState.alphaBlend = true;
  9303. break;
  9304. case Engine.ALPHA_ONEONE:
  9305. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9306. this._alphaState.alphaBlend = true;
  9307. break;
  9308. case Engine.ALPHA_ADD:
  9309. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9310. this._alphaState.alphaBlend = true;
  9311. break;
  9312. case Engine.ALPHA_SUBTRACT:
  9313. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9314. this._alphaState.alphaBlend = true;
  9315. break;
  9316. case Engine.ALPHA_MULTIPLY:
  9317. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  9318. this._alphaState.alphaBlend = true;
  9319. break;
  9320. case Engine.ALPHA_MAXIMIZED:
  9321. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9322. this._alphaState.alphaBlend = true;
  9323. break;
  9324. case Engine.ALPHA_INTERPOLATE:
  9325. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  9326. this._alphaState.alphaBlend = true;
  9327. break;
  9328. case Engine.ALPHA_SCREENMODE:
  9329. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9330. this._alphaState.alphaBlend = true;
  9331. break;
  9332. }
  9333. if (!noDepthWriteChange) {
  9334. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9335. }
  9336. this._alphaMode = mode;
  9337. };
  9338. Engine.prototype.getAlphaMode = function () {
  9339. return this._alphaMode;
  9340. };
  9341. Engine.prototype.setAlphaTesting = function (enable) {
  9342. this._alphaTest = enable;
  9343. };
  9344. Engine.prototype.getAlphaTesting = function () {
  9345. return !!this._alphaTest;
  9346. };
  9347. // Textures
  9348. Engine.prototype.wipeCaches = function (bruteForce) {
  9349. if (this.preventCacheWipeBetweenFrames) {
  9350. return;
  9351. }
  9352. this.resetTextureCache();
  9353. this._currentEffect = null;
  9354. // 6/8/2017: deltakosh: Should not be required anymore.
  9355. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  9356. if (bruteForce) {
  9357. this._currentProgram = null;
  9358. this._stencilState.reset();
  9359. this._depthCullingState.reset();
  9360. this.setDepthFunctionToLessOrEqual();
  9361. this._alphaState.reset();
  9362. }
  9363. this._cachedVertexBuffers = null;
  9364. this._cachedIndexBuffer = null;
  9365. this._cachedEffectForVertexBuffers = null;
  9366. this._unbindVertexArrayObject();
  9367. this.bindIndexBuffer(null);
  9368. this.bindArrayBuffer(null);
  9369. };
  9370. /**
  9371. * Set the compressed texture format to use, based on the formats you have, and the formats
  9372. * supported by the hardware / browser.
  9373. *
  9374. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9375. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9376. * to API arguments needed to compressed textures. This puts the burden on the container
  9377. * generator to house the arcane code for determining these for current & future formats.
  9378. *
  9379. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9380. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9381. *
  9382. * Note: The result of this call is not taken into account when a texture is base64.
  9383. *
  9384. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9385. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9386. *
  9387. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  9388. * @returns The extension selected.
  9389. */
  9390. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9391. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9392. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9393. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9394. return this._textureFormatInUse = this._texturesSupported[i];
  9395. }
  9396. }
  9397. }
  9398. // actively set format to nothing, to allow this to be called more than once
  9399. // and possibly fail the 2nd time
  9400. return this._textureFormatInUse = null;
  9401. };
  9402. /**
  9403. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  9404. * @param {string} urlArg- This contains one of the following:
  9405. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  9406. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  9407. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  9408. *
  9409. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  9410. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  9411. * @param {Scene} scene- Needed for loading to the correct scene.
  9412. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  9413. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  9414. * @param {callback} onError- Optional callback to be called upon failure.
  9415. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  9416. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  9417. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  9418. *
  9419. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  9420. */
  9421. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9422. var _this = this;
  9423. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9424. if (onLoad === void 0) { onLoad = null; }
  9425. if (onError === void 0) { onError = null; }
  9426. if (buffer === void 0) { buffer = null; }
  9427. var texture = fallBack ? fallBack : this._gl.createTexture();
  9428. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  9429. var fromData = url.substr(0, 5) === "data:";
  9430. var isBase64 = fromData && url.indexOf("base64") !== -1;
  9431. // establish the file extension, if possible
  9432. var lastDot = url.lastIndexOf('.');
  9433. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  9434. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9435. var isTGA = (extension === ".tga");
  9436. // determine if a ktx file should be substituted
  9437. var isKTX = false;
  9438. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  9439. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9440. isKTX = true;
  9441. }
  9442. scene._addPendingData(texture);
  9443. texture.url = url;
  9444. texture.generateMipMaps = !noMipmap;
  9445. texture.references = 1;
  9446. texture.samplingMode = samplingMode;
  9447. texture.onLoadedCallbacks = [];
  9448. if (onLoad) {
  9449. texture.onLoadedCallbacks.push(onLoad);
  9450. }
  9451. if (!fallBack)
  9452. this._loadedTexturesCache.push(texture);
  9453. var onerror = function () {
  9454. scene._removePendingData(texture);
  9455. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9456. if (isKTX) {
  9457. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  9458. }
  9459. else if (onError) {
  9460. onError();
  9461. }
  9462. };
  9463. var callback;
  9464. // processing for non-image formats
  9465. if (isKTX || isTGA || isDDS) {
  9466. if (isKTX) {
  9467. callback = function (data) {
  9468. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9469. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9470. ktx.uploadLevels(_this._gl, !noMipmap);
  9471. return false;
  9472. }, samplingMode);
  9473. };
  9474. }
  9475. else if (isTGA) {
  9476. callback = function (arrayBuffer) {
  9477. var data = new Uint8Array(arrayBuffer);
  9478. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9479. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9480. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9481. return false;
  9482. }, samplingMode);
  9483. };
  9484. }
  9485. else if (isDDS) {
  9486. callback = function (data) {
  9487. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9488. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9489. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9490. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, data, info, loadMipmap, 1);
  9491. return false;
  9492. }, samplingMode);
  9493. };
  9494. }
  9495. if (!buffer) {
  9496. BABYLON.Tools.LoadFile(url, function (data) {
  9497. callback(data);
  9498. }, null, scene.database, true, onerror);
  9499. }
  9500. else {
  9501. callback(buffer);
  9502. }
  9503. // image format processing
  9504. }
  9505. else {
  9506. var onload = function (img) {
  9507. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  9508. var gl = _this._gl;
  9509. var isPot = (img.width === potWidth && img.height === potHeight);
  9510. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  9511. if (isPot) {
  9512. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  9513. return false;
  9514. }
  9515. // Using shaders to rescale because canvas.drawImage is lossy
  9516. var source = gl.createTexture();
  9517. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  9518. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  9519. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9520. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  9521. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9522. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9523. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  9524. _this._releaseTexture(source);
  9525. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9526. continuationCallback();
  9527. });
  9528. return true;
  9529. }, samplingMode);
  9530. };
  9531. if (!fromData || isBase64)
  9532. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  9533. else if (buffer instanceof Array || typeof buffer === "string")
  9534. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  9535. else
  9536. onload(buffer);
  9537. }
  9538. return texture;
  9539. };
  9540. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  9541. var _this = this;
  9542. var rtt = this.createRenderTargetTexture({
  9543. width: destination._width,
  9544. height: destination._height,
  9545. }, {
  9546. generateMipMaps: false,
  9547. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  9548. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  9549. generateDepthBuffer: false,
  9550. generateStencilBuffer: false
  9551. });
  9552. if (!this._rescalePostProcess) {
  9553. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  9554. }
  9555. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  9556. _this._rescalePostProcess.onApply = function (effect) {
  9557. effect._bindTexture("textureSampler", source);
  9558. };
  9559. scene.postProcessManager.directRender([_this._rescalePostProcess], rtt);
  9560. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  9561. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination._width, destination._height, 0);
  9562. _this.unBindFramebuffer(rtt);
  9563. _this._releaseTexture(rtt);
  9564. if (onComplete) {
  9565. onComplete();
  9566. }
  9567. });
  9568. };
  9569. Engine.prototype._getInternalFormat = function (format) {
  9570. var internalFormat = this._gl.RGBA;
  9571. switch (format) {
  9572. case Engine.TEXTUREFORMAT_ALPHA:
  9573. internalFormat = this._gl.ALPHA;
  9574. break;
  9575. case Engine.TEXTUREFORMAT_LUMINANCE:
  9576. internalFormat = this._gl.LUMINANCE;
  9577. break;
  9578. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9579. internalFormat = this._gl.LUMINANCE_ALPHA;
  9580. break;
  9581. case Engine.TEXTUREFORMAT_RGB:
  9582. internalFormat = this._gl.RGB;
  9583. break;
  9584. case Engine.TEXTUREFORMAT_RGBA:
  9585. internalFormat = this._gl.RGBA;
  9586. break;
  9587. }
  9588. return internalFormat;
  9589. };
  9590. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9591. if (compression === void 0) { compression = null; }
  9592. var internalFormat = this._getInternalFormat(format);
  9593. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9594. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9595. if (texture._width % 4 !== 0) {
  9596. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9597. }
  9598. if (compression) {
  9599. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  9600. }
  9601. else {
  9602. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9603. }
  9604. if (texture.generateMipMaps) {
  9605. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9606. }
  9607. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9608. this.resetTextureCache();
  9609. texture.isReady = true;
  9610. };
  9611. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9612. if (compression === void 0) { compression = null; }
  9613. var texture = this._gl.createTexture();
  9614. texture._baseWidth = width;
  9615. texture._baseHeight = height;
  9616. texture._width = width;
  9617. texture._height = height;
  9618. texture.references = 1;
  9619. this.updateRawTexture(texture, data, format, invertY, compression);
  9620. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9621. // Filters
  9622. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9623. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9624. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9625. if (generateMipMaps) {
  9626. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9627. }
  9628. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9629. texture.samplingMode = samplingMode;
  9630. this._loadedTexturesCache.push(texture);
  9631. return texture;
  9632. };
  9633. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9634. var texture = this._gl.createTexture();
  9635. texture._baseWidth = width;
  9636. texture._baseHeight = height;
  9637. if (generateMipMaps) {
  9638. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  9639. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  9640. }
  9641. this.resetTextureCache();
  9642. texture._width = width;
  9643. texture._height = height;
  9644. texture.isReady = false;
  9645. texture.generateMipMaps = generateMipMaps;
  9646. texture.references = 1;
  9647. texture.samplingMode = samplingMode;
  9648. this.updateTextureSamplingMode(samplingMode, texture);
  9649. this._loadedTexturesCache.push(texture);
  9650. return texture;
  9651. };
  9652. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9653. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9654. if (texture.isCube) {
  9655. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9656. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9657. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9658. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9659. }
  9660. else {
  9661. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9662. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9663. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9664. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9665. }
  9666. texture.samplingMode = samplingMode;
  9667. };
  9668. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9669. if (premulAlpha === void 0) { premulAlpha = false; }
  9670. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9671. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9672. if (premulAlpha) {
  9673. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9674. }
  9675. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9676. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9677. if (texture.generateMipMaps) {
  9678. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9679. }
  9680. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9681. if (premulAlpha) {
  9682. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9683. }
  9684. this.resetTextureCache();
  9685. texture.isReady = true;
  9686. };
  9687. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9688. if (texture._isDisabled) {
  9689. return;
  9690. }
  9691. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9692. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  9693. try {
  9694. // Testing video texture support
  9695. if (this._videoTextureSupported === undefined) {
  9696. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9697. if (this._gl.getError() !== 0) {
  9698. this._videoTextureSupported = false;
  9699. }
  9700. else {
  9701. this._videoTextureSupported = true;
  9702. }
  9703. }
  9704. // Copy video through the current working canvas if video texture is not supported
  9705. if (!this._videoTextureSupported) {
  9706. if (!texture._workingCanvas) {
  9707. texture._workingCanvas = document.createElement("canvas");
  9708. texture._workingContext = texture._workingCanvas.getContext("2d");
  9709. texture._workingCanvas.width = texture._width;
  9710. texture._workingCanvas.height = texture._height;
  9711. }
  9712. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  9713. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9714. }
  9715. else {
  9716. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9717. }
  9718. if (texture.generateMipMaps) {
  9719. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9720. }
  9721. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9722. this.resetTextureCache();
  9723. texture.isReady = true;
  9724. }
  9725. catch (ex) {
  9726. // Something unexpected
  9727. // Let's disable the texture
  9728. texture._isDisabled = true;
  9729. }
  9730. };
  9731. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9732. // old version had a "generateMipMaps" arg instead of options.
  9733. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  9734. // in the same way, generateDepthBuffer is defaulted to true
  9735. var generateMipMaps = false;
  9736. var generateDepthBuffer = true;
  9737. var generateStencilBuffer = false;
  9738. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9739. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9740. if (options !== undefined) {
  9741. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9742. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9743. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9744. type = options.type === undefined ? type : options.type;
  9745. if (options.samplingMode !== undefined) {
  9746. samplingMode = options.samplingMode;
  9747. }
  9748. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9749. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9750. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9751. }
  9752. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9753. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9754. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9755. }
  9756. }
  9757. var gl = this._gl;
  9758. var texture = gl.createTexture();
  9759. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9760. var width = size.width || size;
  9761. var height = size.height || size;
  9762. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9763. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9764. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9765. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9766. }
  9767. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9768. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9769. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9770. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9771. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9772. // Create the framebuffer
  9773. var framebuffer = gl.createFramebuffer();
  9774. this.bindUnboundFramebuffer(framebuffer);
  9775. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9776. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9777. if (generateMipMaps) {
  9778. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9779. }
  9780. // Unbind
  9781. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9782. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9783. this.bindUnboundFramebuffer(null);
  9784. texture._framebuffer = framebuffer;
  9785. texture._baseWidth = width;
  9786. texture._baseHeight = height;
  9787. texture._width = width;
  9788. texture._height = height;
  9789. texture.isReady = true;
  9790. texture.samples = 1;
  9791. texture.generateMipMaps = generateMipMaps;
  9792. texture.references = 1;
  9793. texture.samplingMode = samplingMode;
  9794. texture.type = type;
  9795. texture._generateDepthBuffer = generateDepthBuffer;
  9796. texture._generateStencilBuffer = generateStencilBuffer;
  9797. this.resetTextureCache();
  9798. this._loadedTexturesCache.push(texture);
  9799. return texture;
  9800. };
  9801. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  9802. var generateMipMaps = false;
  9803. var generateDepthBuffer = true;
  9804. var generateStencilBuffer = false;
  9805. var generateDepthTexture = false;
  9806. var textureCount = 1;
  9807. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  9808. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9809. var types = [], samplingModes = [];
  9810. if (options !== undefined) {
  9811. generateMipMaps = options.generateMipMaps;
  9812. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9813. generateStencilBuffer = options.generateStencilBuffer;
  9814. generateDepthTexture = options.generateDepthTexture;
  9815. textureCount = options.textureCount || 1;
  9816. if (options.types) {
  9817. types = options.types;
  9818. }
  9819. if (options.samplingModes) {
  9820. samplingModes = options.samplingModes;
  9821. }
  9822. }
  9823. var gl = this._gl;
  9824. // Create the framebuffer
  9825. var framebuffer = gl.createFramebuffer();
  9826. this.bindUnboundFramebuffer(framebuffer);
  9827. var width = size.width || size;
  9828. var height = size.height || size;
  9829. var textures = [];
  9830. var attachments = [];
  9831. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9832. for (var i = 0; i < textureCount; i++) {
  9833. var samplingMode = samplingModes[i] || defaultSamplingMode;
  9834. var type = types[i] || defaultType;
  9835. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9836. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9837. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9838. }
  9839. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9840. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9841. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9842. }
  9843. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9844. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9845. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9846. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9847. }
  9848. var texture = gl.createTexture();
  9849. var attachment = gl["COLOR_ATTACHMENT" + i];
  9850. textures.push(texture);
  9851. attachments.push(attachment);
  9852. gl.activeTexture(gl["TEXTURE" + i]);
  9853. gl.bindTexture(gl.TEXTURE_2D, texture);
  9854. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9855. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9856. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9857. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9858. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9859. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture, 0);
  9860. if (generateMipMaps) {
  9861. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9862. }
  9863. // Unbind
  9864. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9865. texture._framebuffer = framebuffer;
  9866. texture._depthStencilBuffer = depthStencilBuffer;
  9867. texture._baseWidth = width;
  9868. texture._baseHeight = height;
  9869. texture._width = width;
  9870. texture._height = height;
  9871. texture.isReady = true;
  9872. texture.samples = 1;
  9873. texture.generateMipMaps = generateMipMaps;
  9874. texture.references = 1;
  9875. texture.samplingMode = samplingMode;
  9876. texture.type = type;
  9877. texture._generateDepthBuffer = generateDepthBuffer;
  9878. texture._generateStencilBuffer = generateStencilBuffer;
  9879. this._loadedTexturesCache.push(texture);
  9880. }
  9881. if (generateDepthTexture) {
  9882. // Depth texture
  9883. var depthTexture = gl.createTexture();
  9884. gl.activeTexture(gl.TEXTURE0);
  9885. gl.bindTexture(gl.TEXTURE_2D, depthTexture);
  9886. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9887. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9888. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9889. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9890. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  9891. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture, 0);
  9892. depthTexture._framebuffer = framebuffer;
  9893. depthTexture._baseWidth = width;
  9894. depthTexture._baseHeight = height;
  9895. depthTexture._width = width;
  9896. depthTexture._height = height;
  9897. depthTexture.isReady = true;
  9898. depthTexture.samples = 1;
  9899. depthTexture.generateMipMaps = generateMipMaps;
  9900. depthTexture.references = 1;
  9901. depthTexture.samplingMode = gl.NEAREST;
  9902. depthTexture._generateDepthBuffer = generateDepthBuffer;
  9903. depthTexture._generateStencilBuffer = generateStencilBuffer;
  9904. textures.push(depthTexture);
  9905. this._loadedTexturesCache.push(depthTexture);
  9906. }
  9907. gl.drawBuffers(attachments);
  9908. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9909. this.bindUnboundFramebuffer(null);
  9910. this.resetTextureCache();
  9911. return textures;
  9912. };
  9913. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  9914. if (samples === void 0) { samples = 1; }
  9915. var depthStencilBuffer = null;
  9916. var gl = this._gl;
  9917. // Create the depth/stencil buffer
  9918. if (generateStencilBuffer) {
  9919. depthStencilBuffer = gl.createRenderbuffer();
  9920. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9921. if (samples > 1) {
  9922. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  9923. }
  9924. else {
  9925. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  9926. }
  9927. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9928. }
  9929. else if (generateDepthBuffer) {
  9930. depthStencilBuffer = gl.createRenderbuffer();
  9931. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9932. if (samples > 1) {
  9933. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  9934. }
  9935. else {
  9936. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  9937. }
  9938. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9939. }
  9940. return depthStencilBuffer;
  9941. };
  9942. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  9943. if (this.webGLVersion < 2) {
  9944. return 1;
  9945. }
  9946. if (texture.samples === samples) {
  9947. return samples;
  9948. }
  9949. var gl = this._gl;
  9950. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  9951. // Dispose previous render buffers
  9952. if (texture._depthStencilBuffer) {
  9953. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9954. }
  9955. if (texture._MSAAFramebuffer) {
  9956. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9957. }
  9958. if (texture._MSAARenderBuffer) {
  9959. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9960. }
  9961. if (samples > 1) {
  9962. texture._MSAAFramebuffer = gl.createFramebuffer();
  9963. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  9964. var colorRenderbuffer = gl.createRenderbuffer();
  9965. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  9966. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture._width, texture._height);
  9967. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  9968. texture._MSAARenderBuffer = colorRenderbuffer;
  9969. }
  9970. else {
  9971. this.bindUnboundFramebuffer(texture._framebuffer);
  9972. }
  9973. texture.samples = samples;
  9974. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture._width, texture._height, samples);
  9975. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9976. this.bindUnboundFramebuffer(null);
  9977. return samples;
  9978. };
  9979. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  9980. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  9981. };
  9982. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  9983. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  9984. };
  9985. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  9986. var gl = this._gl;
  9987. var texture = gl.createTexture();
  9988. var generateMipMaps = true;
  9989. var generateDepthBuffer = true;
  9990. var generateStencilBuffer = false;
  9991. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9992. if (options !== undefined) {
  9993. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9994. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9995. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9996. if (options.samplingMode !== undefined) {
  9997. samplingMode = options.samplingMode;
  9998. }
  9999. }
  10000. texture.isCube = true;
  10001. texture.references = 1;
  10002. texture.generateMipMaps = generateMipMaps;
  10003. texture.references = 1;
  10004. texture.samples = 1;
  10005. texture.samplingMode = samplingMode;
  10006. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10007. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10008. for (var face = 0; face < 6; face++) {
  10009. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10010. }
  10011. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10012. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10013. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10014. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10015. // Create the framebuffer
  10016. var framebuffer = gl.createFramebuffer();
  10017. this.bindUnboundFramebuffer(framebuffer);
  10018. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10019. // Mipmaps
  10020. if (texture.generateMipMaps) {
  10021. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10022. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10023. }
  10024. // Unbind
  10025. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10026. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10027. this.bindUnboundFramebuffer(null);
  10028. texture._framebuffer = framebuffer;
  10029. texture._width = size;
  10030. texture._height = size;
  10031. texture.isReady = true;
  10032. this.resetTextureCache();
  10033. this._loadedTexturesCache.push(texture);
  10034. return texture;
  10035. };
  10036. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  10037. var _this = this;
  10038. if (onError === void 0) { onError = null; }
  10039. if (forcedExtension === void 0) { forcedExtension = null; }
  10040. var callback = function (loadData) {
  10041. if (_this._caps.textureLOD || !loadData) {
  10042. // Do not add extra process if texture lod is supported.
  10043. if (onLoad) {
  10044. onLoad();
  10045. }
  10046. return;
  10047. }
  10048. var mipSlices = 3;
  10049. var gl = _this._gl;
  10050. var width = loadData.width;
  10051. if (!width) {
  10052. return;
  10053. }
  10054. var textures = [];
  10055. for (var i = 0; i < mipSlices; i++) {
  10056. //compute LOD from even spacing in smoothness (matching shader calculation)
  10057. var smoothness = i / (mipSlices - 1);
  10058. var roughness = 1 - smoothness;
  10059. var minLODIndex = offset; // roughness = 0
  10060. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  10061. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  10062. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  10063. var glTextureFromLod = gl.createTexture();
  10064. glTextureFromLod.isCube = true;
  10065. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  10066. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10067. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10068. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10069. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10070. if (loadData.isDDS) {
  10071. var info = loadData.info;
  10072. var data = loadData.data;
  10073. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10074. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, data, info, true, 6, mipmapIndex);
  10075. }
  10076. else {
  10077. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  10078. }
  10079. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10080. // Wrap in a base texture for easy binding.
  10081. var lodTexture = new BABYLON.BaseTexture(scene);
  10082. lodTexture.isCube = true;
  10083. lodTexture._texture = glTextureFromLod;
  10084. glTextureFromLod.isReady = true;
  10085. textures.push(lodTexture);
  10086. }
  10087. loadData.texture._lodTextureHigh = textures[2];
  10088. loadData.texture._lodTextureMid = textures[1];
  10089. loadData.texture._lodTextureLow = textures[0];
  10090. if (onLoad) {
  10091. onLoad();
  10092. }
  10093. };
  10094. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  10095. };
  10096. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  10097. var _this = this;
  10098. if (onLoad === void 0) { onLoad = null; }
  10099. if (onError === void 0) { onError = null; }
  10100. if (forcedExtension === void 0) { forcedExtension = null; }
  10101. var gl = this._gl;
  10102. var texture = gl.createTexture();
  10103. texture.isCube = true;
  10104. texture.url = rootUrl;
  10105. texture.references = 1;
  10106. texture.onLoadedCallbacks = [];
  10107. texture.generateMipMaps = !noMipmap;
  10108. var isKTX = false;
  10109. var isDDS = false;
  10110. var lastDot = rootUrl.lastIndexOf('.');
  10111. var extension = forcedExtension ? forcedExtension : rootUrl.substring(lastDot).toLowerCase();
  10112. if (this._textureFormatInUse) {
  10113. extension = this._textureFormatInUse;
  10114. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  10115. isKTX = true;
  10116. }
  10117. else {
  10118. isDDS = (extension === ".dds");
  10119. }
  10120. if (isKTX) {
  10121. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10122. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  10123. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  10124. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10125. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10126. ktx.uploadLevels(_this._gl, !noMipmap);
  10127. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10128. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10129. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10130. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10131. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10132. _this.resetTextureCache();
  10133. texture._width = ktx.pixelWidth;
  10134. texture._height = ktx.pixelHeight;
  10135. texture.isReady = true;
  10136. }, null, null, true, onError);
  10137. }
  10138. else if (isDDS) {
  10139. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10140. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10141. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  10142. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10143. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10144. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, data, info, loadMipmap, 6);
  10145. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  10146. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10147. }
  10148. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10149. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10150. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10151. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10152. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10153. _this.resetTextureCache();
  10154. texture._width = info.width;
  10155. texture._height = info.height;
  10156. texture.isReady = true;
  10157. texture.type = info.textureType;
  10158. if (onLoad) {
  10159. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  10160. }
  10161. }, null, null, true, onError);
  10162. }
  10163. else {
  10164. cascadeLoad(rootUrl, scene, function (imgs) {
  10165. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  10166. var height = width;
  10167. _this._prepareWorkingCanvas();
  10168. _this._workingCanvas.width = width;
  10169. _this._workingCanvas.height = height;
  10170. var faces = [
  10171. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10172. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10173. ];
  10174. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10175. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10176. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  10177. for (var index = 0; index < faces.length; index++) {
  10178. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  10179. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  10180. }
  10181. if (!noMipmap) {
  10182. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10183. }
  10184. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10185. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10186. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10187. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10188. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10189. _this.resetTextureCache();
  10190. texture._width = width;
  10191. texture._height = height;
  10192. texture.isReady = true;
  10193. texture.onLoadedCallbacks.forEach(function (callback) {
  10194. callback();
  10195. });
  10196. if (onLoad) {
  10197. onLoad();
  10198. }
  10199. }, files, onError);
  10200. }
  10201. this._loadedTexturesCache.push(texture);
  10202. return texture;
  10203. };
  10204. Engine.prototype.updateTextureSize = function (texture, width, height) {
  10205. texture._width = width;
  10206. texture._height = height;
  10207. texture._size = width * height;
  10208. texture._baseWidth = width;
  10209. texture._baseHeight = height;
  10210. };
  10211. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  10212. if (compression === void 0) { compression = null; }
  10213. if (level === void 0) { level = 0; }
  10214. var gl = this._gl;
  10215. var textureType = this._getWebGLTextureType(type);
  10216. var internalFormat = this._getInternalFormat(format);
  10217. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10218. var needConversion = false;
  10219. if (internalFormat === gl.RGB) {
  10220. internalFormat = gl.RGBA;
  10221. needConversion = true;
  10222. }
  10223. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10224. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10225. if (texture._width % 4 !== 0) {
  10226. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  10227. }
  10228. // Data are known to be in +X +Y +Z -X -Y -Z
  10229. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10230. var faceData = data[faceIndex];
  10231. if (compression) {
  10232. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, this.getCaps().s3tc[compression], texture._width, texture._height, 0, faceData);
  10233. }
  10234. else {
  10235. if (needConversion) {
  10236. faceData = this._convertRGBtoRGBATextureData(faceData, texture._width, texture._height, type);
  10237. }
  10238. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture._width, texture._height, 0, internalFormat, textureType, faceData);
  10239. }
  10240. }
  10241. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture._width) && BABYLON.Tools.IsExponentOfTwo(texture._height));
  10242. if (isPot && texture.generateMipMaps && level === 0) {
  10243. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10244. }
  10245. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10246. this.resetTextureCache();
  10247. texture.isReady = true;
  10248. };
  10249. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  10250. if (compression === void 0) { compression = null; }
  10251. var gl = this._gl;
  10252. var texture = gl.createTexture();
  10253. texture.isCube = true;
  10254. texture.references = 1;
  10255. texture.generateMipMaps = generateMipMaps;
  10256. texture.format = format;
  10257. texture.type = type;
  10258. var textureType = this._getWebGLTextureType(type);
  10259. var internalFormat = this._getInternalFormat(format);
  10260. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10261. var needConversion = false;
  10262. if (internalFormat === gl.RGB) {
  10263. internalFormat = gl.RGBA;
  10264. needConversion = true;
  10265. }
  10266. var width = size;
  10267. var height = width;
  10268. texture._width = width;
  10269. texture._height = height;
  10270. // Double check on POT to generate Mips.
  10271. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture._width) && BABYLON.Tools.IsExponentOfTwo(texture._height));
  10272. if (!isPot) {
  10273. generateMipMaps = false;
  10274. }
  10275. // Upload data if needed. The texture won t be ready until then.
  10276. if (data) {
  10277. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  10278. }
  10279. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10280. // Filters
  10281. if (data && generateMipMaps) {
  10282. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10283. }
  10284. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  10285. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10286. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10287. }
  10288. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  10289. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10290. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10291. }
  10292. else {
  10293. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10294. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10295. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10296. }
  10297. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10298. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10299. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10300. return texture;
  10301. };
  10302. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  10303. var _this = this;
  10304. if (onLoad === void 0) { onLoad = null; }
  10305. if (onError === void 0) { onError = null; }
  10306. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10307. if (invertY === void 0) { invertY = false; }
  10308. var gl = this._gl;
  10309. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  10310. scene._addPendingData(texture);
  10311. texture.url = url;
  10312. this._loadedTexturesCache.push(texture);
  10313. var onerror = function () {
  10314. scene._removePendingData(texture);
  10315. if (onError) {
  10316. onError();
  10317. }
  10318. };
  10319. var internalCallback = function (data) {
  10320. var width = texture._width;
  10321. var height = texture._height;
  10322. var faceDataArrays = callback(data);
  10323. if (mipmmapGenerator) {
  10324. var textureType = _this._getWebGLTextureType(type);
  10325. var internalFormat = _this._getInternalFormat(format);
  10326. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  10327. var needConversion = false;
  10328. if (internalFormat === gl.RGB) {
  10329. internalFormat = gl.RGBA;
  10330. needConversion = true;
  10331. }
  10332. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10333. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10334. var mipData = mipmmapGenerator(faceDataArrays);
  10335. for (var level = 0; level < mipData.length; level++) {
  10336. var mipSize = width >> level;
  10337. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10338. var mipFaceData = mipData[level][faceIndex];
  10339. if (needConversion) {
  10340. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  10341. }
  10342. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  10343. }
  10344. }
  10345. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10346. }
  10347. else {
  10348. texture.generateMipMaps = !noMipmap;
  10349. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  10350. }
  10351. texture.isReady = true;
  10352. _this.resetTextureCache();
  10353. scene._removePendingData(texture);
  10354. if (onLoad) {
  10355. onLoad();
  10356. }
  10357. };
  10358. BABYLON.Tools.LoadFile(url, function (data) {
  10359. internalCallback(data);
  10360. }, onerror, scene.database, true);
  10361. return texture;
  10362. };
  10363. ;
  10364. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  10365. var gl = this._gl;
  10366. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  10367. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10368. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10369. if (!noMipmap && !isCompressed) {
  10370. gl.generateMipmap(gl.TEXTURE_2D);
  10371. }
  10372. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10373. this.resetTextureCache();
  10374. scene._removePendingData(texture);
  10375. texture.onLoadedCallbacks.forEach(function (callback) {
  10376. callback();
  10377. });
  10378. texture.onLoadedCallbacks = [];
  10379. };
  10380. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  10381. var _this = this;
  10382. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10383. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  10384. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  10385. var gl = this._gl;
  10386. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10387. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10388. texture._baseWidth = width;
  10389. texture._baseHeight = height;
  10390. texture._width = potWidth;
  10391. texture._height = potHeight;
  10392. texture.isReady = true;
  10393. if (processFunction(potWidth, potHeight, function () {
  10394. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  10395. })) {
  10396. // Returning as texture needs extra async steps
  10397. return;
  10398. }
  10399. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  10400. };
  10401. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  10402. // Create new RGBA data container.
  10403. var rgbaData;
  10404. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  10405. rgbaData = new Float32Array(width * height * 4);
  10406. }
  10407. else {
  10408. rgbaData = new Uint32Array(width * height * 4);
  10409. }
  10410. // Convert each pixel.
  10411. for (var x = 0; x < width; x++) {
  10412. for (var y = 0; y < height; y++) {
  10413. var index = (y * width + x) * 3;
  10414. var newIndex = (y * width + x) * 4;
  10415. // Map Old Value to new value.
  10416. rgbaData[newIndex + 0] = rgbData[index + 0];
  10417. rgbaData[newIndex + 1] = rgbData[index + 1];
  10418. rgbaData[newIndex + 2] = rgbData[index + 2];
  10419. // Add fully opaque alpha channel.
  10420. rgbaData[newIndex + 3] = 1;
  10421. }
  10422. }
  10423. return rgbaData;
  10424. };
  10425. Engine.prototype._releaseFramebufferObjects = function (texture) {
  10426. var gl = this._gl;
  10427. if (texture._framebuffer) {
  10428. gl.deleteFramebuffer(texture._framebuffer);
  10429. texture._framebuffer = null;
  10430. }
  10431. if (texture._depthStencilBuffer) {
  10432. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10433. texture._depthStencilBuffer = null;
  10434. }
  10435. if (texture._MSAAFramebuffer) {
  10436. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10437. texture._MSAAFramebuffer = null;
  10438. }
  10439. if (texture._MSAARenderBuffer) {
  10440. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10441. texture._MSAARenderBuffer = null;
  10442. }
  10443. };
  10444. Engine.prototype._releaseTexture = function (texture) {
  10445. var gl = this._gl;
  10446. this._releaseFramebufferObjects(texture);
  10447. gl.deleteTexture(texture);
  10448. // Unbind channels
  10449. this.unbindAllTextures();
  10450. var index = this._loadedTexturesCache.indexOf(texture);
  10451. if (index !== -1) {
  10452. this._loadedTexturesCache.splice(index, 1);
  10453. }
  10454. // Integrated fixed lod samplers.
  10455. if (texture._lodTextureHigh) {
  10456. texture._lodTextureHigh.dispose();
  10457. }
  10458. if (texture._lodTextureMid) {
  10459. texture._lodTextureMid.dispose();
  10460. }
  10461. if (texture._lodTextureLow) {
  10462. texture._lodTextureLow.dispose();
  10463. }
  10464. };
  10465. Engine.prototype.setProgram = function (program) {
  10466. if (this._currentProgram !== program) {
  10467. this._gl.useProgram(program);
  10468. this._currentProgram = program;
  10469. }
  10470. };
  10471. Engine.prototype.bindSamplers = function (effect) {
  10472. this.setProgram(effect.getProgram());
  10473. var samplers = effect.getSamplers();
  10474. for (var index = 0; index < samplers.length; index++) {
  10475. var uniform = effect.getUniform(samplers[index]);
  10476. this._gl.uniform1i(uniform, index);
  10477. }
  10478. this._currentEffect = null;
  10479. };
  10480. Engine.prototype.activateTexture = function (texture) {
  10481. if (this._activeTexture !== texture) {
  10482. this._gl.activeTexture(texture);
  10483. this._activeTexture = texture;
  10484. }
  10485. };
  10486. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10487. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10488. this._gl.bindTexture(target, texture);
  10489. this._activeTexturesCache[this._activeTexture] = texture;
  10490. }
  10491. };
  10492. Engine.prototype._bindTexture = function (channel, texture) {
  10493. if (channel < 0) {
  10494. return;
  10495. }
  10496. this.activateTexture(this._gl.TEXTURE0 + channel);
  10497. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10498. };
  10499. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10500. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10501. };
  10502. Engine.prototype.unbindAllTextures = function () {
  10503. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10504. this.activateTexture(this._gl["TEXTURE" + channel]);
  10505. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10506. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10507. }
  10508. };
  10509. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10510. if (channel < 0) {
  10511. return;
  10512. }
  10513. this._gl.uniform1i(uniform, channel);
  10514. this._setTexture(channel, texture);
  10515. };
  10516. Engine.prototype._setTexture = function (channel, texture) {
  10517. // Not ready?
  10518. if (!texture) {
  10519. if (this._activeTexturesCache[channel] != null) {
  10520. this.activateTexture(this._gl["TEXTURE" + channel]);
  10521. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10522. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10523. }
  10524. return;
  10525. }
  10526. // Video
  10527. var alreadyActivated = false;
  10528. if (texture.video) {
  10529. this.activateTexture(this._gl["TEXTURE" + channel]);
  10530. alreadyActivated = true;
  10531. texture.update();
  10532. }
  10533. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10534. texture.delayLoad();
  10535. return;
  10536. }
  10537. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  10538. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  10539. if (this._activeTexturesCache[channel] === internalTexture) {
  10540. return;
  10541. }
  10542. if (!alreadyActivated) {
  10543. this.activateTexture(this._gl["TEXTURE" + channel]);
  10544. }
  10545. if (internalTexture.isCube) {
  10546. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10547. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10548. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10549. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10550. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10551. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10552. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10553. }
  10554. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10555. }
  10556. else {
  10557. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10558. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10559. internalTexture._cachedWrapU = texture.wrapU;
  10560. switch (texture.wrapU) {
  10561. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10562. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10563. break;
  10564. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10565. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10566. break;
  10567. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10568. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10569. break;
  10570. }
  10571. }
  10572. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10573. internalTexture._cachedWrapV = texture.wrapV;
  10574. switch (texture.wrapV) {
  10575. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10576. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10577. break;
  10578. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10579. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10580. break;
  10581. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10582. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10583. break;
  10584. }
  10585. }
  10586. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10587. }
  10588. };
  10589. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10590. if (channel < 0) {
  10591. return;
  10592. }
  10593. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10594. this._textureUnits = new Int32Array(textures.length);
  10595. }
  10596. for (var i = 0; i < textures.length; i++) {
  10597. this._textureUnits[i] = channel + i;
  10598. }
  10599. this._gl.uniform1iv(uniform, this._textureUnits);
  10600. for (var index = 0; index < textures.length; index++) {
  10601. this._setTexture(channel + index, textures[index]);
  10602. }
  10603. };
  10604. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10605. var internalTexture = texture.getInternalTexture();
  10606. if (!internalTexture) {
  10607. return;
  10608. }
  10609. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10610. var value = texture.anisotropicFilteringLevel;
  10611. if (internalTexture.samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10612. value = 1;
  10613. }
  10614. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  10615. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10616. texture._cachedAnisotropicFilteringLevel = value;
  10617. }
  10618. };
  10619. Engine.prototype.readPixels = function (x, y, width, height) {
  10620. var data = new Uint8Array(height * width * 4);
  10621. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10622. return data;
  10623. };
  10624. /**
  10625. * Add an externaly attached data from its key.
  10626. * This method call will fail and return false, if such key already exists.
  10627. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10628. * @param key the unique key that identifies the data
  10629. * @param data the data object to associate to the key for this Engine instance
  10630. * @return true if no such key were already present and the data was added successfully, false otherwise
  10631. */
  10632. Engine.prototype.addExternalData = function (key, data) {
  10633. if (!this._externalData) {
  10634. this._externalData = new BABYLON.StringDictionary();
  10635. }
  10636. return this._externalData.add(key, data);
  10637. };
  10638. /**
  10639. * Get an externaly attached data from its key
  10640. * @param key the unique key that identifies the data
  10641. * @return the associated data, if present (can be null), or undefined if not present
  10642. */
  10643. Engine.prototype.getExternalData = function (key) {
  10644. if (!this._externalData) {
  10645. this._externalData = new BABYLON.StringDictionary();
  10646. }
  10647. return this._externalData.get(key);
  10648. };
  10649. /**
  10650. * Get an externaly attached data from its key, create it using a factory if it's not already present
  10651. * @param key the unique key that identifies the data
  10652. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  10653. * @return the associated data, can be null if the factory returned null.
  10654. */
  10655. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  10656. if (!this._externalData) {
  10657. this._externalData = new BABYLON.StringDictionary();
  10658. }
  10659. return this._externalData.getOrAddWithFactory(key, factory);
  10660. };
  10661. /**
  10662. * Remove an externaly attached data from the Engine instance
  10663. * @param key the unique key that identifies the data
  10664. * @return true if the data was successfully removed, false if it doesn't exist
  10665. */
  10666. Engine.prototype.removeExternalData = function (key) {
  10667. if (!this._externalData) {
  10668. this._externalData = new BABYLON.StringDictionary();
  10669. }
  10670. return this._externalData.remove(key);
  10671. };
  10672. Engine.prototype.releaseInternalTexture = function (texture) {
  10673. if (!texture) {
  10674. return;
  10675. }
  10676. texture.references--;
  10677. // Final reference ?
  10678. if (texture.references === 0) {
  10679. var texturesCache = this.getLoadedTexturesCache();
  10680. var index = texturesCache.indexOf(texture);
  10681. if (index > -1) {
  10682. texturesCache.splice(index, 1);
  10683. }
  10684. this._releaseTexture(texture);
  10685. }
  10686. };
  10687. Engine.prototype.unbindAllAttributes = function () {
  10688. if (this._mustWipeVertexAttributes) {
  10689. this._mustWipeVertexAttributes = false;
  10690. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10691. this._gl.disableVertexAttribArray(i);
  10692. this._vertexAttribArraysEnabled[i] = false;
  10693. this._currentBufferPointers[i].active = false;
  10694. }
  10695. return;
  10696. }
  10697. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  10698. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  10699. continue;
  10700. }
  10701. this._gl.disableVertexAttribArray(i);
  10702. this._vertexAttribArraysEnabled[i] = false;
  10703. this._currentBufferPointers[i].active = false;
  10704. }
  10705. };
  10706. Engine.prototype.releaseEffects = function () {
  10707. for (var name in this._compiledEffects) {
  10708. this._gl.deleteProgram(this._compiledEffects[name]._program);
  10709. }
  10710. this._compiledEffects = {};
  10711. };
  10712. // Dispose
  10713. Engine.prototype.dispose = function () {
  10714. this.hideLoadingUI();
  10715. this.stopRenderLoop();
  10716. // Empty texture
  10717. if (this._emptyTexture) {
  10718. this._releaseTexture(this._emptyTexture);
  10719. this._emptyTexture = null;
  10720. }
  10721. if (this._emptyCubeTexture) {
  10722. this._releaseTexture(this._emptyCubeTexture);
  10723. this._emptyCubeTexture = null;
  10724. }
  10725. // Rescale PP
  10726. if (this._rescalePostProcess) {
  10727. this._rescalePostProcess.dispose();
  10728. }
  10729. // Release scenes
  10730. while (this.scenes.length) {
  10731. this.scenes[0].dispose();
  10732. }
  10733. // Release audio engine
  10734. if (Engine.audioEngine) {
  10735. Engine.audioEngine.dispose();
  10736. }
  10737. // Release effects
  10738. this.releaseEffects();
  10739. // Unbind
  10740. this.unbindAllAttributes();
  10741. if (this._dummyFramebuffer) {
  10742. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  10743. }
  10744. this._gl = null;
  10745. //WebVR
  10746. this.disableVR();
  10747. // Events
  10748. window.removeEventListener("blur", this._onBlur);
  10749. window.removeEventListener("focus", this._onFocus);
  10750. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  10751. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  10752. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  10753. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  10754. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  10755. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  10756. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  10757. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  10758. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  10759. // Remove from Instances
  10760. var index = Engine.Instances.indexOf(this);
  10761. if (index >= 0) {
  10762. Engine.Instances.splice(index, 1);
  10763. }
  10764. this._workingCanvas = null;
  10765. this._workingContext = null;
  10766. this._currentBufferPointers = null;
  10767. this._renderingCanvas = null;
  10768. this._currentProgram = null;
  10769. this.onResizeObservable.clear();
  10770. this.onCanvasBlurObservable.clear();
  10771. BABYLON.Effect.ResetCache();
  10772. };
  10773. // Loading screen
  10774. Engine.prototype.displayLoadingUI = function () {
  10775. var loadingScreen = this.loadingScreen;
  10776. if (loadingScreen) {
  10777. loadingScreen.displayLoadingUI();
  10778. }
  10779. };
  10780. Engine.prototype.hideLoadingUI = function () {
  10781. var loadingScreen = this.loadingScreen;
  10782. if (loadingScreen) {
  10783. loadingScreen.hideLoadingUI();
  10784. }
  10785. };
  10786. Object.defineProperty(Engine.prototype, "loadingScreen", {
  10787. get: function () {
  10788. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen)
  10789. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  10790. return this._loadingScreen;
  10791. },
  10792. set: function (loadingScreen) {
  10793. this._loadingScreen = loadingScreen;
  10794. },
  10795. enumerable: true,
  10796. configurable: true
  10797. });
  10798. Object.defineProperty(Engine.prototype, "loadingUIText", {
  10799. set: function (text) {
  10800. this.loadingScreen.loadingUIText = text;
  10801. },
  10802. enumerable: true,
  10803. configurable: true
  10804. });
  10805. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  10806. set: function (color) {
  10807. this.loadingScreen.loadingUIBackgroundColor = color;
  10808. },
  10809. enumerable: true,
  10810. configurable: true
  10811. });
  10812. Engine.prototype.attachContextLostEvent = function (callback) {
  10813. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  10814. };
  10815. Engine.prototype.attachContextRestoredEvent = function (callback) {
  10816. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  10817. };
  10818. Engine.prototype.getVertexShaderSource = function (program) {
  10819. var shaders = this._gl.getAttachedShaders(program);
  10820. return this._gl.getShaderSource(shaders[0]);
  10821. };
  10822. Engine.prototype.getFragmentShaderSource = function (program) {
  10823. var shaders = this._gl.getAttachedShaders(program);
  10824. return this._gl.getShaderSource(shaders[1]);
  10825. };
  10826. Engine.prototype.getError = function () {
  10827. return this._gl.getError();
  10828. };
  10829. // FPS
  10830. Engine.prototype.getFps = function () {
  10831. return this._fps;
  10832. };
  10833. Engine.prototype.getDeltaTime = function () {
  10834. return this._deltaTime;
  10835. };
  10836. Engine.prototype._measureFps = function () {
  10837. this._performanceMonitor.sampleFrame();
  10838. this._fps = this._performanceMonitor.averageFPS;
  10839. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  10840. };
  10841. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  10842. if (faceIndex === void 0) { faceIndex = -1; }
  10843. var gl = this._gl;
  10844. if (!this._dummyFramebuffer) {
  10845. this._dummyFramebuffer = gl.createFramebuffer();
  10846. }
  10847. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  10848. if (faceIndex > -1) {
  10849. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  10850. }
  10851. else {
  10852. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  10853. }
  10854. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  10855. var buffer;
  10856. switch (readType) {
  10857. case gl.UNSIGNED_BYTE:
  10858. buffer = new Uint8Array(4 * width * height);
  10859. readType = gl.UNSIGNED_BYTE;
  10860. break;
  10861. default:
  10862. buffer = new Float32Array(4 * width * height);
  10863. readType = gl.FLOAT;
  10864. break;
  10865. }
  10866. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  10867. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  10868. return buffer;
  10869. };
  10870. Engine.prototype._canRenderToFloatFramebuffer = function () {
  10871. if (this._webGLVersion > 1) {
  10872. return this._caps.colorBufferFloat;
  10873. }
  10874. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  10875. };
  10876. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  10877. if (this._webGLVersion > 1) {
  10878. return this._caps.colorBufferFloat;
  10879. }
  10880. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  10881. };
  10882. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  10883. Engine.prototype._canRenderToFramebuffer = function (type) {
  10884. var gl = this._gl;
  10885. //clear existing errors
  10886. while (gl.getError() !== gl.NO_ERROR) { }
  10887. var successful = true;
  10888. var texture = gl.createTexture();
  10889. gl.bindTexture(gl.TEXTURE_2D, texture);
  10890. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10891. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10892. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10893. var fb = gl.createFramebuffer();
  10894. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  10895. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  10896. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  10897. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  10898. successful = successful && (gl.getError() === gl.NO_ERROR);
  10899. //try render by clearing frame buffer's color buffer
  10900. if (successful) {
  10901. gl.clear(gl.COLOR_BUFFER_BIT);
  10902. successful = successful && (gl.getError() === gl.NO_ERROR);
  10903. }
  10904. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  10905. if (successful) {
  10906. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  10907. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10908. var readFormat = gl.RGBA;
  10909. var readType = gl.UNSIGNED_BYTE;
  10910. var buffer = new Uint8Array(4);
  10911. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  10912. successful = successful && (gl.getError() === gl.NO_ERROR);
  10913. }
  10914. //clean up
  10915. gl.deleteTexture(texture);
  10916. gl.deleteFramebuffer(fb);
  10917. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10918. //clear accumulated errors
  10919. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  10920. return successful;
  10921. };
  10922. Engine.prototype._getWebGLTextureType = function (type) {
  10923. if (type === Engine.TEXTURETYPE_FLOAT) {
  10924. return this._gl.FLOAT;
  10925. }
  10926. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10927. // Add Half Float Constant.
  10928. return this._gl.HALF_FLOAT_OES;
  10929. }
  10930. return this._gl.UNSIGNED_BYTE;
  10931. };
  10932. ;
  10933. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  10934. if (this._webGLVersion === 1) {
  10935. return this._gl.RGBA;
  10936. }
  10937. if (type === Engine.TEXTURETYPE_FLOAT) {
  10938. return this._gl.RGBA32F;
  10939. }
  10940. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10941. return this._gl.RGBA16F;
  10942. }
  10943. return this._gl.RGBA;
  10944. };
  10945. ;
  10946. // Statics
  10947. Engine.isSupported = function () {
  10948. try {
  10949. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  10950. if (navigator.isCocoonJS) {
  10951. return true;
  10952. }
  10953. var tempcanvas = document.createElement("canvas");
  10954. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  10955. return gl != null && !!window.WebGLRenderingContext;
  10956. }
  10957. catch (e) {
  10958. return false;
  10959. }
  10960. };
  10961. return Engine;
  10962. }());
  10963. Engine.Instances = new Array();
  10964. // Const statics
  10965. Engine._ALPHA_DISABLE = 0;
  10966. Engine._ALPHA_ADD = 1;
  10967. Engine._ALPHA_COMBINE = 2;
  10968. Engine._ALPHA_SUBTRACT = 3;
  10969. Engine._ALPHA_MULTIPLY = 4;
  10970. Engine._ALPHA_MAXIMIZED = 5;
  10971. Engine._ALPHA_ONEONE = 6;
  10972. Engine._ALPHA_PREMULTIPLIED = 7;
  10973. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  10974. Engine._ALPHA_INTERPOLATE = 9;
  10975. Engine._ALPHA_SCREENMODE = 10;
  10976. Engine._DELAYLOADSTATE_NONE = 0;
  10977. Engine._DELAYLOADSTATE_LOADED = 1;
  10978. Engine._DELAYLOADSTATE_LOADING = 2;
  10979. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  10980. Engine._TEXTUREFORMAT_ALPHA = 0;
  10981. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  10982. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  10983. Engine._TEXTUREFORMAT_RGB = 4;
  10984. Engine._TEXTUREFORMAT_RGBA = 5;
  10985. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  10986. Engine._TEXTURETYPE_FLOAT = 1;
  10987. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  10988. // Depht or Stencil test Constants.
  10989. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  10990. 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.
  10991. 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.
  10992. 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.
  10993. 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.
  10994. 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.
  10995. 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.
  10996. 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.
  10997. // Stencil Actions Constants.
  10998. Engine._KEEP = 0x1E00;
  10999. Engine._REPLACE = 0x1E01;
  11000. Engine._INCR = 0x1E02;
  11001. Engine._DECR = 0x1E03;
  11002. Engine._INVERT = 0x150A;
  11003. Engine._INCR_WRAP = 0x8507;
  11004. Engine._DECR_WRAP = 0x8508;
  11005. // Texture rescaling mode
  11006. Engine._SCALEMODE_FLOOR = 1;
  11007. Engine._SCALEMODE_NEAREST = 2;
  11008. Engine._SCALEMODE_CEILING = 3;
  11009. // Updatable statics so stick with vars here
  11010. Engine.CollisionsEpsilon = 0.001;
  11011. Engine.CodeRepository = "src/";
  11012. Engine.ShadersRepository = "src/Shaders/";
  11013. BABYLON.Engine = Engine;
  11014. })(BABYLON || (BABYLON = {}));
  11015. //# sourceMappingURL=babylon.engine.js.map
  11016. /// <reference path="Tools\babylon.decorators.ts" />
  11017. var BABYLON;
  11018. (function (BABYLON) {
  11019. /**
  11020. * Node is the basic class for all scene objects (Mesh, Light Camera).
  11021. */
  11022. var Node = (function () {
  11023. /**
  11024. * @constructor
  11025. * @param {string} name - the name and id to be given to this node
  11026. * @param {BABYLON.Scene} the scene this node will be added to
  11027. */
  11028. function Node(name, scene) {
  11029. this.state = "";
  11030. this.metadata = null;
  11031. this.doNotSerialize = false;
  11032. this.animations = new Array();
  11033. this._ranges = {};
  11034. this._childrenFlag = -1;
  11035. this._isEnabled = true;
  11036. this._isReady = true;
  11037. this._currentRenderId = -1;
  11038. this._parentRenderId = -1;
  11039. /**
  11040. * An event triggered when the mesh is disposed.
  11041. * @type {BABYLON.Observable}
  11042. */
  11043. this.onDisposeObservable = new BABYLON.Observable();
  11044. this.name = name;
  11045. this.id = name;
  11046. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  11047. this._initCache();
  11048. }
  11049. Object.defineProperty(Node.prototype, "parent", {
  11050. get: function () {
  11051. return this._parentNode;
  11052. },
  11053. set: function (parent) {
  11054. if (this._parentNode === parent) {
  11055. return;
  11056. }
  11057. if (this._parentNode) {
  11058. var index = this._parentNode._children.indexOf(this);
  11059. if (index !== -1) {
  11060. this._parentNode._children.splice(index, 1);
  11061. }
  11062. }
  11063. this._parentNode = parent;
  11064. if (this._parentNode) {
  11065. if (!this._parentNode._children) {
  11066. this._parentNode._children = new Array();
  11067. }
  11068. this._parentNode._children.push(this);
  11069. }
  11070. },
  11071. enumerable: true,
  11072. configurable: true
  11073. });
  11074. Node.prototype.getClassName = function () {
  11075. return "Node";
  11076. };
  11077. Object.defineProperty(Node.prototype, "onDispose", {
  11078. set: function (callback) {
  11079. if (this._onDisposeObserver) {
  11080. this.onDisposeObservable.remove(this._onDisposeObserver);
  11081. }
  11082. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  11083. },
  11084. enumerable: true,
  11085. configurable: true
  11086. });
  11087. Node.prototype.getScene = function () {
  11088. return this._scene;
  11089. };
  11090. Node.prototype.getEngine = function () {
  11091. return this._scene.getEngine();
  11092. };
  11093. // override it in derived class
  11094. Node.prototype.getWorldMatrix = function () {
  11095. return BABYLON.Matrix.Identity();
  11096. };
  11097. // override it in derived class if you add new variables to the cache
  11098. // and call the parent class method
  11099. Node.prototype._initCache = function () {
  11100. this._cache = {};
  11101. this._cache.parent = undefined;
  11102. };
  11103. Node.prototype.updateCache = function (force) {
  11104. if (!force && this.isSynchronized())
  11105. return;
  11106. this._cache.parent = this.parent;
  11107. this._updateCache();
  11108. };
  11109. // override it in derived class if you add new variables to the cache
  11110. // and call the parent class method if !ignoreParentClass
  11111. Node.prototype._updateCache = function (ignoreParentClass) {
  11112. };
  11113. // override it in derived class if you add new variables to the cache
  11114. Node.prototype._isSynchronized = function () {
  11115. return true;
  11116. };
  11117. Node.prototype._markSyncedWithParent = function () {
  11118. this._parentRenderId = this.parent._currentRenderId;
  11119. };
  11120. Node.prototype.isSynchronizedWithParent = function () {
  11121. if (!this.parent) {
  11122. return true;
  11123. }
  11124. if (this._parentRenderId !== this.parent._currentRenderId) {
  11125. return false;
  11126. }
  11127. return this.parent.isSynchronized();
  11128. };
  11129. Node.prototype.isSynchronized = function (updateCache) {
  11130. var check = this.hasNewParent();
  11131. check = check || !this.isSynchronizedWithParent();
  11132. check = check || !this._isSynchronized();
  11133. if (updateCache)
  11134. this.updateCache(true);
  11135. return !check;
  11136. };
  11137. Node.prototype.hasNewParent = function (update) {
  11138. if (this._cache.parent === this.parent)
  11139. return false;
  11140. if (update)
  11141. this._cache.parent = this.parent;
  11142. return true;
  11143. };
  11144. /**
  11145. * Is this node ready to be used/rendered
  11146. * @return {boolean} is it ready
  11147. */
  11148. Node.prototype.isReady = function () {
  11149. return this._isReady;
  11150. };
  11151. /**
  11152. * Is this node enabled.
  11153. * If the node has a parent and is enabled, the parent will be inspected as well.
  11154. * @return {boolean} whether this node (and its parent) is enabled.
  11155. * @see setEnabled
  11156. */
  11157. Node.prototype.isEnabled = function () {
  11158. if (!this._isEnabled) {
  11159. return false;
  11160. }
  11161. if (this.parent) {
  11162. return this.parent.isEnabled();
  11163. }
  11164. return true;
  11165. };
  11166. /**
  11167. * Set the enabled state of this node.
  11168. * @param {boolean} value - the new enabled state
  11169. * @see isEnabled
  11170. */
  11171. Node.prototype.setEnabled = function (value) {
  11172. this._isEnabled = value;
  11173. };
  11174. /**
  11175. * Is this node a descendant of the given node.
  11176. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  11177. * @param {BABYLON.Node} ancestor - The parent node to inspect
  11178. * @see parent
  11179. */
  11180. Node.prototype.isDescendantOf = function (ancestor) {
  11181. if (this.parent) {
  11182. if (this.parent === ancestor) {
  11183. return true;
  11184. }
  11185. return this.parent.isDescendantOf(ancestor);
  11186. }
  11187. return false;
  11188. };
  11189. /**
  11190. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  11191. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  11192. * @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.
  11193. * @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.
  11194. */
  11195. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  11196. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  11197. if (!this._children) {
  11198. return;
  11199. }
  11200. for (var index = 0; index < this._children.length; index++) {
  11201. var item = this._children[index];
  11202. if (!predicate || predicate(item)) {
  11203. results.push(item);
  11204. }
  11205. if (!directDescendantsOnly) {
  11206. item._getDescendants(results, false, predicate);
  11207. }
  11208. }
  11209. };
  11210. /**
  11211. * Will return all nodes that have this node as ascendant.
  11212. * @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.
  11213. * @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.
  11214. * @return {BABYLON.Node[]} all children nodes of all types.
  11215. */
  11216. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  11217. var results = [];
  11218. this._getDescendants(results, directDescendantsOnly, predicate);
  11219. return results;
  11220. };
  11221. /**
  11222. * Get all child-meshes of this node.
  11223. */
  11224. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  11225. var results = [];
  11226. this._getDescendants(results, directDecendantsOnly, function (node) {
  11227. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  11228. });
  11229. return results;
  11230. };
  11231. /**
  11232. * Get all direct children of this node.
  11233. */
  11234. Node.prototype.getChildren = function (predicate) {
  11235. return this.getDescendants(true, predicate);
  11236. };
  11237. Node.prototype._setReady = function (state) {
  11238. if (state === this._isReady) {
  11239. return;
  11240. }
  11241. if (!state) {
  11242. this._isReady = false;
  11243. return;
  11244. }
  11245. this._isReady = true;
  11246. if (this.onReady) {
  11247. this.onReady(this);
  11248. }
  11249. };
  11250. Node.prototype.getAnimationByName = function (name) {
  11251. for (var i = 0; i < this.animations.length; i++) {
  11252. var animation = this.animations[i];
  11253. if (animation.name === name) {
  11254. return animation;
  11255. }
  11256. }
  11257. return null;
  11258. };
  11259. Node.prototype.createAnimationRange = function (name, from, to) {
  11260. // check name not already in use
  11261. if (!this._ranges[name]) {
  11262. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  11263. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11264. if (this.animations[i]) {
  11265. this.animations[i].createRange(name, from, to);
  11266. }
  11267. }
  11268. }
  11269. };
  11270. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  11271. if (deleteFrames === void 0) { deleteFrames = true; }
  11272. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11273. if (this.animations[i]) {
  11274. this.animations[i].deleteRange(name, deleteFrames);
  11275. }
  11276. }
  11277. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  11278. };
  11279. Node.prototype.getAnimationRange = function (name) {
  11280. return this._ranges[name];
  11281. };
  11282. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  11283. var range = this.getAnimationRange(name);
  11284. if (!range) {
  11285. return null;
  11286. }
  11287. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  11288. };
  11289. Node.prototype.serializeAnimationRanges = function () {
  11290. var serializationRanges = [];
  11291. for (var name in this._ranges) {
  11292. var range = {};
  11293. range.name = name;
  11294. range.from = this._ranges[name].from;
  11295. range.to = this._ranges[name].to;
  11296. serializationRanges.push(range);
  11297. }
  11298. return serializationRanges;
  11299. };
  11300. Node.prototype.dispose = function () {
  11301. this.parent = null;
  11302. // Callback
  11303. this.onDisposeObservable.notifyObservers(this);
  11304. this.onDisposeObservable.clear();
  11305. };
  11306. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  11307. if (parsedNode.ranges) {
  11308. for (var index = 0; index < parsedNode.ranges.length; index++) {
  11309. var data = parsedNode.ranges[index];
  11310. node.createAnimationRange(data.name, data.from, data.to);
  11311. }
  11312. }
  11313. };
  11314. return Node;
  11315. }());
  11316. __decorate([
  11317. BABYLON.serialize()
  11318. ], Node.prototype, "name", void 0);
  11319. __decorate([
  11320. BABYLON.serialize()
  11321. ], Node.prototype, "id", void 0);
  11322. __decorate([
  11323. BABYLON.serialize()
  11324. ], Node.prototype, "uniqueId", void 0);
  11325. __decorate([
  11326. BABYLON.serialize()
  11327. ], Node.prototype, "state", void 0);
  11328. __decorate([
  11329. BABYLON.serialize()
  11330. ], Node.prototype, "metadata", void 0);
  11331. BABYLON.Node = Node;
  11332. })(BABYLON || (BABYLON = {}));
  11333. //# sourceMappingURL=babylon.node.js.map
  11334. var BABYLON;
  11335. (function (BABYLON) {
  11336. var BoundingSphere = (function () {
  11337. function BoundingSphere(minimum, maximum) {
  11338. this.minimum = minimum;
  11339. this.maximum = maximum;
  11340. this._tempRadiusVector = BABYLON.Vector3.Zero();
  11341. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  11342. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  11343. this.radius = distance * 0.5;
  11344. this.centerWorld = BABYLON.Vector3.Zero();
  11345. this._update(BABYLON.Matrix.Identity());
  11346. }
  11347. // Methods
  11348. BoundingSphere.prototype._update = function (world) {
  11349. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  11350. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  11351. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  11352. };
  11353. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  11354. for (var i = 0; i < 6; i++) {
  11355. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  11356. return false;
  11357. }
  11358. return true;
  11359. };
  11360. BoundingSphere.prototype.intersectsPoint = function (point) {
  11361. var x = this.centerWorld.x - point.x;
  11362. var y = this.centerWorld.y - point.y;
  11363. var z = this.centerWorld.z - point.z;
  11364. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11365. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  11366. return false;
  11367. return true;
  11368. };
  11369. // Statics
  11370. BoundingSphere.Intersects = function (sphere0, sphere1) {
  11371. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  11372. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  11373. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  11374. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11375. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  11376. return false;
  11377. return true;
  11378. };
  11379. return BoundingSphere;
  11380. }());
  11381. BABYLON.BoundingSphere = BoundingSphere;
  11382. })(BABYLON || (BABYLON = {}));
  11383. //# sourceMappingURL=babylon.boundingSphere.js.map
  11384. var BABYLON;
  11385. (function (BABYLON) {
  11386. var BoundingBox = (function () {
  11387. function BoundingBox(minimum, maximum) {
  11388. this.minimum = minimum;
  11389. this.maximum = maximum;
  11390. this.vectors = new Array();
  11391. this.vectorsWorld = new Array();
  11392. // Bounding vectors
  11393. this.vectors.push(this.minimum.clone());
  11394. this.vectors.push(this.maximum.clone());
  11395. this.vectors.push(this.minimum.clone());
  11396. this.vectors[2].x = this.maximum.x;
  11397. this.vectors.push(this.minimum.clone());
  11398. this.vectors[3].y = this.maximum.y;
  11399. this.vectors.push(this.minimum.clone());
  11400. this.vectors[4].z = this.maximum.z;
  11401. this.vectors.push(this.maximum.clone());
  11402. this.vectors[5].z = this.minimum.z;
  11403. this.vectors.push(this.maximum.clone());
  11404. this.vectors[6].x = this.minimum.x;
  11405. this.vectors.push(this.maximum.clone());
  11406. this.vectors[7].y = this.minimum.y;
  11407. // OBB
  11408. this.center = this.maximum.add(this.minimum).scale(0.5);
  11409. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  11410. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  11411. // World
  11412. for (var index = 0; index < this.vectors.length; index++) {
  11413. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  11414. }
  11415. this.minimumWorld = BABYLON.Vector3.Zero();
  11416. this.maximumWorld = BABYLON.Vector3.Zero();
  11417. this.centerWorld = BABYLON.Vector3.Zero();
  11418. this.extendSizeWorld = BABYLON.Vector3.Zero();
  11419. this._update(BABYLON.Matrix.Identity());
  11420. }
  11421. // Methods
  11422. BoundingBox.prototype.getWorldMatrix = function () {
  11423. return this._worldMatrix;
  11424. };
  11425. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  11426. this._worldMatrix.copyFrom(matrix);
  11427. return this;
  11428. };
  11429. BoundingBox.prototype._update = function (world) {
  11430. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  11431. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  11432. for (var index = 0; index < this.vectors.length; index++) {
  11433. var v = this.vectorsWorld[index];
  11434. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  11435. if (v.x < this.minimumWorld.x)
  11436. this.minimumWorld.x = v.x;
  11437. if (v.y < this.minimumWorld.y)
  11438. this.minimumWorld.y = v.y;
  11439. if (v.z < this.minimumWorld.z)
  11440. this.minimumWorld.z = v.z;
  11441. if (v.x > this.maximumWorld.x)
  11442. this.maximumWorld.x = v.x;
  11443. if (v.y > this.maximumWorld.y)
  11444. this.maximumWorld.y = v.y;
  11445. if (v.z > this.maximumWorld.z)
  11446. this.maximumWorld.z = v.z;
  11447. }
  11448. // Extend
  11449. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  11450. this.extendSizeWorld.scaleInPlace(0.5);
  11451. // OBB
  11452. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  11453. this.centerWorld.scaleInPlace(0.5);
  11454. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  11455. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  11456. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  11457. this._worldMatrix = world;
  11458. };
  11459. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  11460. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  11461. };
  11462. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11463. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  11464. };
  11465. BoundingBox.prototype.intersectsPoint = function (point) {
  11466. var delta = -BABYLON.Epsilon;
  11467. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  11468. return false;
  11469. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  11470. return false;
  11471. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  11472. return false;
  11473. return true;
  11474. };
  11475. BoundingBox.prototype.intersectsSphere = function (sphere) {
  11476. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  11477. };
  11478. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  11479. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  11480. return false;
  11481. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  11482. return false;
  11483. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  11484. return false;
  11485. return true;
  11486. };
  11487. // Statics
  11488. BoundingBox.Intersects = function (box0, box1) {
  11489. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  11490. return false;
  11491. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  11492. return false;
  11493. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  11494. return false;
  11495. return true;
  11496. };
  11497. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  11498. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  11499. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  11500. return (num <= (sphereRadius * sphereRadius));
  11501. };
  11502. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  11503. for (var p = 0; p < 6; p++) {
  11504. for (var i = 0; i < 8; i++) {
  11505. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11506. return false;
  11507. }
  11508. }
  11509. }
  11510. return true;
  11511. };
  11512. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  11513. for (var p = 0; p < 6; p++) {
  11514. var inCount = 8;
  11515. for (var i = 0; i < 8; i++) {
  11516. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11517. --inCount;
  11518. }
  11519. else {
  11520. break;
  11521. }
  11522. }
  11523. if (inCount === 0)
  11524. return false;
  11525. }
  11526. return true;
  11527. };
  11528. return BoundingBox;
  11529. }());
  11530. BABYLON.BoundingBox = BoundingBox;
  11531. })(BABYLON || (BABYLON = {}));
  11532. //# sourceMappingURL=babylon.boundingBox.js.map
  11533. var BABYLON;
  11534. (function (BABYLON) {
  11535. var computeBoxExtents = function (axis, box) {
  11536. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  11537. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11538. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  11539. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11540. var r = r0 + r1 + r2;
  11541. return {
  11542. min: p - r,
  11543. max: p + r
  11544. };
  11545. };
  11546. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11547. var axisOverlap = function (axis, box0, box1) {
  11548. var result0 = computeBoxExtents(axis, box0);
  11549. var result1 = computeBoxExtents(axis, box1);
  11550. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11551. };
  11552. var BoundingInfo = (function () {
  11553. function BoundingInfo(minimum, maximum) {
  11554. this.minimum = minimum;
  11555. this.maximum = maximum;
  11556. this._isLocked = false;
  11557. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  11558. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  11559. }
  11560. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  11561. get: function () {
  11562. return this._isLocked;
  11563. },
  11564. set: function (value) {
  11565. this._isLocked = value;
  11566. },
  11567. enumerable: true,
  11568. configurable: true
  11569. });
  11570. // Methods
  11571. BoundingInfo.prototype.update = function (world) {
  11572. if (this._isLocked) {
  11573. return;
  11574. }
  11575. this.boundingBox._update(world);
  11576. this.boundingSphere._update(world);
  11577. };
  11578. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  11579. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  11580. return false;
  11581. return this.boundingBox.isInFrustum(frustumPlanes);
  11582. };
  11583. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11584. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  11585. };
  11586. BoundingInfo.prototype._checkCollision = function (collider) {
  11587. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  11588. };
  11589. BoundingInfo.prototype.intersectsPoint = function (point) {
  11590. if (!this.boundingSphere.centerWorld) {
  11591. return false;
  11592. }
  11593. if (!this.boundingSphere.intersectsPoint(point)) {
  11594. return false;
  11595. }
  11596. if (!this.boundingBox.intersectsPoint(point)) {
  11597. return false;
  11598. }
  11599. return true;
  11600. };
  11601. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  11602. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  11603. return false;
  11604. }
  11605. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  11606. return false;
  11607. }
  11608. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  11609. return false;
  11610. }
  11611. if (!precise) {
  11612. return true;
  11613. }
  11614. var box0 = this.boundingBox;
  11615. var box1 = boundingInfo.boundingBox;
  11616. if (!axisOverlap(box0.directions[0], box0, box1))
  11617. return false;
  11618. if (!axisOverlap(box0.directions[1], box0, box1))
  11619. return false;
  11620. if (!axisOverlap(box0.directions[2], box0, box1))
  11621. return false;
  11622. if (!axisOverlap(box1.directions[0], box0, box1))
  11623. return false;
  11624. if (!axisOverlap(box1.directions[1], box0, box1))
  11625. return false;
  11626. if (!axisOverlap(box1.directions[2], box0, box1))
  11627. return false;
  11628. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  11629. return false;
  11630. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  11631. return false;
  11632. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  11633. return false;
  11634. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  11635. return false;
  11636. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  11637. return false;
  11638. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  11639. return false;
  11640. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  11641. return false;
  11642. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  11643. return false;
  11644. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  11645. return false;
  11646. return true;
  11647. };
  11648. return BoundingInfo;
  11649. }());
  11650. BABYLON.BoundingInfo = BoundingInfo;
  11651. })(BABYLON || (BABYLON = {}));
  11652. //# sourceMappingURL=babylon.boundingInfo.js.map
  11653. var BABYLON;
  11654. (function (BABYLON) {
  11655. var AbstractMesh = (function (_super) {
  11656. __extends(AbstractMesh, _super);
  11657. // Constructor
  11658. function AbstractMesh(name, scene) {
  11659. var _this = _super.call(this, name, scene) || this;
  11660. _this._facetNb = 0; // facet number
  11661. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  11662. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  11663. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  11664. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  11665. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  11666. _this._subDiv = {
  11667. max: 1,
  11668. X: 1,
  11669. Y: 1,
  11670. Z: 1
  11671. };
  11672. // Events
  11673. /**
  11674. * An event triggered when this mesh collides with another one
  11675. * @type {BABYLON.Observable}
  11676. */
  11677. _this.onCollideObservable = new BABYLON.Observable();
  11678. /**
  11679. * An event triggered when the collision's position changes
  11680. * @type {BABYLON.Observable}
  11681. */
  11682. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  11683. /**
  11684. * An event triggered after the world matrix is updated
  11685. * @type {BABYLON.Observable}
  11686. */
  11687. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  11688. /**
  11689. * An event triggered when material is changed
  11690. * @type {BABYLON.Observable}
  11691. */
  11692. _this.onMaterialChangedObservable = new BABYLON.Observable();
  11693. // Properties
  11694. _this.definedFacingForward = true; // orientation for POV movement & rotation
  11695. _this.position = BABYLON.Vector3.Zero();
  11696. _this._rotation = BABYLON.Vector3.Zero();
  11697. _this._scaling = BABYLON.Vector3.One();
  11698. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  11699. _this.visibility = 1.0;
  11700. _this.alphaIndex = Number.MAX_VALUE;
  11701. _this.infiniteDistance = false;
  11702. _this.isVisible = true;
  11703. _this.isPickable = true;
  11704. _this.showBoundingBox = false;
  11705. _this.showSubMeshesBoundingBox = false;
  11706. _this.isBlocker = false;
  11707. _this.enablePointerMoveEvents = false;
  11708. _this.renderingGroupId = 0;
  11709. _this._receiveShadows = false;
  11710. _this.renderOutline = false;
  11711. _this.outlineColor = BABYLON.Color3.Red();
  11712. _this.outlineWidth = 0.02;
  11713. _this.renderOverlay = false;
  11714. _this.overlayColor = BABYLON.Color3.Red();
  11715. _this.overlayAlpha = 0.5;
  11716. _this._hasVertexAlpha = false;
  11717. _this._useVertexColors = true;
  11718. _this._computeBonesUsingShaders = true;
  11719. _this._numBoneInfluencers = 4;
  11720. _this._applyFog = true;
  11721. _this.scalingDeterminant = 1;
  11722. _this.useOctreeForRenderingSelection = true;
  11723. _this.useOctreeForPicking = true;
  11724. _this.useOctreeForCollisions = true;
  11725. _this.layerMask = 0x0FFFFFFF;
  11726. /**
  11727. * True if the mesh must be rendered in any case.
  11728. */
  11729. _this.alwaysSelectAsActiveMesh = false;
  11730. // Collisions
  11731. _this._checkCollisions = false;
  11732. _this._collisionMask = -1;
  11733. _this._collisionGroup = -1;
  11734. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11735. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  11736. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11737. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11738. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11739. // Edges
  11740. _this.edgesWidth = 1;
  11741. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  11742. // Cache
  11743. _this._localWorld = BABYLON.Matrix.Zero();
  11744. _this._worldMatrix = BABYLON.Matrix.Zero();
  11745. _this._absolutePosition = BABYLON.Vector3.Zero();
  11746. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  11747. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  11748. _this._isDirty = false;
  11749. _this._pivotMatrix = BABYLON.Matrix.Identity();
  11750. _this._isDisposed = false;
  11751. _this._renderId = 0;
  11752. _this._intersectionsInProgress = new Array();
  11753. _this._isWorldMatrixFrozen = false;
  11754. _this._unIndexed = false;
  11755. _this._lightSources = new Array();
  11756. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11757. if (collidedMesh === void 0) { collidedMesh = null; }
  11758. //TODO move this to the collision coordinator!
  11759. if (_this.getScene().workerCollisions)
  11760. newPosition.multiplyInPlace(_this._collider.radius);
  11761. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  11762. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  11763. _this.position.addInPlace(_this._diffPositionForCollisions);
  11764. }
  11765. if (collidedMesh) {
  11766. _this.onCollideObservable.notifyObservers(collidedMesh);
  11767. }
  11768. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  11769. };
  11770. _this.getScene().addMesh(_this);
  11771. _this._resyncLightSources();
  11772. return _this;
  11773. }
  11774. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  11775. get: function () {
  11776. return AbstractMesh._BILLBOARDMODE_NONE;
  11777. },
  11778. enumerable: true,
  11779. configurable: true
  11780. });
  11781. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  11782. get: function () {
  11783. return AbstractMesh._BILLBOARDMODE_X;
  11784. },
  11785. enumerable: true,
  11786. configurable: true
  11787. });
  11788. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  11789. get: function () {
  11790. return AbstractMesh._BILLBOARDMODE_Y;
  11791. },
  11792. enumerable: true,
  11793. configurable: true
  11794. });
  11795. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  11796. get: function () {
  11797. return AbstractMesh._BILLBOARDMODE_Z;
  11798. },
  11799. enumerable: true,
  11800. configurable: true
  11801. });
  11802. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  11803. get: function () {
  11804. return AbstractMesh._BILLBOARDMODE_ALL;
  11805. },
  11806. enumerable: true,
  11807. configurable: true
  11808. });
  11809. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  11810. /**
  11811. * Read-only : the number of facets in the mesh
  11812. */
  11813. get: function () {
  11814. return this._facetNb;
  11815. },
  11816. enumerable: true,
  11817. configurable: true
  11818. });
  11819. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  11820. /**
  11821. * The number (integer) of subdivisions per axis in the partioning space
  11822. */
  11823. get: function () {
  11824. return this._partitioningSubdivisions;
  11825. },
  11826. set: function (nb) {
  11827. this._partitioningSubdivisions = nb;
  11828. },
  11829. enumerable: true,
  11830. configurable: true
  11831. });
  11832. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  11833. /**
  11834. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  11835. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  11836. */
  11837. get: function () {
  11838. return this._partitioningBBoxRatio;
  11839. },
  11840. set: function (ratio) {
  11841. this._partitioningBBoxRatio = ratio;
  11842. },
  11843. enumerable: true,
  11844. configurable: true
  11845. });
  11846. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  11847. /**
  11848. * Read-only boolean : is the feature facetData enabled ?
  11849. */
  11850. get: function () {
  11851. return this._facetDataEnabled;
  11852. },
  11853. enumerable: true,
  11854. configurable: true
  11855. });
  11856. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  11857. set: function (callback) {
  11858. if (this._onCollideObserver) {
  11859. this.onCollideObservable.remove(this._onCollideObserver);
  11860. }
  11861. this._onCollideObserver = this.onCollideObservable.add(callback);
  11862. },
  11863. enumerable: true,
  11864. configurable: true
  11865. });
  11866. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  11867. set: function (callback) {
  11868. if (this._onCollisionPositionChangeObserver) {
  11869. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  11870. }
  11871. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  11872. },
  11873. enumerable: true,
  11874. configurable: true
  11875. });
  11876. Object.defineProperty(AbstractMesh.prototype, "material", {
  11877. get: function () {
  11878. return this._material;
  11879. },
  11880. set: function (value) {
  11881. if (this._material === value) {
  11882. return;
  11883. }
  11884. this._material = value;
  11885. if (this.onMaterialChangedObservable.hasObservers) {
  11886. this.onMaterialChangedObservable.notifyObservers(this);
  11887. }
  11888. if (!this.subMeshes) {
  11889. return;
  11890. }
  11891. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11892. var subMesh = _a[_i];
  11893. subMesh.setEffect(null);
  11894. }
  11895. },
  11896. enumerable: true,
  11897. configurable: true
  11898. });
  11899. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  11900. get: function () {
  11901. return this._receiveShadows;
  11902. },
  11903. set: function (value) {
  11904. if (this._receiveShadows === value) {
  11905. return;
  11906. }
  11907. this._receiveShadows = value;
  11908. this._markSubMeshesAsLightDirty();
  11909. },
  11910. enumerable: true,
  11911. configurable: true
  11912. });
  11913. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  11914. get: function () {
  11915. return this._hasVertexAlpha;
  11916. },
  11917. set: function (value) {
  11918. if (this._hasVertexAlpha === value) {
  11919. return;
  11920. }
  11921. this._hasVertexAlpha = value;
  11922. this._markSubMeshesAsAttributesDirty();
  11923. },
  11924. enumerable: true,
  11925. configurable: true
  11926. });
  11927. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  11928. get: function () {
  11929. return this._useVertexColors;
  11930. },
  11931. set: function (value) {
  11932. if (this._useVertexColors === value) {
  11933. return;
  11934. }
  11935. this._useVertexColors = value;
  11936. this._markSubMeshesAsAttributesDirty();
  11937. },
  11938. enumerable: true,
  11939. configurable: true
  11940. });
  11941. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  11942. get: function () {
  11943. return this._computeBonesUsingShaders;
  11944. },
  11945. set: function (value) {
  11946. if (this._computeBonesUsingShaders === value) {
  11947. return;
  11948. }
  11949. this._computeBonesUsingShaders = value;
  11950. this._markSubMeshesAsAttributesDirty();
  11951. },
  11952. enumerable: true,
  11953. configurable: true
  11954. });
  11955. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  11956. get: function () {
  11957. return this._numBoneInfluencers;
  11958. },
  11959. set: function (value) {
  11960. if (this._numBoneInfluencers === value) {
  11961. return;
  11962. }
  11963. this._numBoneInfluencers = value;
  11964. this._markSubMeshesAsAttributesDirty();
  11965. },
  11966. enumerable: true,
  11967. configurable: true
  11968. });
  11969. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  11970. get: function () {
  11971. return this._applyFog;
  11972. },
  11973. set: function (value) {
  11974. if (this._applyFog === value) {
  11975. return;
  11976. }
  11977. this._applyFog = value;
  11978. this._markSubMeshesAsMiscDirty();
  11979. },
  11980. enumerable: true,
  11981. configurable: true
  11982. });
  11983. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  11984. get: function () {
  11985. return this._collisionMask;
  11986. },
  11987. set: function (mask) {
  11988. this._collisionMask = !isNaN(mask) ? mask : -1;
  11989. },
  11990. enumerable: true,
  11991. configurable: true
  11992. });
  11993. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  11994. get: function () {
  11995. return this._collisionGroup;
  11996. },
  11997. set: function (mask) {
  11998. this._collisionGroup = !isNaN(mask) ? mask : -1;
  11999. },
  12000. enumerable: true,
  12001. configurable: true
  12002. });
  12003. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  12004. get: function () {
  12005. return null;
  12006. },
  12007. enumerable: true,
  12008. configurable: true
  12009. });
  12010. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  12011. get: function () {
  12012. return this._skeleton;
  12013. },
  12014. set: function (value) {
  12015. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  12016. this._skeleton._unregisterMeshWithPoseMatrix(this);
  12017. }
  12018. if (value && value.needInitialSkinMatrix) {
  12019. value._registerMeshWithPoseMatrix(this);
  12020. }
  12021. this._skeleton = value;
  12022. if (!this._skeleton) {
  12023. this._bonesTransformMatrices = null;
  12024. }
  12025. this._markSubMeshesAsAttributesDirty();
  12026. },
  12027. enumerable: true,
  12028. configurable: true
  12029. });
  12030. /**
  12031. * Boolean : true if the mesh has been disposed.
  12032. */
  12033. AbstractMesh.prototype.isDisposed = function () {
  12034. return this._isDisposed;
  12035. };
  12036. /**
  12037. * Returns the string "AbstractMesh"
  12038. */
  12039. AbstractMesh.prototype.getClassName = function () {
  12040. return "AbstractMesh";
  12041. };
  12042. /**
  12043. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12044. */
  12045. AbstractMesh.prototype.toString = function (fullDetails) {
  12046. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  12047. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  12048. if (this._skeleton) {
  12049. ret += ", skeleton: " + this._skeleton.name;
  12050. }
  12051. if (fullDetails) {
  12052. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  12053. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  12054. }
  12055. return ret;
  12056. };
  12057. AbstractMesh.prototype._resyncLightSources = function () {
  12058. this._lightSources.length = 0;
  12059. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  12060. var light = _a[_i];
  12061. if (!light.isEnabled()) {
  12062. continue;
  12063. }
  12064. if (light.canAffectMesh(this)) {
  12065. this._lightSources.push(light);
  12066. }
  12067. }
  12068. this._markSubMeshesAsLightDirty();
  12069. };
  12070. AbstractMesh.prototype._resyncLighSource = function (light) {
  12071. var isIn = light.isEnabled() && light.canAffectMesh(this);
  12072. var index = this._lightSources.indexOf(light);
  12073. if (index === -1) {
  12074. if (!isIn) {
  12075. return;
  12076. }
  12077. this._lightSources.push(light);
  12078. }
  12079. else {
  12080. if (isIn) {
  12081. return;
  12082. }
  12083. this._lightSources.splice(index, 1);
  12084. }
  12085. this._markSubMeshesAsLightDirty();
  12086. };
  12087. AbstractMesh.prototype._removeLightSource = function (light) {
  12088. var index = this._lightSources.indexOf(light);
  12089. if (index === -1) {
  12090. return;
  12091. }
  12092. this._lightSources.splice(index, 1);
  12093. };
  12094. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  12095. if (!this.subMeshes) {
  12096. return;
  12097. }
  12098. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12099. var subMesh = _a[_i];
  12100. if (subMesh._materialDefines) {
  12101. func(subMesh._materialDefines);
  12102. }
  12103. }
  12104. };
  12105. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  12106. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  12107. };
  12108. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  12109. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  12110. };
  12111. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  12112. if (!this.subMeshes) {
  12113. return;
  12114. }
  12115. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12116. var subMesh = _a[_i];
  12117. var material = subMesh.getMaterial();
  12118. if (material) {
  12119. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  12120. }
  12121. }
  12122. };
  12123. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  12124. /**
  12125. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  12126. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  12127. * Default : (0.0, 0.0, 0.0)
  12128. */
  12129. get: function () {
  12130. return this._rotation;
  12131. },
  12132. set: function (newRotation) {
  12133. this._rotation = newRotation;
  12134. },
  12135. enumerable: true,
  12136. configurable: true
  12137. });
  12138. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  12139. /**
  12140. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  12141. * Default : (1.0, 1.0, 1.0)
  12142. */
  12143. get: function () {
  12144. return this._scaling;
  12145. },
  12146. set: function (newScaling) {
  12147. this._scaling = newScaling;
  12148. if (this.physicsImpostor) {
  12149. this.physicsImpostor.forceUpdate();
  12150. }
  12151. },
  12152. enumerable: true,
  12153. configurable: true
  12154. });
  12155. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  12156. /**
  12157. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  12158. * It's null by default.
  12159. * 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)
  12160. */
  12161. get: function () {
  12162. return this._rotationQuaternion;
  12163. },
  12164. set: function (quaternion) {
  12165. this._rotationQuaternion = quaternion;
  12166. //reset the rotation vector.
  12167. if (quaternion && this.rotation.length()) {
  12168. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  12169. }
  12170. },
  12171. enumerable: true,
  12172. configurable: true
  12173. });
  12174. // Methods
  12175. /**
  12176. * Copies the paramater passed Matrix into the mesh Pose matrix.
  12177. * Returns the AbstractMesh.
  12178. */
  12179. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  12180. this._poseMatrix.copyFrom(matrix);
  12181. return this;
  12182. };
  12183. /**
  12184. * Returns the mesh Pose matrix.
  12185. * Returned object : Matrix
  12186. */
  12187. AbstractMesh.prototype.getPoseMatrix = function () {
  12188. return this._poseMatrix;
  12189. };
  12190. /**
  12191. * Disables the mesh edger rendering mode.
  12192. * Returns the AbstractMesh.
  12193. */
  12194. AbstractMesh.prototype.disableEdgesRendering = function () {
  12195. if (this._edgesRenderer !== undefined) {
  12196. this._edgesRenderer.dispose();
  12197. this._edgesRenderer = undefined;
  12198. }
  12199. return this;
  12200. };
  12201. /**
  12202. * Enables the edge rendering mode on the mesh.
  12203. * This mode makes the mesh edges visible.
  12204. * Returns the AbstractMesh.
  12205. */
  12206. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  12207. if (epsilon === void 0) { epsilon = 0.95; }
  12208. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  12209. this.disableEdgesRendering();
  12210. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  12211. return this;
  12212. };
  12213. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  12214. /**
  12215. * Returns true if the mesh is blocked. Used by the class Mesh.
  12216. * Returns the boolean `false` by default.
  12217. */
  12218. get: function () {
  12219. return false;
  12220. },
  12221. enumerable: true,
  12222. configurable: true
  12223. });
  12224. /**
  12225. * Returns the mesh itself by default, used by the class Mesh.
  12226. * Returned type : AbstractMesh
  12227. */
  12228. AbstractMesh.prototype.getLOD = function (camera) {
  12229. return this;
  12230. };
  12231. /**
  12232. * Returns 0 by default, used by the class Mesh.
  12233. * Returns an integer.
  12234. */
  12235. AbstractMesh.prototype.getTotalVertices = function () {
  12236. return 0;
  12237. };
  12238. /**
  12239. * Returns null by default, used by the class Mesh.
  12240. * Returned type : integer array
  12241. */
  12242. AbstractMesh.prototype.getIndices = function () {
  12243. return null;
  12244. };
  12245. /**
  12246. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  12247. * Returned type : float array or Float32Array
  12248. */
  12249. AbstractMesh.prototype.getVerticesData = function (kind) {
  12250. return null;
  12251. };
  12252. /**
  12253. * Sets the vertex data of the mesh geometry for the requested `kind`.
  12254. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  12255. * The `data` are either a numeric array either a Float32Array.
  12256. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  12257. * 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).
  12258. * Note that a new underlying VertexBuffer object is created each call.
  12259. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  12260. *
  12261. * Possible `kind` values :
  12262. * - BABYLON.VertexBuffer.PositionKind
  12263. * - BABYLON.VertexBuffer.UVKind
  12264. * - BABYLON.VertexBuffer.UV2Kind
  12265. * - BABYLON.VertexBuffer.UV3Kind
  12266. * - BABYLON.VertexBuffer.UV4Kind
  12267. * - BABYLON.VertexBuffer.UV5Kind
  12268. * - BABYLON.VertexBuffer.UV6Kind
  12269. * - BABYLON.VertexBuffer.ColorKind
  12270. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12271. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12272. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12273. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12274. *
  12275. * Returns the Mesh.
  12276. */
  12277. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  12278. return null;
  12279. };
  12280. /**
  12281. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  12282. * If the mesh has no geometry, it is simply returned as it is.
  12283. * The `data` are either a numeric array either a Float32Array.
  12284. * No new underlying VertexBuffer object is created.
  12285. * 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.
  12286. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  12287. *
  12288. * Possible `kind` values :
  12289. * - BABYLON.VertexBuffer.PositionKind
  12290. * - BABYLON.VertexBuffer.UVKind
  12291. * - BABYLON.VertexBuffer.UV2Kind
  12292. * - BABYLON.VertexBuffer.UV3Kind
  12293. * - BABYLON.VertexBuffer.UV4Kind
  12294. * - BABYLON.VertexBuffer.UV5Kind
  12295. * - BABYLON.VertexBuffer.UV6Kind
  12296. * - BABYLON.VertexBuffer.ColorKind
  12297. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12298. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12299. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12300. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12301. *
  12302. * Returns the Mesh.
  12303. */
  12304. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  12305. return null;
  12306. };
  12307. /**
  12308. * Sets the mesh indices.
  12309. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  12310. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  12311. * This method creates a new index buffer each call.
  12312. * Returns the Mesh.
  12313. */
  12314. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  12315. return null;
  12316. };
  12317. /** Returns false by default, used by the class Mesh.
  12318. * Returns a boolean
  12319. */
  12320. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  12321. return false;
  12322. };
  12323. /**
  12324. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  12325. * Returns a BoundingInfo
  12326. */
  12327. AbstractMesh.prototype.getBoundingInfo = function () {
  12328. if (this._masterMesh) {
  12329. return this._masterMesh.getBoundingInfo();
  12330. }
  12331. if (!this._boundingInfo) {
  12332. this._updateBoundingInfo();
  12333. }
  12334. return this._boundingInfo;
  12335. };
  12336. /**
  12337. * Sets a mesh new object BoundingInfo.
  12338. * Returns the AbstractMesh.
  12339. */
  12340. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  12341. this._boundingInfo = boundingInfo;
  12342. return this;
  12343. };
  12344. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  12345. get: function () {
  12346. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  12347. },
  12348. enumerable: true,
  12349. configurable: true
  12350. });
  12351. AbstractMesh.prototype._preActivate = function () {
  12352. };
  12353. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  12354. };
  12355. AbstractMesh.prototype._activate = function (renderId) {
  12356. this._renderId = renderId;
  12357. };
  12358. /**
  12359. * Returns the last update of the World matrix
  12360. * Returns a Matrix.
  12361. */
  12362. AbstractMesh.prototype.getWorldMatrix = function () {
  12363. if (this._masterMesh) {
  12364. return this._masterMesh.getWorldMatrix();
  12365. }
  12366. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  12367. this.computeWorldMatrix();
  12368. }
  12369. return this._worldMatrix;
  12370. };
  12371. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  12372. /**
  12373. * Returns directly the last state of the mesh World matrix.
  12374. * A Matrix is returned.
  12375. */
  12376. get: function () {
  12377. return this._worldMatrix;
  12378. },
  12379. enumerable: true,
  12380. configurable: true
  12381. });
  12382. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  12383. /**
  12384. * Returns the current mesh absolute position.
  12385. * Retuns a Vector3.
  12386. */
  12387. get: function () {
  12388. return this._absolutePosition;
  12389. },
  12390. enumerable: true,
  12391. configurable: true
  12392. });
  12393. /**
  12394. * Prevents the World matrix to be computed any longer.
  12395. * Returns the AbstractMesh.
  12396. */
  12397. AbstractMesh.prototype.freezeWorldMatrix = function () {
  12398. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  12399. this.computeWorldMatrix(true);
  12400. this._isWorldMatrixFrozen = true;
  12401. return this;
  12402. };
  12403. /**
  12404. * Allows back the World matrix computation.
  12405. * Returns the AbstractMesh.
  12406. */
  12407. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  12408. this._isWorldMatrixFrozen = false;
  12409. this.computeWorldMatrix(true);
  12410. return this;
  12411. };
  12412. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  12413. /**
  12414. * True if the World matrix has been frozen.
  12415. * Returns a boolean.
  12416. */
  12417. get: function () {
  12418. return this._isWorldMatrixFrozen;
  12419. },
  12420. enumerable: true,
  12421. configurable: true
  12422. });
  12423. /**
  12424. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  12425. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12426. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12427. * The passed axis is also normalized.
  12428. * Returns the AbstractMesh.
  12429. */
  12430. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  12431. axis.normalize();
  12432. if (!this.rotationQuaternion) {
  12433. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12434. this.rotation = BABYLON.Vector3.Zero();
  12435. }
  12436. var rotationQuaternion;
  12437. if (!space || space === BABYLON.Space.LOCAL) {
  12438. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12439. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  12440. }
  12441. else {
  12442. if (this.parent) {
  12443. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12444. invertParentWorldMatrix.invert();
  12445. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  12446. }
  12447. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12448. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  12449. }
  12450. return this;
  12451. };
  12452. /**
  12453. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  12454. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12455. * The passed axis is also normalized.
  12456. * Returns the AbstractMesh.
  12457. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  12458. */
  12459. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  12460. axis.normalize();
  12461. if (!this.rotationQuaternion) {
  12462. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12463. this.rotation.copyFromFloats(0, 0, 0);
  12464. }
  12465. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  12466. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  12467. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  12468. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  12469. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  12470. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  12471. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  12472. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  12473. this.rotationQuaternion.multiplyInPlace(BABYLON.Tmp.Quaternion[0]);
  12474. return this;
  12475. };
  12476. /**
  12477. * Translates the mesh along the axis vector for the passed distance in the given space.
  12478. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12479. * Returns the AbstractMesh.
  12480. */
  12481. AbstractMesh.prototype.translate = function (axis, distance, space) {
  12482. var displacementVector = axis.scale(distance);
  12483. if (!space || space === BABYLON.Space.LOCAL) {
  12484. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  12485. this.setPositionWithLocalVector(tempV3);
  12486. }
  12487. else {
  12488. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  12489. }
  12490. return this;
  12491. };
  12492. /**
  12493. * Adds a rotation step to the mesh current rotation.
  12494. * x, y, z are Euler angles expressed in radians.
  12495. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  12496. * This means this rotation is made in the mesh local space only.
  12497. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  12498. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  12499. * ```javascript
  12500. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  12501. * ```
  12502. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  12503. * 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.
  12504. * Returns the AbstractMesh.
  12505. */
  12506. AbstractMesh.prototype.addRotation = function (x, y, z) {
  12507. var rotationQuaternion;
  12508. if (this.rotationQuaternion) {
  12509. rotationQuaternion = this.rotationQuaternion;
  12510. }
  12511. else {
  12512. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  12513. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  12514. }
  12515. var accumulation = BABYLON.Tmp.Quaternion[0];
  12516. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  12517. rotationQuaternion.multiplyInPlace(accumulation);
  12518. if (!this.rotationQuaternion) {
  12519. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  12520. }
  12521. return this;
  12522. };
  12523. /**
  12524. * Retuns the mesh absolute position in the World.
  12525. * Returns a Vector3.
  12526. */
  12527. AbstractMesh.prototype.getAbsolutePosition = function () {
  12528. this.computeWorldMatrix();
  12529. return this._absolutePosition;
  12530. };
  12531. /**
  12532. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  12533. * Returns the AbstractMesh.
  12534. */
  12535. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  12536. if (!absolutePosition) {
  12537. return;
  12538. }
  12539. var absolutePositionX;
  12540. var absolutePositionY;
  12541. var absolutePositionZ;
  12542. if (absolutePosition.x === undefined) {
  12543. if (arguments.length < 3) {
  12544. return;
  12545. }
  12546. absolutePositionX = arguments[0];
  12547. absolutePositionY = arguments[1];
  12548. absolutePositionZ = arguments[2];
  12549. }
  12550. else {
  12551. absolutePositionX = absolutePosition.x;
  12552. absolutePositionY = absolutePosition.y;
  12553. absolutePositionZ = absolutePosition.z;
  12554. }
  12555. if (this.parent) {
  12556. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12557. invertParentWorldMatrix.invert();
  12558. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  12559. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  12560. }
  12561. else {
  12562. this.position.x = absolutePositionX;
  12563. this.position.y = absolutePositionY;
  12564. this.position.z = absolutePositionZ;
  12565. }
  12566. return this;
  12567. };
  12568. // ================================== Point of View Movement =================================
  12569. /**
  12570. * Perform relative position change from the point of view of behind the front of the mesh.
  12571. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12572. * Supports definition of mesh facing forward or backward.
  12573. * @param {number} amountRight
  12574. * @param {number} amountUp
  12575. * @param {number} amountForward
  12576. *
  12577. * Returns the AbstractMesh.
  12578. */
  12579. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  12580. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  12581. return this;
  12582. };
  12583. /**
  12584. * Calculate relative position change from the point of view of behind the front of the mesh.
  12585. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12586. * Supports definition of mesh facing forward or backward.
  12587. * @param {number} amountRight
  12588. * @param {number} amountUp
  12589. * @param {number} amountForward
  12590. *
  12591. * Returns a new Vector3.
  12592. */
  12593. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  12594. var rotMatrix = new BABYLON.Matrix();
  12595. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12596. rotQuaternion.toRotationMatrix(rotMatrix);
  12597. var translationDelta = BABYLON.Vector3.Zero();
  12598. var defForwardMult = this.definedFacingForward ? -1 : 1;
  12599. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  12600. return translationDelta;
  12601. };
  12602. // ================================== Point of View Rotation =================================
  12603. /**
  12604. * Perform relative rotation change from the point of view of behind the front of the mesh.
  12605. * Supports definition of mesh facing forward or backward.
  12606. * @param {number} flipBack
  12607. * @param {number} twirlClockwise
  12608. * @param {number} tiltRight
  12609. *
  12610. * Returns the AbstractMesh.
  12611. */
  12612. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12613. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  12614. return this;
  12615. };
  12616. /**
  12617. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  12618. * Supports definition of mesh facing forward or backward.
  12619. * @param {number} flipBack
  12620. * @param {number} twirlClockwise
  12621. * @param {number} tiltRight
  12622. *
  12623. * Returns a new Vector3.
  12624. */
  12625. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12626. var defForwardMult = this.definedFacingForward ? 1 : -1;
  12627. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  12628. };
  12629. /**
  12630. * Sets a new pivot matrix to the mesh.
  12631. * Returns the AbstractMesh.
  12632. */
  12633. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  12634. this._pivotMatrix = matrix;
  12635. this._cache.pivotMatrixUpdated = true;
  12636. return this;
  12637. };
  12638. /**
  12639. * Returns the mesh pivot matrix.
  12640. * Default : Identity.
  12641. * A Matrix is returned.
  12642. */
  12643. AbstractMesh.prototype.getPivotMatrix = function () {
  12644. return this._pivotMatrix;
  12645. };
  12646. AbstractMesh.prototype._isSynchronized = function () {
  12647. if (this._isDirty) {
  12648. return false;
  12649. }
  12650. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  12651. return false;
  12652. if (this._cache.pivotMatrixUpdated) {
  12653. return false;
  12654. }
  12655. if (this.infiniteDistance) {
  12656. return false;
  12657. }
  12658. if (!this._cache.position.equals(this.position))
  12659. return false;
  12660. if (this.rotationQuaternion) {
  12661. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  12662. return false;
  12663. }
  12664. if (!this._cache.rotation.equals(this.rotation))
  12665. return false;
  12666. if (!this._cache.scaling.equals(this.scaling))
  12667. return false;
  12668. return true;
  12669. };
  12670. AbstractMesh.prototype._initCache = function () {
  12671. _super.prototype._initCache.call(this);
  12672. this._cache.localMatrixUpdated = false;
  12673. this._cache.position = BABYLON.Vector3.Zero();
  12674. this._cache.scaling = BABYLON.Vector3.Zero();
  12675. this._cache.rotation = BABYLON.Vector3.Zero();
  12676. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  12677. this._cache.billboardMode = -1;
  12678. };
  12679. AbstractMesh.prototype.markAsDirty = function (property) {
  12680. if (property === "rotation") {
  12681. this.rotationQuaternion = null;
  12682. }
  12683. this._currentRenderId = Number.MAX_VALUE;
  12684. this._isDirty = true;
  12685. return this;
  12686. };
  12687. /**
  12688. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  12689. * Returns the AbstractMesh.
  12690. */
  12691. AbstractMesh.prototype._updateBoundingInfo = function () {
  12692. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  12693. this._boundingInfo.update(this.worldMatrixFromCache);
  12694. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  12695. return this;
  12696. };
  12697. /**
  12698. * Update a mesh's children BoundingInfo objects only.
  12699. * Returns the AbstractMesh.
  12700. */
  12701. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  12702. if (!this.subMeshes) {
  12703. return;
  12704. }
  12705. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  12706. var subMesh = this.subMeshes[subIndex];
  12707. if (!subMesh.IsGlobal) {
  12708. subMesh.updateBoundingInfo(matrix);
  12709. }
  12710. }
  12711. return this;
  12712. };
  12713. /**
  12714. * Computes the mesh World matrix and returns it.
  12715. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  12716. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  12717. * If the parameter `force`is set to `true`, the actual computation is done.
  12718. * Returns the mesh World Matrix.
  12719. */
  12720. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  12721. if (this._isWorldMatrixFrozen) {
  12722. return this._worldMatrix;
  12723. }
  12724. if (!force && this.isSynchronized(true)) {
  12725. this._currentRenderId = this.getScene().getRenderId();
  12726. return this._worldMatrix;
  12727. }
  12728. this._cache.position.copyFrom(this.position);
  12729. this._cache.scaling.copyFrom(this.scaling);
  12730. this._cache.pivotMatrixUpdated = false;
  12731. this._cache.billboardMode = this.billboardMode;
  12732. this._currentRenderId = this.getScene().getRenderId();
  12733. this._isDirty = false;
  12734. // Scaling
  12735. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  12736. // Rotation
  12737. //rotate, if quaternion is set and rotation was used
  12738. if (this.rotationQuaternion) {
  12739. var len = this.rotation.length();
  12740. if (len) {
  12741. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  12742. this.rotation.copyFromFloats(0, 0, 0);
  12743. }
  12744. }
  12745. if (this.rotationQuaternion) {
  12746. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  12747. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  12748. }
  12749. else {
  12750. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  12751. this._cache.rotation.copyFrom(this.rotation);
  12752. }
  12753. // Translation
  12754. if (this.infiniteDistance && !this.parent) {
  12755. var camera = this.getScene().activeCamera;
  12756. if (camera) {
  12757. var cameraWorldMatrix = camera.getWorldMatrix();
  12758. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  12759. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  12760. }
  12761. }
  12762. else {
  12763. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  12764. }
  12765. // Composing transformations
  12766. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  12767. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12768. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  12769. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  12770. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  12771. // Need to decompose each rotation here
  12772. var currentPosition = BABYLON.Tmp.Vector3[3];
  12773. if (this.parent && this.parent.getWorldMatrix) {
  12774. if (this._meshToBoneReferal) {
  12775. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12776. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  12777. }
  12778. else {
  12779. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  12780. }
  12781. }
  12782. else {
  12783. currentPosition.copyFrom(this.position);
  12784. }
  12785. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  12786. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  12787. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  12788. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  12789. }
  12790. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  12791. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  12792. }
  12793. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  12794. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  12795. }
  12796. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  12797. }
  12798. else {
  12799. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  12800. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  12801. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  12802. }
  12803. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  12804. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12805. }
  12806. // Local world
  12807. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  12808. // Parent
  12809. if (this.parent && this.parent.getWorldMatrix) {
  12810. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  12811. if (this._meshToBoneReferal) {
  12812. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12813. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  12814. }
  12815. else {
  12816. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  12817. }
  12818. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  12819. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  12820. this._worldMatrix.copyFrom(this._localWorld);
  12821. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  12822. }
  12823. else {
  12824. if (this._meshToBoneReferal) {
  12825. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12826. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  12827. }
  12828. else {
  12829. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  12830. }
  12831. }
  12832. this._markSyncedWithParent();
  12833. }
  12834. else {
  12835. this._worldMatrix.copyFrom(this._localWorld);
  12836. }
  12837. // Bounding info
  12838. this._updateBoundingInfo();
  12839. // Absolute position
  12840. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  12841. // Callbacks
  12842. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  12843. if (!this._poseMatrix) {
  12844. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  12845. }
  12846. return this._worldMatrix;
  12847. };
  12848. /**
  12849. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  12850. * @param func: callback function to add
  12851. *
  12852. * Returns the AbstractMesh.
  12853. */
  12854. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  12855. this.onAfterWorldMatrixUpdateObservable.add(func);
  12856. return this;
  12857. };
  12858. /**
  12859. * Removes a registered callback function.
  12860. * Returns the AbstractMesh.
  12861. */
  12862. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  12863. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  12864. return this;
  12865. };
  12866. /**
  12867. * Sets the mesh position in its local space.
  12868. * Returns the AbstractMesh.
  12869. */
  12870. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  12871. this.computeWorldMatrix();
  12872. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  12873. return this;
  12874. };
  12875. /**
  12876. * Returns the mesh position in the local space from the current World matrix values.
  12877. * Returns a new Vector3.
  12878. */
  12879. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  12880. this.computeWorldMatrix();
  12881. var invLocalWorldMatrix = this._localWorld.clone();
  12882. invLocalWorldMatrix.invert();
  12883. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  12884. };
  12885. /**
  12886. * Translates the mesh along the passed Vector3 in its local space.
  12887. * Returns the AbstractMesh.
  12888. */
  12889. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  12890. this.computeWorldMatrix(true);
  12891. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  12892. return this;
  12893. };
  12894. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  12895. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  12896. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  12897. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  12898. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  12899. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  12900. /// <returns>Mesh oriented towards targetMesh</returns>
  12901. if (yawCor === void 0) { yawCor = 0; }
  12902. if (pitchCor === void 0) { pitchCor = 0; }
  12903. if (rollCor === void 0) { rollCor = 0; }
  12904. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12905. var dv = AbstractMesh._lookAtVectorCache;
  12906. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  12907. targetPoint.subtractToRef(pos, dv);
  12908. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  12909. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  12910. var pitch = Math.atan2(dv.y, len);
  12911. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  12912. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  12913. return this;
  12914. };
  12915. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  12916. this._meshToBoneReferal = affectedMesh;
  12917. this.parent = bone;
  12918. if (bone.getWorldMatrix().determinant() < 0) {
  12919. this.scalingDeterminant *= -1;
  12920. }
  12921. return this;
  12922. };
  12923. AbstractMesh.prototype.detachFromBone = function () {
  12924. if (this.parent.getWorldMatrix().determinant() < 0) {
  12925. this.scalingDeterminant *= -1;
  12926. }
  12927. this._meshToBoneReferal = null;
  12928. this.parent = null;
  12929. return this;
  12930. };
  12931. /**
  12932. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  12933. * A mesh is in the frustum if its bounding box intersects the frustum.
  12934. * Boolean returned.
  12935. */
  12936. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  12937. return this._boundingInfo.isInFrustum(frustumPlanes);
  12938. };
  12939. /**
  12940. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  12941. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  12942. * Boolean returned.
  12943. */
  12944. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12945. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  12946. ;
  12947. };
  12948. /**
  12949. * True if the mesh intersects another mesh or a SolidParticle object.
  12950. * 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)
  12951. * Returns a boolean.
  12952. */
  12953. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  12954. if (!this._boundingInfo || !mesh._boundingInfo) {
  12955. return false;
  12956. }
  12957. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  12958. };
  12959. /**
  12960. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  12961. * Returns a boolean.
  12962. */
  12963. AbstractMesh.prototype.intersectsPoint = function (point) {
  12964. if (!this._boundingInfo) {
  12965. return false;
  12966. }
  12967. return this._boundingInfo.intersectsPoint(point);
  12968. };
  12969. AbstractMesh.prototype.getPhysicsImpostor = function () {
  12970. return this.physicsImpostor;
  12971. };
  12972. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  12973. if (!camera) {
  12974. camera = this.getScene().activeCamera;
  12975. }
  12976. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  12977. };
  12978. /**
  12979. * Returns the distance from the mesh to the active camera.
  12980. * Returns a float.
  12981. */
  12982. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  12983. if (!camera) {
  12984. camera = this.getScene().activeCamera;
  12985. }
  12986. return this.absolutePosition.subtract(camera.position).length();
  12987. };
  12988. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  12989. if (!this.physicsImpostor) {
  12990. return;
  12991. }
  12992. this.physicsImpostor.applyImpulse(force, contactPoint);
  12993. return this;
  12994. };
  12995. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  12996. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  12997. return;
  12998. }
  12999. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  13000. mainPivot: pivot1,
  13001. connectedPivot: pivot2,
  13002. nativeParams: options
  13003. });
  13004. return this;
  13005. };
  13006. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  13007. // Collisions
  13008. /**
  13009. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  13010. * Default `false`.
  13011. */
  13012. get: function () {
  13013. return this._checkCollisions;
  13014. },
  13015. set: function (collisionEnabled) {
  13016. this._checkCollisions = collisionEnabled;
  13017. if (this.getScene().workerCollisions) {
  13018. this.getScene().collisionCoordinator.onMeshUpdated(this);
  13019. }
  13020. },
  13021. enumerable: true,
  13022. configurable: true
  13023. });
  13024. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  13025. var globalPosition = this.getAbsolutePosition();
  13026. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  13027. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  13028. if (!this._collider) {
  13029. this._collider = new BABYLON.Collider();
  13030. }
  13031. this._collider.radius = this.ellipsoid;
  13032. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  13033. return this;
  13034. };
  13035. // Submeshes octree
  13036. /**
  13037. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  13038. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  13039. * Returns an Octree of submeshes.
  13040. */
  13041. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  13042. if (maxCapacity === void 0) { maxCapacity = 64; }
  13043. if (maxDepth === void 0) { maxDepth = 2; }
  13044. if (!this._submeshesOctree) {
  13045. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  13046. }
  13047. this.computeWorldMatrix(true);
  13048. // Update octree
  13049. var bbox = this.getBoundingInfo().boundingBox;
  13050. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  13051. return this._submeshesOctree;
  13052. };
  13053. // Collisions
  13054. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  13055. this._generatePointsArray();
  13056. // Transformation
  13057. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  13058. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  13059. subMesh._lastColliderWorldVertices = [];
  13060. subMesh._trianglePlanes = [];
  13061. var start = subMesh.verticesStart;
  13062. var end = (subMesh.verticesStart + subMesh.verticesCount);
  13063. for (var i = start; i < end; i++) {
  13064. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  13065. }
  13066. }
  13067. // Collide
  13068. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  13069. if (collider.collisionFound) {
  13070. collider.collidedMesh = this;
  13071. }
  13072. return this;
  13073. };
  13074. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  13075. var subMeshes;
  13076. var len;
  13077. // Octrees
  13078. if (this._submeshesOctree && this.useOctreeForCollisions) {
  13079. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  13080. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  13081. len = intersections.length;
  13082. subMeshes = intersections.data;
  13083. }
  13084. else {
  13085. subMeshes = this.subMeshes;
  13086. len = subMeshes.length;
  13087. }
  13088. for (var index = 0; index < len; index++) {
  13089. var subMesh = subMeshes[index];
  13090. // Bounding test
  13091. if (len > 1 && !subMesh._checkCollision(collider))
  13092. continue;
  13093. this._collideForSubMesh(subMesh, transformMatrix, collider);
  13094. }
  13095. return this;
  13096. };
  13097. AbstractMesh.prototype._checkCollision = function (collider) {
  13098. // Bounding box test
  13099. if (!this._boundingInfo._checkCollision(collider))
  13100. return this;
  13101. // Transformation matrix
  13102. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  13103. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  13104. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  13105. return this;
  13106. };
  13107. // Picking
  13108. AbstractMesh.prototype._generatePointsArray = function () {
  13109. return false;
  13110. };
  13111. /**
  13112. * Checks if the passed Ray intersects with the mesh.
  13113. * Returns an object PickingInfo.
  13114. */
  13115. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  13116. var pickingInfo = new BABYLON.PickingInfo();
  13117. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  13118. return pickingInfo;
  13119. }
  13120. if (!this._generatePointsArray()) {
  13121. return pickingInfo;
  13122. }
  13123. var intersectInfo = null;
  13124. // Octrees
  13125. var subMeshes;
  13126. var len;
  13127. if (this._submeshesOctree && this.useOctreeForPicking) {
  13128. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  13129. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  13130. len = intersections.length;
  13131. subMeshes = intersections.data;
  13132. }
  13133. else {
  13134. subMeshes = this.subMeshes;
  13135. len = subMeshes.length;
  13136. }
  13137. for (var index = 0; index < len; index++) {
  13138. var subMesh = subMeshes[index];
  13139. // Bounding test
  13140. if (len > 1 && !subMesh.canIntersects(ray))
  13141. continue;
  13142. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  13143. if (currentIntersectInfo) {
  13144. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  13145. intersectInfo = currentIntersectInfo;
  13146. intersectInfo.subMeshId = index;
  13147. if (fastCheck) {
  13148. break;
  13149. }
  13150. }
  13151. }
  13152. }
  13153. if (intersectInfo) {
  13154. // Get picked point
  13155. var world = this.getWorldMatrix();
  13156. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  13157. var direction = ray.direction.clone();
  13158. direction = direction.scale(intersectInfo.distance);
  13159. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  13160. var pickedPoint = worldOrigin.add(worldDirection);
  13161. // Return result
  13162. pickingInfo.hit = true;
  13163. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  13164. pickingInfo.pickedPoint = pickedPoint;
  13165. pickingInfo.pickedMesh = this;
  13166. pickingInfo.bu = intersectInfo.bu;
  13167. pickingInfo.bv = intersectInfo.bv;
  13168. pickingInfo.faceId = intersectInfo.faceId;
  13169. pickingInfo.subMeshId = intersectInfo.subMeshId;
  13170. return pickingInfo;
  13171. }
  13172. return pickingInfo;
  13173. };
  13174. /**
  13175. * Clones the mesh, used by the class Mesh.
  13176. * Just returns `null` for an AbstractMesh.
  13177. */
  13178. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13179. return null;
  13180. };
  13181. /**
  13182. * Disposes all the mesh submeshes.
  13183. * Returns the AbstractMesh.
  13184. */
  13185. AbstractMesh.prototype.releaseSubMeshes = function () {
  13186. if (this.subMeshes) {
  13187. while (this.subMeshes.length) {
  13188. this.subMeshes[0].dispose();
  13189. }
  13190. }
  13191. else {
  13192. this.subMeshes = new Array();
  13193. }
  13194. return this;
  13195. };
  13196. /**
  13197. * Disposes the AbstractMesh.
  13198. * Some internal references are kept for further use.
  13199. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  13200. * Returns nothing.
  13201. */
  13202. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  13203. var _this = this;
  13204. var index;
  13205. // Action manager
  13206. if (this.actionManager) {
  13207. this.actionManager.dispose();
  13208. this.actionManager = null;
  13209. }
  13210. // Skeleton
  13211. this.skeleton = null;
  13212. // Animations
  13213. this.getScene().stopAnimation(this);
  13214. // Physics
  13215. if (this.physicsImpostor) {
  13216. this.physicsImpostor.dispose();
  13217. }
  13218. // Intersections in progress
  13219. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  13220. var other = this._intersectionsInProgress[index];
  13221. var pos = other._intersectionsInProgress.indexOf(this);
  13222. other._intersectionsInProgress.splice(pos, 1);
  13223. }
  13224. this._intersectionsInProgress = [];
  13225. // Lights
  13226. var lights = this.getScene().lights;
  13227. lights.forEach(function (light) {
  13228. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  13229. if (meshIndex !== -1) {
  13230. light.includedOnlyMeshes.splice(meshIndex, 1);
  13231. }
  13232. meshIndex = light.excludedMeshes.indexOf(_this);
  13233. if (meshIndex !== -1) {
  13234. light.excludedMeshes.splice(meshIndex, 1);
  13235. }
  13236. // Shadow generators
  13237. var generator = light.getShadowGenerator();
  13238. if (generator) {
  13239. var shadowMap = generator.getShadowMap();
  13240. meshIndex = shadowMap.renderList.indexOf(_this);
  13241. if (meshIndex !== -1) {
  13242. shadowMap.renderList.splice(meshIndex, 1);
  13243. }
  13244. }
  13245. });
  13246. // Edges
  13247. if (this._edgesRenderer) {
  13248. this._edgesRenderer.dispose();
  13249. this._edgesRenderer = null;
  13250. }
  13251. // SubMeshes
  13252. if (this.getClassName() !== "InstancedMesh") {
  13253. this.releaseSubMeshes();
  13254. }
  13255. // Octree
  13256. var sceneOctree = this.getScene().selectionOctree;
  13257. if (sceneOctree) {
  13258. var index = sceneOctree.dynamicContent.indexOf(this);
  13259. if (index !== -1) {
  13260. sceneOctree.dynamicContent.splice(index, 1);
  13261. }
  13262. }
  13263. // Engine
  13264. this.getScene().getEngine().wipeCaches();
  13265. // Remove from scene
  13266. this.getScene().removeMesh(this);
  13267. if (!doNotRecurse) {
  13268. // Particles
  13269. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  13270. if (this.getScene().particleSystems[index].emitter === this) {
  13271. this.getScene().particleSystems[index].dispose();
  13272. index--;
  13273. }
  13274. }
  13275. // Children
  13276. var objects = this.getDescendants(true);
  13277. for (index = 0; index < objects.length; index++) {
  13278. objects[index].dispose();
  13279. }
  13280. }
  13281. else {
  13282. var childMeshes = this.getChildMeshes(true);
  13283. for (index = 0; index < childMeshes.length; index++) {
  13284. var child = childMeshes[index];
  13285. child.parent = null;
  13286. child.computeWorldMatrix(true);
  13287. }
  13288. }
  13289. // facet data
  13290. if (this._facetDataEnabled) {
  13291. this.disableFacetData();
  13292. }
  13293. this.onAfterWorldMatrixUpdateObservable.clear();
  13294. this.onCollideObservable.clear();
  13295. this.onCollisionPositionChangeObservable.clear();
  13296. this._isDisposed = true;
  13297. _super.prototype.dispose.call(this);
  13298. };
  13299. /**
  13300. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13301. * This Vector3 is expressed in the World space.
  13302. */
  13303. AbstractMesh.prototype.getDirection = function (localAxis) {
  13304. var result = BABYLON.Vector3.Zero();
  13305. this.getDirectionToRef(localAxis, result);
  13306. return result;
  13307. };
  13308. /**
  13309. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13310. * localAxis is expressed in the mesh local space.
  13311. * result is computed in the Wordl space from the mesh World matrix.
  13312. * Returns the AbstractMesh.
  13313. */
  13314. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  13315. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13316. return this;
  13317. };
  13318. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  13319. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13320. if (this.getScene().getRenderId() == 0) {
  13321. this.computeWorldMatrix(true);
  13322. }
  13323. var wm = this.getWorldMatrix();
  13324. if (space == BABYLON.Space.WORLD) {
  13325. var tmat = BABYLON.Tmp.Matrix[0];
  13326. wm.invertToRef(tmat);
  13327. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13328. }
  13329. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13330. this._pivotMatrix.m[12] = -point.x;
  13331. this._pivotMatrix.m[13] = -point.y;
  13332. this._pivotMatrix.m[14] = -point.z;
  13333. this._cache.pivotMatrixUpdated = true;
  13334. return this;
  13335. };
  13336. /**
  13337. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13338. */
  13339. AbstractMesh.prototype.getPivotPoint = function () {
  13340. var point = BABYLON.Vector3.Zero();
  13341. this.getPivotPointToRef(point);
  13342. return point;
  13343. };
  13344. /**
  13345. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13346. * Returns the AbstractMesh.
  13347. */
  13348. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  13349. result.x = -this._pivotMatrix.m[12];
  13350. result.y = -this._pivotMatrix.m[13];
  13351. result.z = -this._pivotMatrix.m[14];
  13352. return this;
  13353. };
  13354. /**
  13355. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13356. */
  13357. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  13358. var point = BABYLON.Vector3.Zero();
  13359. this.getAbsolutePivotPointToRef(point);
  13360. return point;
  13361. };
  13362. /**
  13363. * Defines the passed mesh as the parent of the current mesh.
  13364. * Returns the AbstractMesh.
  13365. */
  13366. AbstractMesh.prototype.setParent = function (mesh) {
  13367. var child = this;
  13368. var parent = mesh;
  13369. if (mesh == null) {
  13370. var rotation = BABYLON.Tmp.Quaternion[0];
  13371. var position = BABYLON.Tmp.Vector3[0];
  13372. var scale = BABYLON.Tmp.Vector3[1];
  13373. child.getWorldMatrix().decompose(scale, rotation, position);
  13374. if (child.rotationQuaternion) {
  13375. child.rotationQuaternion.copyFrom(rotation);
  13376. }
  13377. else {
  13378. rotation.toEulerAnglesToRef(child.rotation);
  13379. }
  13380. child.position.x = position.x;
  13381. child.position.y = position.y;
  13382. child.position.z = position.z;
  13383. }
  13384. else {
  13385. var rotation = BABYLON.Tmp.Quaternion[0];
  13386. var position = BABYLON.Tmp.Vector3[0];
  13387. var scale = BABYLON.Tmp.Vector3[1];
  13388. var m1 = BABYLON.Tmp.Matrix[0];
  13389. var m2 = BABYLON.Tmp.Matrix[1];
  13390. parent.getWorldMatrix().decompose(scale, rotation, position);
  13391. rotation.toRotationMatrix(m1);
  13392. m2.setTranslation(position);
  13393. m2.multiplyToRef(m1, m1);
  13394. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  13395. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13396. m.decompose(scale, rotation, position);
  13397. if (child.rotationQuaternion) {
  13398. child.rotationQuaternion.copyFrom(rotation);
  13399. }
  13400. else {
  13401. rotation.toEulerAnglesToRef(child.rotation);
  13402. }
  13403. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  13404. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13405. m.decompose(scale, rotation, position);
  13406. child.position.x = position.x;
  13407. child.position.y = position.y;
  13408. child.position.z = position.z;
  13409. }
  13410. child.parent = parent;
  13411. return this;
  13412. };
  13413. /**
  13414. * Adds the passed mesh as a child to the current mesh.
  13415. * Returns the AbstractMesh.
  13416. */
  13417. AbstractMesh.prototype.addChild = function (mesh) {
  13418. mesh.setParent(this);
  13419. return this;
  13420. };
  13421. /**
  13422. * Removes the passed mesh from the current mesh children list.
  13423. * Returns the AbstractMesh.
  13424. */
  13425. AbstractMesh.prototype.removeChild = function (mesh) {
  13426. mesh.setParent(null);
  13427. return this;
  13428. };
  13429. /**
  13430. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  13431. * Returns the AbstractMesh.
  13432. */
  13433. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  13434. result.x = this._pivotMatrix.m[12];
  13435. result.y = this._pivotMatrix.m[13];
  13436. result.z = this._pivotMatrix.m[14];
  13437. this.getPivotPointToRef(result);
  13438. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  13439. return this;
  13440. };
  13441. // Facet data
  13442. /**
  13443. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  13444. * Returns the AbstractMesh.
  13445. */
  13446. AbstractMesh.prototype._initFacetData = function () {
  13447. if (!this._facetNormals) {
  13448. this._facetNormals = new Array();
  13449. }
  13450. if (!this._facetPositions) {
  13451. this._facetPositions = new Array();
  13452. }
  13453. if (!this._facetPartitioning) {
  13454. this._facetPartitioning = new Array();
  13455. }
  13456. this._facetNb = this.getIndices().length / 3;
  13457. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  13458. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  13459. for (var f = 0; f < this._facetNb; f++) {
  13460. this._facetNormals[f] = BABYLON.Vector3.Zero();
  13461. this._facetPositions[f] = BABYLON.Vector3.Zero();
  13462. }
  13463. this._facetDataEnabled = true;
  13464. return this;
  13465. };
  13466. /**
  13467. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  13468. * This method can be called within the render loop.
  13469. * 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.
  13470. * Returns the AbstractMesh.
  13471. */
  13472. AbstractMesh.prototype.updateFacetData = function () {
  13473. if (!this._facetDataEnabled) {
  13474. this._initFacetData();
  13475. }
  13476. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13477. var indices = this.getIndices();
  13478. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13479. var bInfo = this.getBoundingInfo();
  13480. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  13481. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  13482. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  13483. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  13484. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  13485. this._subDiv.max = this._partitioningSubdivisions;
  13486. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  13487. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  13488. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  13489. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  13490. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  13491. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  13492. // set the parameters for ComputeNormals()
  13493. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  13494. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  13495. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  13496. this._facetParameters.bInfo = bInfo;
  13497. this._facetParameters.bbSize = this._bbSize;
  13498. this._facetParameters.subDiv = this._subDiv;
  13499. this._facetParameters.ratio = this.partitioningBBoxRatio;
  13500. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  13501. return this;
  13502. };
  13503. /**
  13504. * Returns the facetLocalNormals array.
  13505. * The normals are expressed in the mesh local space.
  13506. */
  13507. AbstractMesh.prototype.getFacetLocalNormals = function () {
  13508. if (!this._facetNormals) {
  13509. this.updateFacetData();
  13510. }
  13511. return this._facetNormals;
  13512. };
  13513. /**
  13514. * Returns the facetLocalPositions array.
  13515. * The facet positions are expressed in the mesh local space.
  13516. */
  13517. AbstractMesh.prototype.getFacetLocalPositions = function () {
  13518. if (!this._facetPositions) {
  13519. this.updateFacetData();
  13520. }
  13521. return this._facetPositions;
  13522. };
  13523. /**
  13524. * Returns the facetLocalPartioning array.
  13525. */
  13526. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  13527. if (!this._facetPartitioning) {
  13528. this.updateFacetData();
  13529. }
  13530. return this._facetPartitioning;
  13531. };
  13532. /**
  13533. * Returns the i-th facet position in the world system.
  13534. * This method allocates a new Vector3 per call.
  13535. */
  13536. AbstractMesh.prototype.getFacetPosition = function (i) {
  13537. var pos = BABYLON.Vector3.Zero();
  13538. this.getFacetPositionToRef(i, pos);
  13539. return pos;
  13540. };
  13541. /**
  13542. * Sets the reference Vector3 with the i-th facet position in the world system.
  13543. * Returns the AbstractMesh.
  13544. */
  13545. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  13546. var localPos = (this.getFacetLocalPositions())[i];
  13547. var world = this.getWorldMatrix();
  13548. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  13549. return this;
  13550. };
  13551. /**
  13552. * Returns the i-th facet normal in the world system.
  13553. * This method allocates a new Vector3 per call.
  13554. */
  13555. AbstractMesh.prototype.getFacetNormal = function (i) {
  13556. var norm = BABYLON.Vector3.Zero();
  13557. this.getFacetNormalToRef(i, norm);
  13558. return norm;
  13559. };
  13560. /**
  13561. * Sets the reference Vector3 with the i-th facet normal in the world system.
  13562. * Returns the AbstractMesh.
  13563. */
  13564. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  13565. var localNorm = (this.getFacetLocalNormals())[i];
  13566. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  13567. return this;
  13568. };
  13569. /**
  13570. * 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).
  13571. */
  13572. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  13573. var bInfo = this.getBoundingInfo();
  13574. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  13575. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  13576. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  13577. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  13578. return null;
  13579. }
  13580. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  13581. };
  13582. /**
  13583. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  13584. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  13585. * 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.
  13586. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13587. * 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.
  13588. */
  13589. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  13590. if (checkFace === void 0) { checkFace = false; }
  13591. if (facing === void 0) { facing = true; }
  13592. var world = this.getWorldMatrix();
  13593. var invMat = BABYLON.Tmp.Matrix[5];
  13594. world.invertToRef(invMat);
  13595. var invVect = BABYLON.Tmp.Vector3[8];
  13596. var closest = null;
  13597. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  13598. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  13599. if (projected) {
  13600. // tranform the local computed projected vector to world coordinates
  13601. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  13602. }
  13603. return closest;
  13604. };
  13605. /**
  13606. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  13607. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  13608. * 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.
  13609. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13610. * 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.
  13611. */
  13612. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  13613. if (checkFace === void 0) { checkFace = false; }
  13614. if (facing === void 0) { facing = true; }
  13615. var closest = null;
  13616. var tmpx = 0.0;
  13617. var tmpy = 0.0;
  13618. var tmpz = 0.0;
  13619. var d = 0.0; // tmp dot facet normal * facet position
  13620. var t0 = 0.0;
  13621. var projx = 0.0;
  13622. var projy = 0.0;
  13623. var projz = 0.0;
  13624. // Get all the facets in the same partitioning block than (x, y, z)
  13625. var facetPositions = this.getFacetLocalPositions();
  13626. var facetNormals = this.getFacetLocalNormals();
  13627. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  13628. if (!facetsInBlock) {
  13629. return null;
  13630. }
  13631. // Get the closest facet to (x, y, z)
  13632. var shortest = Number.MAX_VALUE; // init distance vars
  13633. var tmpDistance = shortest;
  13634. var fib; // current facet in the block
  13635. var norm; // current facet normal
  13636. var p0; // current facet barycenter position
  13637. // loop on all the facets in the current partitioning block
  13638. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  13639. fib = facetsInBlock[idx];
  13640. norm = facetNormals[fib];
  13641. p0 = facetPositions[fib];
  13642. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  13643. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  13644. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  13645. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  13646. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  13647. projx = x + norm.x * t0;
  13648. projy = y + norm.y * t0;
  13649. projz = z + norm.z * t0;
  13650. tmpx = projx - x;
  13651. tmpy = projy - y;
  13652. tmpz = projz - z;
  13653. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  13654. if (tmpDistance < shortest) {
  13655. shortest = tmpDistance;
  13656. closest = fib;
  13657. if (projected) {
  13658. projected.x = projx;
  13659. projected.y = projy;
  13660. projected.z = projz;
  13661. }
  13662. }
  13663. }
  13664. }
  13665. return closest;
  13666. };
  13667. /**
  13668. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  13669. */
  13670. AbstractMesh.prototype.getFacetDataParameters = function () {
  13671. return this._facetParameters;
  13672. };
  13673. /**
  13674. * Disables the feature FacetData and frees the related memory.
  13675. * Returns the AbstractMesh.
  13676. */
  13677. AbstractMesh.prototype.disableFacetData = function () {
  13678. if (this._facetDataEnabled) {
  13679. this._facetDataEnabled = false;
  13680. this._facetPositions = null;
  13681. this._facetNormals = null;
  13682. this._facetPartitioning = null;
  13683. this._facetParameters = null;
  13684. }
  13685. return this;
  13686. };
  13687. /**
  13688. * Creates new normals data for the mesh.
  13689. * @param updatable.
  13690. */
  13691. AbstractMesh.prototype.createNormals = function (updatable) {
  13692. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13693. var indices = this.getIndices();
  13694. var normals;
  13695. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13696. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13697. }
  13698. else {
  13699. normals = [];
  13700. }
  13701. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  13702. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  13703. };
  13704. return AbstractMesh;
  13705. }(BABYLON.Node));
  13706. // Statics
  13707. AbstractMesh._BILLBOARDMODE_NONE = 0;
  13708. AbstractMesh._BILLBOARDMODE_X = 1;
  13709. AbstractMesh._BILLBOARDMODE_Y = 2;
  13710. AbstractMesh._BILLBOARDMODE_Z = 4;
  13711. AbstractMesh._BILLBOARDMODE_ALL = 7;
  13712. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  13713. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  13714. BABYLON.AbstractMesh = AbstractMesh;
  13715. })(BABYLON || (BABYLON = {}));
  13716. //# sourceMappingURL=babylon.abstractMesh.js.map
  13717. var BABYLON;
  13718. (function (BABYLON) {
  13719. var Light = (function (_super) {
  13720. __extends(Light, _super);
  13721. /**
  13722. * Creates a Light object in the scene.
  13723. * Documentation : http://doc.babylonjs.com/tutorials/lights
  13724. */
  13725. function Light(name, scene) {
  13726. var _this = _super.call(this, name, scene) || this;
  13727. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  13728. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  13729. _this.intensity = 1.0;
  13730. _this.range = Number.MAX_VALUE;
  13731. /**
  13732. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  13733. * of light.
  13734. */
  13735. _this._photometricScale = 1.0;
  13736. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  13737. _this._radius = 0.00001;
  13738. _this.renderPriority = 0;
  13739. /**
  13740. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  13741. * the current shadow generator.
  13742. */
  13743. _this.shadowEnabled = true;
  13744. _this._excludeWithLayerMask = 0;
  13745. _this._includeOnlyWithLayerMask = 0;
  13746. _this._lightmapMode = 0;
  13747. _this._excludedMeshesIds = new Array();
  13748. _this._includedOnlyMeshesIds = new Array();
  13749. _this.getScene().addLight(_this);
  13750. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  13751. _this._buildUniformLayout();
  13752. _this.includedOnlyMeshes = new Array();
  13753. _this.excludedMeshes = new Array();
  13754. _this._resyncMeshes();
  13755. return _this;
  13756. }
  13757. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  13758. /**
  13759. * If every light affecting the material is in this lightmapMode,
  13760. * material.lightmapTexture adds or multiplies
  13761. * (depends on material.useLightmapAsShadowmap)
  13762. * after every other light calculations.
  13763. */
  13764. get: function () {
  13765. return Light._LIGHTMAP_DEFAULT;
  13766. },
  13767. enumerable: true,
  13768. configurable: true
  13769. });
  13770. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  13771. /**
  13772. * material.lightmapTexture as only diffuse lighting from this light
  13773. * adds pnly specular lighting from this light
  13774. * adds dynamic shadows
  13775. */
  13776. get: function () {
  13777. return Light._LIGHTMAP_SPECULAR;
  13778. },
  13779. enumerable: true,
  13780. configurable: true
  13781. });
  13782. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  13783. /**
  13784. * material.lightmapTexture as only lighting
  13785. * no light calculation from this light
  13786. * only adds dynamic shadows from this light
  13787. */
  13788. get: function () {
  13789. return Light._LIGHTMAP_SHADOWSONLY;
  13790. },
  13791. enumerable: true,
  13792. configurable: true
  13793. });
  13794. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  13795. /**
  13796. * Each light type uses the default quantity according to its type:
  13797. * point/spot lights use luminous intensity
  13798. * directional lights use illuminance
  13799. */
  13800. get: function () {
  13801. return Light._INTENSITYMODE_AUTOMATIC;
  13802. },
  13803. enumerable: true,
  13804. configurable: true
  13805. });
  13806. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  13807. /**
  13808. * lumen (lm)
  13809. */
  13810. get: function () {
  13811. return Light._INTENSITYMODE_LUMINOUSPOWER;
  13812. },
  13813. enumerable: true,
  13814. configurable: true
  13815. });
  13816. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  13817. /**
  13818. * candela (lm/sr)
  13819. */
  13820. get: function () {
  13821. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  13822. },
  13823. enumerable: true,
  13824. configurable: true
  13825. });
  13826. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  13827. /**
  13828. * lux (lm/m^2)
  13829. */
  13830. get: function () {
  13831. return Light._INTENSITYMODE_ILLUMINANCE;
  13832. },
  13833. enumerable: true,
  13834. configurable: true
  13835. });
  13836. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  13837. /**
  13838. * nit (cd/m^2)
  13839. */
  13840. get: function () {
  13841. return Light._INTENSITYMODE_LUMINANCE;
  13842. },
  13843. enumerable: true,
  13844. configurable: true
  13845. });
  13846. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  13847. /**
  13848. * Light type const id of the point light.
  13849. */
  13850. get: function () {
  13851. return Light._LIGHTTYPEID_POINTLIGHT;
  13852. },
  13853. enumerable: true,
  13854. configurable: true
  13855. });
  13856. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  13857. /**
  13858. * Light type const id of the directional light.
  13859. */
  13860. get: function () {
  13861. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  13862. },
  13863. enumerable: true,
  13864. configurable: true
  13865. });
  13866. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  13867. /**
  13868. * Light type const id of the spot light.
  13869. */
  13870. get: function () {
  13871. return Light._LIGHTTYPEID_SPOTLIGHT;
  13872. },
  13873. enumerable: true,
  13874. configurable: true
  13875. });
  13876. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  13877. /**
  13878. * Light type const id of the hemispheric light.
  13879. */
  13880. get: function () {
  13881. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  13882. },
  13883. enumerable: true,
  13884. configurable: true
  13885. });
  13886. Object.defineProperty(Light.prototype, "intensityMode", {
  13887. /**
  13888. * Gets the photometric scale used to interpret the intensity.
  13889. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  13890. */
  13891. get: function () {
  13892. return this._intensityMode;
  13893. },
  13894. /**
  13895. * Sets the photometric scale used to interpret the intensity.
  13896. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  13897. */
  13898. set: function (value) {
  13899. this._intensityMode = value;
  13900. this._computePhotometricScale();
  13901. },
  13902. enumerable: true,
  13903. configurable: true
  13904. });
  13905. ;
  13906. ;
  13907. Object.defineProperty(Light.prototype, "radius", {
  13908. /**
  13909. * Gets the light radius used by PBR Materials to simulate soft area lights.
  13910. */
  13911. get: function () {
  13912. return this._radius;
  13913. },
  13914. /**
  13915. * sets the light radius used by PBR Materials to simulate soft area lights.
  13916. */
  13917. set: function (value) {
  13918. this._radius = value;
  13919. this._computePhotometricScale();
  13920. },
  13921. enumerable: true,
  13922. configurable: true
  13923. });
  13924. ;
  13925. ;
  13926. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  13927. get: function () {
  13928. return this._includedOnlyMeshes;
  13929. },
  13930. set: function (value) {
  13931. this._includedOnlyMeshes = value;
  13932. this._hookArrayForIncludedOnly(value);
  13933. },
  13934. enumerable: true,
  13935. configurable: true
  13936. });
  13937. Object.defineProperty(Light.prototype, "excludedMeshes", {
  13938. get: function () {
  13939. return this._excludedMeshes;
  13940. },
  13941. set: function (value) {
  13942. this._excludedMeshes = value;
  13943. this._hookArrayForExcluded(value);
  13944. },
  13945. enumerable: true,
  13946. configurable: true
  13947. });
  13948. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  13949. get: function () {
  13950. return this._excludeWithLayerMask;
  13951. },
  13952. set: function (value) {
  13953. this._excludeWithLayerMask = value;
  13954. this._resyncMeshes();
  13955. },
  13956. enumerable: true,
  13957. configurable: true
  13958. });
  13959. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  13960. get: function () {
  13961. return this._includeOnlyWithLayerMask;
  13962. },
  13963. set: function (value) {
  13964. this._includeOnlyWithLayerMask = value;
  13965. this._resyncMeshes();
  13966. },
  13967. enumerable: true,
  13968. configurable: true
  13969. });
  13970. Object.defineProperty(Light.prototype, "lightmapMode", {
  13971. get: function () {
  13972. return this._lightmapMode;
  13973. },
  13974. set: function (value) {
  13975. if (this._lightmapMode === value) {
  13976. return;
  13977. }
  13978. this._lightmapMode = value;
  13979. this._markMeshesAsLightDirty();
  13980. },
  13981. enumerable: true,
  13982. configurable: true
  13983. });
  13984. Light.prototype._buildUniformLayout = function () {
  13985. // Overridden
  13986. };
  13987. /**
  13988. * Returns the string "Light".
  13989. */
  13990. Light.prototype.getClassName = function () {
  13991. return "Light";
  13992. };
  13993. /**
  13994. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13995. */
  13996. Light.prototype.toString = function (fullDetails) {
  13997. var ret = "Name: " + this.name;
  13998. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  13999. if (this.animations) {
  14000. for (var i = 0; i < this.animations.length; i++) {
  14001. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14002. }
  14003. }
  14004. if (fullDetails) {
  14005. }
  14006. return ret;
  14007. };
  14008. /**
  14009. * Set the enabled state of this node.
  14010. * @param {boolean} value - the new enabled state
  14011. * @see isEnabled
  14012. */
  14013. Light.prototype.setEnabled = function (value) {
  14014. _super.prototype.setEnabled.call(this, value);
  14015. this._resyncMeshes();
  14016. };
  14017. /**
  14018. * Returns the Light associated shadow generator.
  14019. */
  14020. Light.prototype.getShadowGenerator = function () {
  14021. return this._shadowGenerator;
  14022. };
  14023. /**
  14024. * Returns a Vector3, the absolute light position in the World.
  14025. */
  14026. Light.prototype.getAbsolutePosition = function () {
  14027. return BABYLON.Vector3.Zero();
  14028. };
  14029. Light.prototype.transferToEffect = function (effect, lightIndex) {
  14030. };
  14031. Light.prototype._getWorldMatrix = function () {
  14032. return BABYLON.Matrix.Identity();
  14033. };
  14034. /**
  14035. * Boolean : True if the light will affect the passed mesh.
  14036. */
  14037. Light.prototype.canAffectMesh = function (mesh) {
  14038. if (!mesh) {
  14039. return true;
  14040. }
  14041. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  14042. return false;
  14043. }
  14044. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  14045. return false;
  14046. }
  14047. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  14048. return false;
  14049. }
  14050. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  14051. return false;
  14052. }
  14053. return true;
  14054. };
  14055. /**
  14056. * Returns the light World matrix.
  14057. */
  14058. Light.prototype.getWorldMatrix = function () {
  14059. this._currentRenderId = this.getScene().getRenderId();
  14060. var worldMatrix = this._getWorldMatrix();
  14061. if (this.parent && this.parent.getWorldMatrix) {
  14062. if (!this._parentedWorldMatrix) {
  14063. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  14064. }
  14065. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  14066. this._markSyncedWithParent();
  14067. return this._parentedWorldMatrix;
  14068. }
  14069. return worldMatrix;
  14070. };
  14071. /**
  14072. * Sort function to order lights for rendering.
  14073. * @param a First Light object to compare to second.
  14074. * @param b Second Light object to compare first.
  14075. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  14076. */
  14077. Light.compareLightsPriority = function (a, b) {
  14078. //shadow-casting lights have priority over non-shadow-casting lights
  14079. //the renderPrioirty is a secondary sort criterion
  14080. if (a.shadowEnabled !== b.shadowEnabled) {
  14081. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  14082. }
  14083. return b.renderPriority - a.renderPriority;
  14084. };
  14085. /**
  14086. * Disposes the light.
  14087. */
  14088. Light.prototype.dispose = function () {
  14089. if (this._shadowGenerator) {
  14090. this._shadowGenerator.dispose();
  14091. this._shadowGenerator = null;
  14092. }
  14093. // Animations
  14094. this.getScene().stopAnimation(this);
  14095. // Remove from meshes
  14096. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14097. var mesh = _a[_i];
  14098. mesh._removeLightSource(this);
  14099. }
  14100. this._uniformBuffer.dispose();
  14101. // Remove from scene
  14102. this.getScene().removeLight(this);
  14103. _super.prototype.dispose.call(this);
  14104. };
  14105. /**
  14106. * Returns the light type ID (integer).
  14107. */
  14108. Light.prototype.getTypeID = function () {
  14109. return 0;
  14110. };
  14111. /**
  14112. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  14113. */
  14114. Light.prototype.getScaledIntensity = function () {
  14115. return this._photometricScale * this.intensity;
  14116. };
  14117. /**
  14118. * Returns a new Light object, named "name", from the current one.
  14119. */
  14120. Light.prototype.clone = function (name) {
  14121. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  14122. };
  14123. /**
  14124. * Serializes the current light into a Serialization object.
  14125. * Returns the serialized object.
  14126. */
  14127. Light.prototype.serialize = function () {
  14128. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14129. // Type
  14130. serializationObject.type = this.getTypeID();
  14131. // Parent
  14132. if (this.parent) {
  14133. serializationObject.parentId = this.parent.id;
  14134. }
  14135. // Inclusion / exclusions
  14136. if (this.excludedMeshes.length > 0) {
  14137. serializationObject.excludedMeshesIds = [];
  14138. this.excludedMeshes.forEach(function (mesh) {
  14139. serializationObject.excludedMeshesIds.push(mesh.id);
  14140. });
  14141. }
  14142. if (this.includedOnlyMeshes.length > 0) {
  14143. serializationObject.includedOnlyMeshesIds = [];
  14144. this.includedOnlyMeshes.forEach(function (mesh) {
  14145. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  14146. });
  14147. }
  14148. // Animations
  14149. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14150. serializationObject.ranges = this.serializeAnimationRanges();
  14151. return serializationObject;
  14152. };
  14153. /**
  14154. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  14155. * This new light is named "name" and added to the passed scene.
  14156. */
  14157. Light.GetConstructorFromName = function (type, name, scene) {
  14158. switch (type) {
  14159. case 0:
  14160. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  14161. case 1:
  14162. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  14163. case 2:
  14164. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  14165. case 3:
  14166. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  14167. }
  14168. };
  14169. /**
  14170. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  14171. */
  14172. Light.Parse = function (parsedLight, scene) {
  14173. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  14174. // Inclusion / exclusions
  14175. if (parsedLight.excludedMeshesIds) {
  14176. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  14177. }
  14178. if (parsedLight.includedOnlyMeshesIds) {
  14179. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  14180. }
  14181. // Parent
  14182. if (parsedLight.parentId) {
  14183. light._waitingParentId = parsedLight.parentId;
  14184. }
  14185. // Animations
  14186. if (parsedLight.animations) {
  14187. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  14188. var parsedAnimation = parsedLight.animations[animationIndex];
  14189. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14190. }
  14191. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  14192. }
  14193. if (parsedLight.autoAnimate) {
  14194. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  14195. }
  14196. return light;
  14197. };
  14198. Light.prototype._hookArrayForExcluded = function (array) {
  14199. var _this = this;
  14200. var oldPush = array.push;
  14201. array.push = function () {
  14202. var items = [];
  14203. for (var _i = 0; _i < arguments.length; _i++) {
  14204. items[_i] = arguments[_i];
  14205. }
  14206. var result = oldPush.apply(array, items);
  14207. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  14208. var item = items_1[_a];
  14209. item._resyncLighSource(_this);
  14210. }
  14211. return result;
  14212. };
  14213. var oldSplice = array.splice;
  14214. array.splice = function (index, deleteCount) {
  14215. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14216. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  14217. var item = deleted_1[_i];
  14218. item._resyncLighSource(_this);
  14219. }
  14220. return deleted;
  14221. };
  14222. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  14223. var item = array_1[_i];
  14224. item._resyncLighSource(this);
  14225. }
  14226. };
  14227. Light.prototype._hookArrayForIncludedOnly = function (array) {
  14228. var _this = this;
  14229. var oldPush = array.push;
  14230. array.push = function () {
  14231. var items = [];
  14232. for (var _i = 0; _i < arguments.length; _i++) {
  14233. items[_i] = arguments[_i];
  14234. }
  14235. var result = oldPush.apply(array, items);
  14236. _this._resyncMeshes();
  14237. return result;
  14238. };
  14239. var oldSplice = array.splice;
  14240. array.splice = function (index, deleteCount) {
  14241. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14242. _this._resyncMeshes();
  14243. return deleted;
  14244. };
  14245. this._resyncMeshes();
  14246. };
  14247. Light.prototype._resyncMeshes = function () {
  14248. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14249. var mesh = _a[_i];
  14250. mesh._resyncLighSource(this);
  14251. }
  14252. };
  14253. Light.prototype._markMeshesAsLightDirty = function () {
  14254. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14255. var mesh = _a[_i];
  14256. if (mesh._lightSources.indexOf(this) !== -1) {
  14257. mesh._markSubMeshesAsLightDirty();
  14258. }
  14259. }
  14260. };
  14261. /**
  14262. * Recomputes the cached photometric scale if needed.
  14263. */
  14264. Light.prototype._computePhotometricScale = function () {
  14265. this._photometricScale = this._getPhotometricScale();
  14266. this.getScene().resetCachedMaterial();
  14267. };
  14268. /**
  14269. * Returns the Photometric Scale according to the light type and intensity mode.
  14270. */
  14271. Light.prototype._getPhotometricScale = function () {
  14272. var photometricScale = 0.0;
  14273. var lightTypeID = this.getTypeID();
  14274. //get photometric mode
  14275. var photometricMode = this.intensityMode;
  14276. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  14277. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  14278. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  14279. }
  14280. else {
  14281. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  14282. }
  14283. }
  14284. //compute photometric scale
  14285. switch (lightTypeID) {
  14286. case Light.LIGHTTYPEID_POINTLIGHT:
  14287. case Light.LIGHTTYPEID_SPOTLIGHT:
  14288. switch (photometricMode) {
  14289. case Light.INTENSITYMODE_LUMINOUSPOWER:
  14290. photometricScale = 1.0 / (4.0 * Math.PI);
  14291. break;
  14292. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  14293. photometricScale = 1.0;
  14294. break;
  14295. case Light.INTENSITYMODE_LUMINANCE:
  14296. photometricScale = this.radius * this.radius;
  14297. break;
  14298. }
  14299. break;
  14300. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  14301. switch (photometricMode) {
  14302. case Light.INTENSITYMODE_ILLUMINANCE:
  14303. photometricScale = 1.0;
  14304. break;
  14305. case Light.INTENSITYMODE_LUMINANCE:
  14306. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  14307. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  14308. var apexAngleRadians = this.radius;
  14309. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  14310. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  14311. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  14312. photometricScale = solidAngle;
  14313. break;
  14314. }
  14315. break;
  14316. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  14317. // No fall off in hemisperic light.
  14318. photometricScale = 1.0;
  14319. break;
  14320. }
  14321. return photometricScale;
  14322. };
  14323. Light.prototype._reorderLightsInScene = function () {
  14324. var scene = this.getScene();
  14325. if (this.renderPriority != 0) {
  14326. scene.requireLightSorting = true;
  14327. }
  14328. this.getScene().sortLightsByPriority();
  14329. };
  14330. return Light;
  14331. }(BABYLON.Node));
  14332. //lightmapMode Consts
  14333. Light._LIGHTMAP_DEFAULT = 0;
  14334. Light._LIGHTMAP_SPECULAR = 1;
  14335. Light._LIGHTMAP_SHADOWSONLY = 2;
  14336. // Intensity Mode Consts
  14337. Light._INTENSITYMODE_AUTOMATIC = 0;
  14338. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  14339. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  14340. Light._INTENSITYMODE_ILLUMINANCE = 3;
  14341. Light._INTENSITYMODE_LUMINANCE = 4;
  14342. // Light types ids const.
  14343. Light._LIGHTTYPEID_POINTLIGHT = 0;
  14344. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  14345. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  14346. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  14347. __decorate([
  14348. BABYLON.serializeAsColor3()
  14349. ], Light.prototype, "diffuse", void 0);
  14350. __decorate([
  14351. BABYLON.serializeAsColor3()
  14352. ], Light.prototype, "specular", void 0);
  14353. __decorate([
  14354. BABYLON.serialize()
  14355. ], Light.prototype, "intensity", void 0);
  14356. __decorate([
  14357. BABYLON.serialize()
  14358. ], Light.prototype, "range", void 0);
  14359. __decorate([
  14360. BABYLON.serialize()
  14361. ], Light.prototype, "intensityMode", null);
  14362. __decorate([
  14363. BABYLON.serialize()
  14364. ], Light.prototype, "radius", null);
  14365. __decorate([
  14366. BABYLON.serialize()
  14367. ], Light.prototype, "_renderPriority", void 0);
  14368. __decorate([
  14369. BABYLON.expandToProperty("_reorderLightsInScene")
  14370. ], Light.prototype, "renderPriority", void 0);
  14371. __decorate([
  14372. BABYLON.serialize()
  14373. ], Light.prototype, "shadowEnabled", void 0);
  14374. __decorate([
  14375. BABYLON.serialize("excludeWithLayerMask")
  14376. ], Light.prototype, "_excludeWithLayerMask", void 0);
  14377. __decorate([
  14378. BABYLON.serialize("includeOnlyWithLayerMask")
  14379. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  14380. __decorate([
  14381. BABYLON.serialize("lightmapMode")
  14382. ], Light.prototype, "_lightmapMode", void 0);
  14383. BABYLON.Light = Light;
  14384. })(BABYLON || (BABYLON = {}));
  14385. //# sourceMappingURL=babylon.light.js.map
  14386. var BABYLON;
  14387. (function (BABYLON) {
  14388. var Camera = (function (_super) {
  14389. __extends(Camera, _super);
  14390. function Camera(name, position, scene) {
  14391. var _this = _super.call(this, name, scene) || this;
  14392. _this.upVector = BABYLON.Vector3.Up();
  14393. _this.orthoLeft = null;
  14394. _this.orthoRight = null;
  14395. _this.orthoBottom = null;
  14396. _this.orthoTop = null;
  14397. _this.fov = 0.8;
  14398. _this.minZ = 1.0;
  14399. _this.maxZ = 10000.0;
  14400. _this.inertia = 0.9;
  14401. _this.mode = Camera.PERSPECTIVE_CAMERA;
  14402. _this.isIntermediate = false;
  14403. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  14404. _this.layerMask = 0x0FFFFFFF;
  14405. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  14406. // Camera rig members
  14407. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  14408. _this._rigCameras = new Array();
  14409. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  14410. _this.customRenderTargets = new Array();
  14411. // Observables
  14412. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  14413. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  14414. // Cache
  14415. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  14416. _this._projectionMatrix = new BABYLON.Matrix();
  14417. _this._doNotComputeProjectionMatrix = false;
  14418. _this._postProcesses = new Array();
  14419. _this._transformMatrix = BABYLON.Matrix.Zero();
  14420. _this._activeMeshes = new BABYLON.SmartArray(256);
  14421. _this._globalPosition = BABYLON.Vector3.Zero();
  14422. _this._refreshFrustumPlanes = true;
  14423. _this.getScene().addCamera(_this);
  14424. if (!_this.getScene().activeCamera) {
  14425. _this.getScene().activeCamera = _this;
  14426. }
  14427. _this.position = position;
  14428. return _this;
  14429. }
  14430. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  14431. get: function () {
  14432. return Camera._PERSPECTIVE_CAMERA;
  14433. },
  14434. enumerable: true,
  14435. configurable: true
  14436. });
  14437. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  14438. get: function () {
  14439. return Camera._ORTHOGRAPHIC_CAMERA;
  14440. },
  14441. enumerable: true,
  14442. configurable: true
  14443. });
  14444. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  14445. get: function () {
  14446. return Camera._FOVMODE_VERTICAL_FIXED;
  14447. },
  14448. enumerable: true,
  14449. configurable: true
  14450. });
  14451. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  14452. get: function () {
  14453. return Camera._FOVMODE_HORIZONTAL_FIXED;
  14454. },
  14455. enumerable: true,
  14456. configurable: true
  14457. });
  14458. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  14459. get: function () {
  14460. return Camera._RIG_MODE_NONE;
  14461. },
  14462. enumerable: true,
  14463. configurable: true
  14464. });
  14465. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  14466. get: function () {
  14467. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  14468. },
  14469. enumerable: true,
  14470. configurable: true
  14471. });
  14472. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  14473. get: function () {
  14474. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  14475. },
  14476. enumerable: true,
  14477. configurable: true
  14478. });
  14479. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  14480. get: function () {
  14481. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  14482. },
  14483. enumerable: true,
  14484. configurable: true
  14485. });
  14486. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  14487. get: function () {
  14488. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  14489. },
  14490. enumerable: true,
  14491. configurable: true
  14492. });
  14493. Object.defineProperty(Camera, "RIG_MODE_VR", {
  14494. get: function () {
  14495. return Camera._RIG_MODE_VR;
  14496. },
  14497. enumerable: true,
  14498. configurable: true
  14499. });
  14500. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  14501. get: function () {
  14502. return Camera._RIG_MODE_WEBVR;
  14503. },
  14504. enumerable: true,
  14505. configurable: true
  14506. });
  14507. Camera.prototype.getClassName = function () {
  14508. return "Camera";
  14509. };
  14510. /**
  14511. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14512. */
  14513. Camera.prototype.toString = function (fullDetails) {
  14514. var ret = "Name: " + this.name;
  14515. ret += ", type: " + this.getClassName();
  14516. if (this.animations) {
  14517. for (var i = 0; i < this.animations.length; i++) {
  14518. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14519. }
  14520. }
  14521. if (fullDetails) {
  14522. }
  14523. return ret;
  14524. };
  14525. Object.defineProperty(Camera.prototype, "globalPosition", {
  14526. get: function () {
  14527. return this._globalPosition;
  14528. },
  14529. enumerable: true,
  14530. configurable: true
  14531. });
  14532. Camera.prototype.getActiveMeshes = function () {
  14533. return this._activeMeshes;
  14534. };
  14535. Camera.prototype.isActiveMesh = function (mesh) {
  14536. return (this._activeMeshes.indexOf(mesh) !== -1);
  14537. };
  14538. //Cache
  14539. Camera.prototype._initCache = function () {
  14540. _super.prototype._initCache.call(this);
  14541. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14542. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14543. this._cache.mode = undefined;
  14544. this._cache.minZ = undefined;
  14545. this._cache.maxZ = undefined;
  14546. this._cache.fov = undefined;
  14547. this._cache.fovMode = undefined;
  14548. this._cache.aspectRatio = undefined;
  14549. this._cache.orthoLeft = undefined;
  14550. this._cache.orthoRight = undefined;
  14551. this._cache.orthoBottom = undefined;
  14552. this._cache.orthoTop = undefined;
  14553. this._cache.renderWidth = undefined;
  14554. this._cache.renderHeight = undefined;
  14555. };
  14556. Camera.prototype._updateCache = function (ignoreParentClass) {
  14557. if (!ignoreParentClass) {
  14558. _super.prototype._updateCache.call(this);
  14559. }
  14560. var engine = this.getEngine();
  14561. this._cache.position.copyFrom(this.position);
  14562. this._cache.upVector.copyFrom(this.upVector);
  14563. this._cache.mode = this.mode;
  14564. this._cache.minZ = this.minZ;
  14565. this._cache.maxZ = this.maxZ;
  14566. this._cache.fov = this.fov;
  14567. this._cache.fovMode = this.fovMode;
  14568. this._cache.aspectRatio = engine.getAspectRatio(this);
  14569. this._cache.orthoLeft = this.orthoLeft;
  14570. this._cache.orthoRight = this.orthoRight;
  14571. this._cache.orthoBottom = this.orthoBottom;
  14572. this._cache.orthoTop = this.orthoTop;
  14573. this._cache.renderWidth = engine.getRenderWidth();
  14574. this._cache.renderHeight = engine.getRenderHeight();
  14575. };
  14576. Camera.prototype._updateFromScene = function () {
  14577. this.updateCache();
  14578. this.update();
  14579. };
  14580. // Synchronized
  14581. Camera.prototype._isSynchronized = function () {
  14582. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  14583. };
  14584. Camera.prototype._isSynchronizedViewMatrix = function () {
  14585. if (!_super.prototype._isSynchronized.call(this))
  14586. return false;
  14587. return this._cache.position.equals(this.position)
  14588. && this._cache.upVector.equals(this.upVector)
  14589. && this.isSynchronizedWithParent();
  14590. };
  14591. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  14592. var check = this._cache.mode === this.mode
  14593. && this._cache.minZ === this.minZ
  14594. && this._cache.maxZ === this.maxZ;
  14595. if (!check) {
  14596. return false;
  14597. }
  14598. var engine = this.getEngine();
  14599. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14600. check = this._cache.fov === this.fov
  14601. && this._cache.fovMode === this.fovMode
  14602. && this._cache.aspectRatio === engine.getAspectRatio(this);
  14603. }
  14604. else {
  14605. check = this._cache.orthoLeft === this.orthoLeft
  14606. && this._cache.orthoRight === this.orthoRight
  14607. && this._cache.orthoBottom === this.orthoBottom
  14608. && this._cache.orthoTop === this.orthoTop
  14609. && this._cache.renderWidth === engine.getRenderWidth()
  14610. && this._cache.renderHeight === engine.getRenderHeight();
  14611. }
  14612. return check;
  14613. };
  14614. // Controls
  14615. Camera.prototype.attachControl = function (element, noPreventDefault) {
  14616. };
  14617. Camera.prototype.detachControl = function (element) {
  14618. };
  14619. Camera.prototype.update = function () {
  14620. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14621. this._updateRigCameras();
  14622. }
  14623. this._checkInputs();
  14624. };
  14625. Camera.prototype._checkInputs = function () {
  14626. };
  14627. Object.defineProperty(Camera.prototype, "rigCameras", {
  14628. get: function () {
  14629. return this._rigCameras;
  14630. },
  14631. enumerable: true,
  14632. configurable: true
  14633. });
  14634. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  14635. get: function () {
  14636. return this._rigPostProcess;
  14637. },
  14638. enumerable: true,
  14639. configurable: true
  14640. });
  14641. Camera.prototype._cascadePostProcessesToRigCams = function () {
  14642. // invalidate framebuffer
  14643. if (this._postProcesses.length > 0) {
  14644. this._postProcesses[0].markTextureDirty();
  14645. }
  14646. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  14647. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  14648. var cam = this._rigCameras[i];
  14649. var rigPostProcess = cam._rigPostProcess;
  14650. // for VR rig, there does not have to be a post process
  14651. if (rigPostProcess) {
  14652. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  14653. if (isPass) {
  14654. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  14655. cam.isIntermediate = this._postProcesses.length === 0;
  14656. }
  14657. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  14658. rigPostProcess.markTextureDirty();
  14659. }
  14660. else {
  14661. cam._postProcesses = this._postProcesses.slice(0);
  14662. }
  14663. }
  14664. };
  14665. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  14666. if (insertAt === void 0) { insertAt = null; }
  14667. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  14668. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  14669. return 0;
  14670. }
  14671. if (insertAt == null || insertAt < 0) {
  14672. this._postProcesses.push(postProcess);
  14673. }
  14674. else {
  14675. this._postProcesses.splice(insertAt, 0, postProcess);
  14676. }
  14677. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14678. return this._postProcesses.indexOf(postProcess);
  14679. };
  14680. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  14681. if (atIndices === void 0) { atIndices = null; }
  14682. var result = [];
  14683. var i;
  14684. var index;
  14685. if (!atIndices) {
  14686. var idx = this._postProcesses.indexOf(postProcess);
  14687. if (idx !== -1) {
  14688. this._postProcesses.splice(idx, 1);
  14689. }
  14690. }
  14691. else {
  14692. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  14693. // iterate descending, so can just splice as we go
  14694. for (i = atIndices.length - 1; i >= 0; i--) {
  14695. if (this._postProcesses[atIndices[i]] !== postProcess) {
  14696. result.push(i);
  14697. continue;
  14698. }
  14699. index = atIndices[i];
  14700. this._postProcesses.splice(index, 1);
  14701. }
  14702. }
  14703. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14704. return result;
  14705. };
  14706. Camera.prototype.getWorldMatrix = function () {
  14707. if (!this._worldMatrix) {
  14708. this._worldMatrix = BABYLON.Matrix.Identity();
  14709. }
  14710. var viewMatrix = this.getViewMatrix();
  14711. viewMatrix.invertToRef(this._worldMatrix);
  14712. return this._worldMatrix;
  14713. };
  14714. Camera.prototype._getViewMatrix = function () {
  14715. return BABYLON.Matrix.Identity();
  14716. };
  14717. Camera.prototype.getViewMatrix = function (force) {
  14718. if (!force && this._isSynchronizedViewMatrix()) {
  14719. return this._computedViewMatrix;
  14720. }
  14721. this._computedViewMatrix = this._getViewMatrix();
  14722. this._currentRenderId = this.getScene().getRenderId();
  14723. this._refreshFrustumPlanes = true;
  14724. if (!this.parent || !this.parent.getWorldMatrix) {
  14725. this._globalPosition.copyFrom(this.position);
  14726. }
  14727. else {
  14728. if (!this._worldMatrix) {
  14729. this._worldMatrix = BABYLON.Matrix.Identity();
  14730. }
  14731. this._computedViewMatrix.invertToRef(this._worldMatrix);
  14732. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  14733. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  14734. this._computedViewMatrix.invert();
  14735. this._markSyncedWithParent();
  14736. }
  14737. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  14738. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  14739. }
  14740. this.onViewMatrixChangedObservable.notifyObservers(this);
  14741. return this._computedViewMatrix;
  14742. };
  14743. Camera.prototype.freezeProjectionMatrix = function (projection) {
  14744. this._doNotComputeProjectionMatrix = true;
  14745. if (projection !== undefined) {
  14746. this._projectionMatrix = projection;
  14747. }
  14748. };
  14749. ;
  14750. Camera.prototype.unfreezeProjectionMatrix = function () {
  14751. this._doNotComputeProjectionMatrix = false;
  14752. };
  14753. ;
  14754. Camera.prototype.getProjectionMatrix = function (force) {
  14755. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  14756. return this._projectionMatrix;
  14757. }
  14758. this._refreshFrustumPlanes = true;
  14759. var engine = this.getEngine();
  14760. var scene = this.getScene();
  14761. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14762. if (this.minZ <= 0) {
  14763. this.minZ = 0.1;
  14764. }
  14765. if (scene.useRightHandedSystem) {
  14766. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14767. }
  14768. else {
  14769. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14770. }
  14771. }
  14772. else {
  14773. var halfWidth = engine.getRenderWidth() / 2.0;
  14774. var halfHeight = engine.getRenderHeight() / 2.0;
  14775. if (scene.useRightHandedSystem) {
  14776. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14777. }
  14778. else {
  14779. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14780. }
  14781. }
  14782. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  14783. return this._projectionMatrix;
  14784. };
  14785. Camera.prototype.getTranformationMatrix = function () {
  14786. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  14787. return this._transformMatrix;
  14788. };
  14789. Camera.prototype.updateFrustumPlanes = function () {
  14790. if (!this._refreshFrustumPlanes) {
  14791. return;
  14792. }
  14793. this.getTranformationMatrix();
  14794. if (!this._frustumPlanes) {
  14795. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  14796. }
  14797. else {
  14798. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  14799. }
  14800. this._refreshFrustumPlanes = false;
  14801. };
  14802. Camera.prototype.isInFrustum = function (target) {
  14803. this.updateFrustumPlanes();
  14804. return target.isInFrustum(this._frustumPlanes);
  14805. };
  14806. Camera.prototype.isCompletelyInFrustum = function (target) {
  14807. this.updateFrustumPlanes();
  14808. return target.isCompletelyInFrustum(this._frustumPlanes);
  14809. };
  14810. Camera.prototype.getForwardRay = function (length, transform, origin) {
  14811. if (length === void 0) { length = 100; }
  14812. if (!transform) {
  14813. transform = this.getWorldMatrix();
  14814. }
  14815. if (!origin) {
  14816. origin = this.position;
  14817. }
  14818. var forward = new BABYLON.Vector3(0, 0, 1);
  14819. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  14820. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  14821. return new BABYLON.Ray(origin, direction, length);
  14822. };
  14823. Camera.prototype.dispose = function () {
  14824. // Observables
  14825. this.onViewMatrixChangedObservable.clear();
  14826. this.onProjectionMatrixChangedObservable.clear();
  14827. // Animations
  14828. this.getScene().stopAnimation(this);
  14829. // Remove from scene
  14830. this.getScene().removeCamera(this);
  14831. while (this._rigCameras.length > 0) {
  14832. this._rigCameras.pop().dispose();
  14833. }
  14834. // Postprocesses
  14835. var i = this._postProcesses.length;
  14836. while (--i >= 0) {
  14837. this._postProcesses[i].dispose(this);
  14838. }
  14839. // Render targets
  14840. var i = this.customRenderTargets.length;
  14841. while (--i >= 0) {
  14842. this.customRenderTargets[i].dispose();
  14843. }
  14844. this.customRenderTargets = [];
  14845. // Active Meshes
  14846. this._activeMeshes.dispose();
  14847. _super.prototype.dispose.call(this);
  14848. };
  14849. Object.defineProperty(Camera.prototype, "leftCamera", {
  14850. // ---- Camera rigs section ----
  14851. get: function () {
  14852. if (this._rigCameras.length < 1) {
  14853. return undefined;
  14854. }
  14855. return this._rigCameras[0];
  14856. },
  14857. enumerable: true,
  14858. configurable: true
  14859. });
  14860. Object.defineProperty(Camera.prototype, "rightCamera", {
  14861. get: function () {
  14862. if (this._rigCameras.length < 2) {
  14863. return undefined;
  14864. }
  14865. return this._rigCameras[1];
  14866. },
  14867. enumerable: true,
  14868. configurable: true
  14869. });
  14870. Camera.prototype.getLeftTarget = function () {
  14871. if (this._rigCameras.length < 1) {
  14872. return undefined;
  14873. }
  14874. return this._rigCameras[0].getTarget();
  14875. };
  14876. Camera.prototype.getRightTarget = function () {
  14877. if (this._rigCameras.length < 2) {
  14878. return undefined;
  14879. }
  14880. return this._rigCameras[1].getTarget();
  14881. };
  14882. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  14883. while (this._rigCameras.length > 0) {
  14884. this._rigCameras.pop().dispose();
  14885. }
  14886. this.cameraRigMode = mode;
  14887. this._cameraRigParams = {};
  14888. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  14889. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  14890. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  14891. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  14892. // create the rig cameras, unless none
  14893. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14894. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  14895. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  14896. }
  14897. switch (this.cameraRigMode) {
  14898. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14899. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14900. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  14901. break;
  14902. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14903. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14904. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14905. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  14906. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14907. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  14908. break;
  14909. case Camera.RIG_MODE_VR:
  14910. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  14911. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  14912. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14913. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14914. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  14915. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  14916. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  14917. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  14918. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14919. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14920. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  14921. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  14922. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  14923. if (metrics.compensateDistortion) {
  14924. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  14925. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  14926. }
  14927. break;
  14928. case Camera.RIG_MODE_WEBVR:
  14929. if (rigParams.vrDisplay) {
  14930. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  14931. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  14932. //Left eye
  14933. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14934. this._rigCameras[0].setCameraRigParameter("left", true);
  14935. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  14936. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  14937. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  14938. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  14939. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14940. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14941. this._rigCameras[0].parent = this;
  14942. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  14943. //Right eye
  14944. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14945. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  14946. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  14947. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  14948. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  14949. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14950. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14951. this._rigCameras[1].parent = this;
  14952. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  14953. }
  14954. break;
  14955. }
  14956. this._cascadePostProcessesToRigCams();
  14957. this.
  14958. update();
  14959. };
  14960. Camera.prototype._getVRProjectionMatrix = function () {
  14961. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  14962. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  14963. return this._projectionMatrix;
  14964. };
  14965. Camera.prototype._updateCameraRotationMatrix = function () {
  14966. //Here for WebVR
  14967. };
  14968. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  14969. //Here for WebVR
  14970. };
  14971. /**
  14972. * This function MUST be overwritten by the different WebVR cameras available.
  14973. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  14974. */
  14975. Camera.prototype._getWebVRProjectionMatrix = function () {
  14976. return BABYLON.Matrix.Identity();
  14977. };
  14978. /**
  14979. * This function MUST be overwritten by the different WebVR cameras available.
  14980. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  14981. */
  14982. Camera.prototype._getWebVRViewMatrix = function () {
  14983. return BABYLON.Matrix.Identity();
  14984. };
  14985. Camera.prototype.setCameraRigParameter = function (name, value) {
  14986. if (!this._cameraRigParams) {
  14987. this._cameraRigParams = {};
  14988. }
  14989. this._cameraRigParams[name] = value;
  14990. //provisionnally:
  14991. if (name === "interaxialDistance") {
  14992. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  14993. }
  14994. };
  14995. /**
  14996. * needs to be overridden by children so sub has required properties to be copied
  14997. */
  14998. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  14999. return null;
  15000. };
  15001. /**
  15002. * May need to be overridden by children
  15003. */
  15004. Camera.prototype._updateRigCameras = function () {
  15005. for (var i = 0; i < this._rigCameras.length; i++) {
  15006. this._rigCameras[i].minZ = this.minZ;
  15007. this._rigCameras[i].maxZ = this.maxZ;
  15008. this._rigCameras[i].fov = this.fov;
  15009. }
  15010. // only update viewport when ANAGLYPH
  15011. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  15012. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  15013. }
  15014. };
  15015. Camera.prototype._setupInputs = function () {
  15016. };
  15017. Camera.prototype.serialize = function () {
  15018. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  15019. // Type
  15020. serializationObject.type = this.getClassName();
  15021. // Parent
  15022. if (this.parent) {
  15023. serializationObject.parentId = this.parent.id;
  15024. }
  15025. if (this.inputs) {
  15026. this.inputs.serialize(serializationObject);
  15027. }
  15028. // Animations
  15029. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  15030. serializationObject.ranges = this.serializeAnimationRanges();
  15031. return serializationObject;
  15032. };
  15033. Camera.prototype.clone = function (name) {
  15034. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  15035. };
  15036. Camera.prototype.getDirection = function (localAxis) {
  15037. var result = BABYLON.Vector3.Zero();
  15038. this.getDirectionToRef(localAxis, result);
  15039. return result;
  15040. };
  15041. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  15042. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  15043. };
  15044. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  15045. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  15046. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  15047. switch (type) {
  15048. case "ArcRotateCamera":
  15049. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  15050. case "DeviceOrientationCamera":
  15051. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  15052. case "FollowCamera":
  15053. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  15054. case "ArcFollowCamera":
  15055. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  15056. case "GamepadCamera":
  15057. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15058. case "TouchCamera":
  15059. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  15060. case "VirtualJoysticksCamera":
  15061. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  15062. case "WebVRFreeCamera":
  15063. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15064. case "WebVRGamepadCamera":
  15065. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15066. case "VRDeviceOrientationFreeCamera":
  15067. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15068. case "VRDeviceOrientationGamepadCamera":
  15069. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15070. case "AnaglyphArcRotateCamera":
  15071. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15072. case "AnaglyphFreeCamera":
  15073. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15074. case "AnaglyphGamepadCamera":
  15075. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15076. case "AnaglyphUniversalCamera":
  15077. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15078. case "StereoscopicArcRotateCamera":
  15079. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15080. case "StereoscopicFreeCamera":
  15081. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15082. case "StereoscopicGamepadCamera":
  15083. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15084. case "StereoscopicUniversalCamera":
  15085. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15086. case "FreeCamera":
  15087. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15088. default:
  15089. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15090. }
  15091. };
  15092. Camera.Parse = function (parsedCamera, scene) {
  15093. var type = parsedCamera.type;
  15094. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  15095. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  15096. // Parent
  15097. if (parsedCamera.parentId) {
  15098. camera._waitingParentId = parsedCamera.parentId;
  15099. }
  15100. //If camera has an input manager, let it parse inputs settings
  15101. if (camera.inputs) {
  15102. camera.inputs.parse(parsedCamera);
  15103. camera._setupInputs();
  15104. }
  15105. if (camera.setPosition) {
  15106. camera.position.copyFromFloats(0, 0, 0);
  15107. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  15108. }
  15109. // Target
  15110. if (parsedCamera.target) {
  15111. if (camera.setTarget) {
  15112. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  15113. }
  15114. }
  15115. // Apply 3d rig, when found
  15116. if (parsedCamera.cameraRigMode) {
  15117. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  15118. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  15119. }
  15120. // Animations
  15121. if (parsedCamera.animations) {
  15122. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  15123. var parsedAnimation = parsedCamera.animations[animationIndex];
  15124. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15125. }
  15126. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  15127. }
  15128. if (parsedCamera.autoAnimate) {
  15129. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  15130. }
  15131. return camera;
  15132. };
  15133. return Camera;
  15134. }(BABYLON.Node));
  15135. // Statics
  15136. Camera._PERSPECTIVE_CAMERA = 0;
  15137. Camera._ORTHOGRAPHIC_CAMERA = 1;
  15138. Camera._FOVMODE_VERTICAL_FIXED = 0;
  15139. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  15140. Camera._RIG_MODE_NONE = 0;
  15141. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  15142. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  15143. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  15144. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  15145. Camera._RIG_MODE_VR = 20;
  15146. Camera._RIG_MODE_WEBVR = 21;
  15147. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  15148. __decorate([
  15149. BABYLON.serializeAsVector3()
  15150. ], Camera.prototype, "position", void 0);
  15151. __decorate([
  15152. BABYLON.serializeAsVector3()
  15153. ], Camera.prototype, "upVector", void 0);
  15154. __decorate([
  15155. BABYLON.serialize()
  15156. ], Camera.prototype, "orthoLeft", void 0);
  15157. __decorate([
  15158. BABYLON.serialize()
  15159. ], Camera.prototype, "orthoRight", void 0);
  15160. __decorate([
  15161. BABYLON.serialize()
  15162. ], Camera.prototype, "orthoBottom", void 0);
  15163. __decorate([
  15164. BABYLON.serialize()
  15165. ], Camera.prototype, "orthoTop", void 0);
  15166. __decorate([
  15167. BABYLON.serialize()
  15168. ], Camera.prototype, "fov", void 0);
  15169. __decorate([
  15170. BABYLON.serialize()
  15171. ], Camera.prototype, "minZ", void 0);
  15172. __decorate([
  15173. BABYLON.serialize()
  15174. ], Camera.prototype, "maxZ", void 0);
  15175. __decorate([
  15176. BABYLON.serialize()
  15177. ], Camera.prototype, "inertia", void 0);
  15178. __decorate([
  15179. BABYLON.serialize()
  15180. ], Camera.prototype, "mode", void 0);
  15181. __decorate([
  15182. BABYLON.serialize()
  15183. ], Camera.prototype, "layerMask", void 0);
  15184. __decorate([
  15185. BABYLON.serialize()
  15186. ], Camera.prototype, "fovMode", void 0);
  15187. __decorate([
  15188. BABYLON.serialize()
  15189. ], Camera.prototype, "cameraRigMode", void 0);
  15190. __decorate([
  15191. BABYLON.serialize()
  15192. ], Camera.prototype, "interaxialDistance", void 0);
  15193. __decorate([
  15194. BABYLON.serialize()
  15195. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  15196. BABYLON.Camera = Camera;
  15197. })(BABYLON || (BABYLON = {}));
  15198. //# sourceMappingURL=babylon.camera.js.map
  15199. var BABYLON;
  15200. (function (BABYLON) {
  15201. var RenderingManager = (function () {
  15202. function RenderingManager(scene) {
  15203. this._renderingGroups = new Array();
  15204. this._autoClearDepthStencil = {};
  15205. this._customOpaqueSortCompareFn = {};
  15206. this._customAlphaTestSortCompareFn = {};
  15207. this._customTransparentSortCompareFn = {};
  15208. this._renderinGroupInfo = null;
  15209. this._scene = scene;
  15210. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  15211. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  15212. }
  15213. }
  15214. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  15215. if (depth === void 0) { depth = true; }
  15216. if (stencil === void 0) { stencil = true; }
  15217. if (this._depthStencilBufferAlreadyCleaned) {
  15218. return;
  15219. }
  15220. this._scene.getEngine().clear(null, false, depth, stencil);
  15221. this._depthStencilBufferAlreadyCleaned = true;
  15222. };
  15223. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  15224. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  15225. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  15226. var info = null;
  15227. if (observable) {
  15228. if (!this._renderinGroupInfo) {
  15229. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  15230. }
  15231. info = this._renderinGroupInfo;
  15232. info.scene = this._scene;
  15233. info.camera = this._scene.activeCamera;
  15234. }
  15235. // Dispatch sprites
  15236. if (renderSprites) {
  15237. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  15238. var manager = this._scene.spriteManagers[index];
  15239. this.dispatchSprites(manager);
  15240. }
  15241. }
  15242. // Render
  15243. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15244. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  15245. var renderingGroup = this._renderingGroups[index];
  15246. if (!renderingGroup && !observable)
  15247. continue;
  15248. this._currentIndex = index;
  15249. var renderingGroupMask = 0;
  15250. // Fire PRECLEAR stage
  15251. if (observable) {
  15252. renderingGroupMask = Math.pow(2, index);
  15253. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  15254. info.renderingGroupId = index;
  15255. observable.notifyObservers(info, renderingGroupMask);
  15256. }
  15257. // Clear depth/stencil if needed
  15258. if (RenderingManager.AUTOCLEAR) {
  15259. var autoClear = this._autoClearDepthStencil[index];
  15260. if (autoClear && autoClear.autoClear) {
  15261. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  15262. }
  15263. }
  15264. if (observable) {
  15265. // Fire PREOPAQUE stage
  15266. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  15267. observable.notifyObservers(info, renderingGroupMask);
  15268. // Fire PRETRANSPARENT stage
  15269. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  15270. observable.notifyObservers(info, renderingGroupMask);
  15271. }
  15272. if (renderingGroup)
  15273. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  15274. // Fire POSTTRANSPARENT stage
  15275. if (observable) {
  15276. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  15277. observable.notifyObservers(info, renderingGroupMask);
  15278. }
  15279. }
  15280. };
  15281. RenderingManager.prototype.reset = function () {
  15282. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15283. var renderingGroup = this._renderingGroups[index];
  15284. if (renderingGroup) {
  15285. renderingGroup.prepare();
  15286. }
  15287. }
  15288. };
  15289. RenderingManager.prototype.dispose = function () {
  15290. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15291. var renderingGroup = this._renderingGroups[index];
  15292. if (renderingGroup) {
  15293. renderingGroup.dispose();
  15294. }
  15295. }
  15296. this._renderingGroups.length = 0;
  15297. };
  15298. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  15299. if (!this._renderingGroups[renderingGroupId]) {
  15300. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  15301. }
  15302. };
  15303. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  15304. var renderingGroupId = spriteManager.renderingGroupId || 0;
  15305. this._prepareRenderingGroup(renderingGroupId);
  15306. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  15307. };
  15308. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  15309. var renderingGroupId = particleSystem.renderingGroupId || 0;
  15310. this._prepareRenderingGroup(renderingGroupId);
  15311. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  15312. };
  15313. RenderingManager.prototype.dispatch = function (subMesh) {
  15314. var mesh = subMesh.getMesh();
  15315. var renderingGroupId = mesh.renderingGroupId || 0;
  15316. this._prepareRenderingGroup(renderingGroupId);
  15317. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  15318. };
  15319. /**
  15320. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  15321. * This allowed control for front to back rendering or reversly depending of the special needs.
  15322. *
  15323. * @param renderingGroupId The rendering group id corresponding to its index
  15324. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  15325. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  15326. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  15327. */
  15328. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15329. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15330. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15331. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15332. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  15333. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  15334. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  15335. if (this._renderingGroups[renderingGroupId]) {
  15336. var group = this._renderingGroups[renderingGroupId];
  15337. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  15338. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  15339. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  15340. }
  15341. };
  15342. /**
  15343. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  15344. *
  15345. * @param renderingGroupId The rendering group id corresponding to its index
  15346. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  15347. * @param depth Automatically clears depth between groups if true and autoClear is true.
  15348. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  15349. */
  15350. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  15351. if (depth === void 0) { depth = true; }
  15352. if (stencil === void 0) { stencil = true; }
  15353. this._autoClearDepthStencil[renderingGroupId] = {
  15354. autoClear: autoClearDepthStencil,
  15355. depth: depth,
  15356. stencil: stencil
  15357. };
  15358. };
  15359. return RenderingManager;
  15360. }());
  15361. /**
  15362. * The max id used for rendering groups (not included)
  15363. */
  15364. RenderingManager.MAX_RENDERINGGROUPS = 4;
  15365. /**
  15366. * The min id used for rendering groups (included)
  15367. */
  15368. RenderingManager.MIN_RENDERINGGROUPS = 0;
  15369. /**
  15370. * Used to globally prevent autoclearing scenes.
  15371. */
  15372. RenderingManager.AUTOCLEAR = true;
  15373. BABYLON.RenderingManager = RenderingManager;
  15374. })(BABYLON || (BABYLON = {}));
  15375. //# sourceMappingURL=babylon.renderingManager.js.map
  15376. var BABYLON;
  15377. (function (BABYLON) {
  15378. var RenderingGroup = (function () {
  15379. /**
  15380. * Creates a new rendering group.
  15381. * @param index The rendering group index
  15382. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  15383. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  15384. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  15385. */
  15386. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15387. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15388. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15389. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15390. this.index = index;
  15391. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  15392. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  15393. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  15394. this._particleSystems = new BABYLON.SmartArray(256);
  15395. this._spriteManagers = new BABYLON.SmartArray(256);
  15396. this._edgesRenderers = new BABYLON.SmartArray(16);
  15397. this._scene = scene;
  15398. this.opaqueSortCompareFn = opaqueSortCompareFn;
  15399. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  15400. this.transparentSortCompareFn = transparentSortCompareFn;
  15401. }
  15402. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  15403. /**
  15404. * Set the opaque sort comparison function.
  15405. * If null the sub meshes will be render in the order they were created
  15406. */
  15407. set: function (value) {
  15408. this._opaqueSortCompareFn = value;
  15409. if (value) {
  15410. this._renderOpaque = this.renderOpaqueSorted;
  15411. }
  15412. else {
  15413. this._renderOpaque = RenderingGroup.renderUnsorted;
  15414. }
  15415. },
  15416. enumerable: true,
  15417. configurable: true
  15418. });
  15419. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  15420. /**
  15421. * Set the alpha test sort comparison function.
  15422. * If null the sub meshes will be render in the order they were created
  15423. */
  15424. set: function (value) {
  15425. this._alphaTestSortCompareFn = value;
  15426. if (value) {
  15427. this._renderAlphaTest = this.renderAlphaTestSorted;
  15428. }
  15429. else {
  15430. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  15431. }
  15432. },
  15433. enumerable: true,
  15434. configurable: true
  15435. });
  15436. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  15437. /**
  15438. * Set the transparent sort comparison function.
  15439. * If null the sub meshes will be render in the order they were created
  15440. */
  15441. set: function (value) {
  15442. if (value) {
  15443. this._transparentSortCompareFn = value;
  15444. }
  15445. else {
  15446. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  15447. }
  15448. this._renderTransparent = this.renderTransparentSorted;
  15449. },
  15450. enumerable: true,
  15451. configurable: true
  15452. });
  15453. /**
  15454. * Render all the sub meshes contained in the group.
  15455. * @param customRenderFunction Used to override the default render behaviour of the group.
  15456. * @returns true if rendered some submeshes.
  15457. */
  15458. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  15459. if (customRenderFunction) {
  15460. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  15461. return;
  15462. }
  15463. var engine = this._scene.getEngine();
  15464. // Opaque
  15465. if (this._opaqueSubMeshes.length !== 0) {
  15466. this._renderOpaque(this._opaqueSubMeshes);
  15467. }
  15468. // Alpha test
  15469. if (this._alphaTestSubMeshes.length !== 0) {
  15470. engine.setAlphaTesting(true);
  15471. this._renderAlphaTest(this._alphaTestSubMeshes);
  15472. engine.setAlphaTesting(false);
  15473. }
  15474. var stencilState = engine.getStencilBuffer();
  15475. engine.setStencilBuffer(false);
  15476. // Sprites
  15477. if (renderSprites) {
  15478. this._renderSprites();
  15479. }
  15480. // Particles
  15481. if (renderParticles) {
  15482. this._renderParticles(activeMeshes);
  15483. }
  15484. if (this.onBeforeTransparentRendering) {
  15485. this.onBeforeTransparentRendering();
  15486. }
  15487. // Transparent
  15488. if (this._transparentSubMeshes.length !== 0) {
  15489. this._renderTransparent(this._transparentSubMeshes);
  15490. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15491. }
  15492. // Set back stencil to false in case it changes before the edge renderer.
  15493. engine.setStencilBuffer(false);
  15494. // Edges
  15495. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  15496. this._edgesRenderers.data[edgesRendererIndex].render();
  15497. }
  15498. // Restore Stencil state.
  15499. engine.setStencilBuffer(stencilState);
  15500. };
  15501. /**
  15502. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  15503. * @param subMeshes The submeshes to render
  15504. */
  15505. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  15506. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15507. };
  15508. /**
  15509. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  15510. * @param subMeshes The submeshes to render
  15511. */
  15512. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  15513. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15514. };
  15515. /**
  15516. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  15517. * @param subMeshes The submeshes to render
  15518. */
  15519. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  15520. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  15521. };
  15522. /**
  15523. * Renders the submeshes in a specified order.
  15524. * @param subMeshes The submeshes to sort before render
  15525. * @param sortCompareFn The comparison function use to sort
  15526. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  15527. * @param transparent Specifies to activate blending if true
  15528. */
  15529. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  15530. var subIndex = 0;
  15531. var subMesh;
  15532. for (; subIndex < subMeshes.length; subIndex++) {
  15533. subMesh = subMeshes.data[subIndex];
  15534. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  15535. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  15536. }
  15537. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  15538. sortedArray.sort(sortCompareFn);
  15539. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  15540. subMesh = sortedArray[subIndex];
  15541. subMesh.render(transparent);
  15542. }
  15543. };
  15544. /**
  15545. * Renders the submeshes in the order they were dispatched (no sort applied).
  15546. * @param subMeshes The submeshes to render
  15547. */
  15548. RenderingGroup.renderUnsorted = function (subMeshes) {
  15549. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  15550. var submesh = subMeshes.data[subIndex];
  15551. submesh.render(false);
  15552. }
  15553. };
  15554. /**
  15555. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15556. * are rendered back to front if in the same alpha index.
  15557. *
  15558. * @param a The first submesh
  15559. * @param b The second submesh
  15560. * @returns The result of the comparison
  15561. */
  15562. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  15563. // Alpha index first
  15564. if (a._alphaIndex > b._alphaIndex) {
  15565. return 1;
  15566. }
  15567. if (a._alphaIndex < b._alphaIndex) {
  15568. return -1;
  15569. }
  15570. // Then distance to camera
  15571. return RenderingGroup.backToFrontSortCompare(a, b);
  15572. };
  15573. /**
  15574. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15575. * are rendered back to front.
  15576. *
  15577. * @param a The first submesh
  15578. * @param b The second submesh
  15579. * @returns The result of the comparison
  15580. */
  15581. RenderingGroup.backToFrontSortCompare = function (a, b) {
  15582. // Then distance to camera
  15583. if (a._distanceToCamera < b._distanceToCamera) {
  15584. return 1;
  15585. }
  15586. if (a._distanceToCamera > b._distanceToCamera) {
  15587. return -1;
  15588. }
  15589. return 0;
  15590. };
  15591. /**
  15592. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15593. * are rendered front to back (prevent overdraw).
  15594. *
  15595. * @param a The first submesh
  15596. * @param b The second submesh
  15597. * @returns The result of the comparison
  15598. */
  15599. RenderingGroup.frontToBackSortCompare = function (a, b) {
  15600. // Then distance to camera
  15601. if (a._distanceToCamera < b._distanceToCamera) {
  15602. return -1;
  15603. }
  15604. if (a._distanceToCamera > b._distanceToCamera) {
  15605. return 1;
  15606. }
  15607. return 0;
  15608. };
  15609. /**
  15610. * Resets the different lists of submeshes to prepare a new frame.
  15611. */
  15612. RenderingGroup.prototype.prepare = function () {
  15613. this._opaqueSubMeshes.reset();
  15614. this._transparentSubMeshes.reset();
  15615. this._alphaTestSubMeshes.reset();
  15616. this._particleSystems.reset();
  15617. this._spriteManagers.reset();
  15618. this._edgesRenderers.reset();
  15619. };
  15620. RenderingGroup.prototype.dispose = function () {
  15621. this._opaqueSubMeshes.dispose();
  15622. this._transparentSubMeshes.dispose();
  15623. this._alphaTestSubMeshes.dispose();
  15624. this._particleSystems.dispose();
  15625. this._spriteManagers.dispose();
  15626. this._edgesRenderers.dispose();
  15627. };
  15628. /**
  15629. * Inserts the submesh in its correct queue depending on its material.
  15630. * @param subMesh The submesh to dispatch
  15631. */
  15632. RenderingGroup.prototype.dispatch = function (subMesh) {
  15633. var material = subMesh.getMaterial();
  15634. var mesh = subMesh.getMesh();
  15635. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  15636. this._transparentSubMeshes.push(subMesh);
  15637. }
  15638. else if (material.needAlphaTesting()) {
  15639. this._alphaTestSubMeshes.push(subMesh);
  15640. }
  15641. else {
  15642. this._opaqueSubMeshes.push(subMesh); // Opaque
  15643. }
  15644. if (mesh._edgesRenderer) {
  15645. this._edgesRenderers.push(mesh._edgesRenderer);
  15646. }
  15647. };
  15648. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  15649. this._spriteManagers.push(spriteManager);
  15650. };
  15651. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  15652. this._particleSystems.push(particleSystem);
  15653. };
  15654. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  15655. if (this._particleSystems.length === 0) {
  15656. return;
  15657. }
  15658. // Particles
  15659. var activeCamera = this._scene.activeCamera;
  15660. this._scene._particlesDuration.beginMonitoring();
  15661. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  15662. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  15663. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  15664. continue;
  15665. }
  15666. var emitter = particleSystem.emitter;
  15667. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  15668. this._scene._activeParticles.addCount(particleSystem.render(), false);
  15669. }
  15670. }
  15671. this._scene._particlesDuration.endMonitoring(false);
  15672. };
  15673. RenderingGroup.prototype._renderSprites = function () {
  15674. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  15675. return;
  15676. }
  15677. // Sprites
  15678. var activeCamera = this._scene.activeCamera;
  15679. this._scene._spritesDuration.beginMonitoring();
  15680. for (var id = 0; id < this._spriteManagers.length; id++) {
  15681. var spriteManager = this._spriteManagers.data[id];
  15682. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  15683. spriteManager.render();
  15684. }
  15685. }
  15686. this._scene._spritesDuration.endMonitoring(false);
  15687. };
  15688. return RenderingGroup;
  15689. }());
  15690. BABYLON.RenderingGroup = RenderingGroup;
  15691. })(BABYLON || (BABYLON = {}));
  15692. //# sourceMappingURL=babylon.renderingGroup.js.map
  15693. var BABYLON;
  15694. (function (BABYLON) {
  15695. var ClickInfo = (function () {
  15696. function ClickInfo() {
  15697. this._singleClick = false;
  15698. this._doubleClick = false;
  15699. this._hasSwiped = false;
  15700. this._ignore = false;
  15701. }
  15702. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  15703. get: function () {
  15704. return this._singleClick;
  15705. },
  15706. set: function (b) {
  15707. this._singleClick = b;
  15708. },
  15709. enumerable: true,
  15710. configurable: true
  15711. });
  15712. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  15713. get: function () {
  15714. return this._doubleClick;
  15715. },
  15716. set: function (b) {
  15717. this._doubleClick = b;
  15718. },
  15719. enumerable: true,
  15720. configurable: true
  15721. });
  15722. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  15723. get: function () {
  15724. return this._hasSwiped;
  15725. },
  15726. set: function (b) {
  15727. this._hasSwiped = b;
  15728. },
  15729. enumerable: true,
  15730. configurable: true
  15731. });
  15732. Object.defineProperty(ClickInfo.prototype, "ignore", {
  15733. get: function () {
  15734. return this._ignore;
  15735. },
  15736. set: function (b) {
  15737. this._ignore = b;
  15738. },
  15739. enumerable: true,
  15740. configurable: true
  15741. });
  15742. return ClickInfo;
  15743. }());
  15744. var PointerEventTypes = (function () {
  15745. function PointerEventTypes() {
  15746. }
  15747. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  15748. get: function () {
  15749. return PointerEventTypes._POINTERDOWN;
  15750. },
  15751. enumerable: true,
  15752. configurable: true
  15753. });
  15754. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  15755. get: function () {
  15756. return PointerEventTypes._POINTERUP;
  15757. },
  15758. enumerable: true,
  15759. configurable: true
  15760. });
  15761. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  15762. get: function () {
  15763. return PointerEventTypes._POINTERMOVE;
  15764. },
  15765. enumerable: true,
  15766. configurable: true
  15767. });
  15768. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  15769. get: function () {
  15770. return PointerEventTypes._POINTERWHEEL;
  15771. },
  15772. enumerable: true,
  15773. configurable: true
  15774. });
  15775. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  15776. get: function () {
  15777. return PointerEventTypes._POINTERPICK;
  15778. },
  15779. enumerable: true,
  15780. configurable: true
  15781. });
  15782. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  15783. get: function () {
  15784. return PointerEventTypes._POINTERTAP;
  15785. },
  15786. enumerable: true,
  15787. configurable: true
  15788. });
  15789. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  15790. get: function () {
  15791. return PointerEventTypes._POINTERDOUBLETAP;
  15792. },
  15793. enumerable: true,
  15794. configurable: true
  15795. });
  15796. return PointerEventTypes;
  15797. }());
  15798. PointerEventTypes._POINTERDOWN = 0x01;
  15799. PointerEventTypes._POINTERUP = 0x02;
  15800. PointerEventTypes._POINTERMOVE = 0x04;
  15801. PointerEventTypes._POINTERWHEEL = 0x08;
  15802. PointerEventTypes._POINTERPICK = 0x10;
  15803. PointerEventTypes._POINTERTAP = 0x20;
  15804. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  15805. BABYLON.PointerEventTypes = PointerEventTypes;
  15806. var PointerInfoBase = (function () {
  15807. function PointerInfoBase(type, event) {
  15808. this.type = type;
  15809. this.event = event;
  15810. }
  15811. return PointerInfoBase;
  15812. }());
  15813. BABYLON.PointerInfoBase = PointerInfoBase;
  15814. /**
  15815. * This class is used to store pointer related info for the onPrePointerObservable event.
  15816. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  15817. */
  15818. var PointerInfoPre = (function (_super) {
  15819. __extends(PointerInfoPre, _super);
  15820. function PointerInfoPre(type, event, localX, localY) {
  15821. var _this = _super.call(this, type, event) || this;
  15822. _this.skipOnPointerObservable = false;
  15823. _this.localPosition = new BABYLON.Vector2(localX, localY);
  15824. return _this;
  15825. }
  15826. return PointerInfoPre;
  15827. }(PointerInfoBase));
  15828. BABYLON.PointerInfoPre = PointerInfoPre;
  15829. /**
  15830. * This type contains all the data related to a pointer event in Babylon.js.
  15831. * 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.
  15832. */
  15833. var PointerInfo = (function (_super) {
  15834. __extends(PointerInfo, _super);
  15835. function PointerInfo(type, event, pickInfo) {
  15836. var _this = _super.call(this, type, event) || this;
  15837. _this.pickInfo = pickInfo;
  15838. return _this;
  15839. }
  15840. return PointerInfo;
  15841. }(PointerInfoBase));
  15842. BABYLON.PointerInfo = PointerInfo;
  15843. /**
  15844. * This class is used by the onRenderingGroupObservable
  15845. */
  15846. var RenderingGroupInfo = (function () {
  15847. function RenderingGroupInfo() {
  15848. }
  15849. return RenderingGroupInfo;
  15850. }());
  15851. /**
  15852. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  15853. * This stage will be fired no matter what
  15854. */
  15855. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  15856. /**
  15857. * Called before opaque object are rendered.
  15858. * This stage will be fired only if there's 3D Opaque content to render
  15859. */
  15860. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  15861. /**
  15862. * Called after the opaque objects are rendered and before the transparent ones
  15863. * This stage will be fired only if there's 3D transparent content to render
  15864. */
  15865. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  15866. /**
  15867. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  15868. * This stage will be fired no matter what
  15869. */
  15870. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  15871. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  15872. /**
  15873. * Represents a scene to be rendered by the engine.
  15874. * @see http://doc.babylonjs.com/page.php?p=21911
  15875. */
  15876. var Scene = (function () {
  15877. /**
  15878. * @constructor
  15879. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  15880. */
  15881. function Scene(engine) {
  15882. // Members
  15883. this.autoClear = true;
  15884. this.autoClearDepthAndStencil = true;
  15885. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  15886. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  15887. this.forceWireframe = false;
  15888. this._forcePointsCloud = false;
  15889. this.forceShowBoundingBoxes = false;
  15890. this.animationsEnabled = true;
  15891. this.constantlyUpdateMeshUnderPointer = false;
  15892. this.hoverCursor = "pointer";
  15893. this.defaultCursor = "";
  15894. // Metadata
  15895. this.metadata = null;
  15896. // Events
  15897. /**
  15898. * An event triggered when the scene is disposed.
  15899. * @type {BABYLON.Observable}
  15900. */
  15901. this.onDisposeObservable = new BABYLON.Observable();
  15902. /**
  15903. * An event triggered before rendering the scene
  15904. * @type {BABYLON.Observable}
  15905. */
  15906. this.onBeforeRenderObservable = new BABYLON.Observable();
  15907. /**
  15908. * An event triggered after rendering the scene
  15909. * @type {BABYLON.Observable}
  15910. */
  15911. this.onAfterRenderObservable = new BABYLON.Observable();
  15912. /**
  15913. * An event triggered when the scene is ready
  15914. * @type {BABYLON.Observable}
  15915. */
  15916. this.onReadyObservable = new BABYLON.Observable();
  15917. /**
  15918. * An event triggered before rendering a camera
  15919. * @type {BABYLON.Observable}
  15920. */
  15921. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  15922. /**
  15923. * An event triggered after rendering a camera
  15924. * @type {BABYLON.Observable}
  15925. */
  15926. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  15927. /**
  15928. * An event triggered when a camera is created
  15929. * @type {BABYLON.Observable}
  15930. */
  15931. this.onNewCameraAddedObservable = new BABYLON.Observable();
  15932. /**
  15933. * An event triggered when a camera is removed
  15934. * @type {BABYLON.Observable}
  15935. */
  15936. this.onCameraRemovedObservable = new BABYLON.Observable();
  15937. /**
  15938. * An event triggered when a light is created
  15939. * @type {BABYLON.Observable}
  15940. */
  15941. this.onNewLightAddedObservable = new BABYLON.Observable();
  15942. /**
  15943. * An event triggered when a light is removed
  15944. * @type {BABYLON.Observable}
  15945. */
  15946. this.onLightRemovedObservable = new BABYLON.Observable();
  15947. /**
  15948. * An event triggered when a geometry is created
  15949. * @type {BABYLON.Observable}
  15950. */
  15951. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  15952. /**
  15953. * An event triggered when a geometry is removed
  15954. * @type {BABYLON.Observable}
  15955. */
  15956. this.onGeometryRemovedObservable = new BABYLON.Observable();
  15957. /**
  15958. * An event triggered when a mesh is created
  15959. * @type {BABYLON.Observable}
  15960. */
  15961. this.onNewMeshAddedObservable = new BABYLON.Observable();
  15962. /**
  15963. * An event triggered when a mesh is removed
  15964. * @type {BABYLON.Observable}
  15965. */
  15966. this.onMeshRemovedObservable = new BABYLON.Observable();
  15967. /**
  15968. * An event triggered before calculating deterministic simulation step
  15969. * @type {BABYLON.Observable}
  15970. */
  15971. this.onBeforeStepObservable = new BABYLON.Observable();
  15972. /**
  15973. * An event triggered after calculating deterministic simulation step
  15974. * @type {BABYLON.Observable}
  15975. */
  15976. this.onAfterStepObservable = new BABYLON.Observable();
  15977. /**
  15978. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  15979. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  15980. * 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)
  15981. */
  15982. this.onRenderingGroupObservable = new BABYLON.Observable();
  15983. // Animations
  15984. this.animations = [];
  15985. /**
  15986. * This observable event is triggered when any mouse event registered during Scene.attach() is called BEFORE the 3D engine to process anything (mesh/sprite picking for instance).
  15987. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  15988. */
  15989. this.onPrePointerObservable = new BABYLON.Observable();
  15990. /**
  15991. * Observable event triggered each time an input event is received from the rendering canvas
  15992. */
  15993. this.onPointerObservable = new BABYLON.Observable();
  15994. this._meshPickProceed = false;
  15995. this._previousHasSwiped = false;
  15996. this._currentPickResult = null;
  15997. this._previousPickResult = null;
  15998. this._isButtonPressed = false;
  15999. this._doubleClickOccured = false;
  16000. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  16001. this.cameraToUseForPointers = null;
  16002. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  16003. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  16004. this._startingPointerTime = 0;
  16005. this._previousStartingPointerTime = 0;
  16006. // Deterministic lockstep
  16007. this._timeAccumulator = 0;
  16008. this._currentStepId = 0;
  16009. this._currentInternalStep = 0;
  16010. // Coordinate system
  16011. /**
  16012. * use right-handed coordinate system on this scene.
  16013. * @type {boolean}
  16014. */
  16015. this._useRightHandedSystem = false;
  16016. // Fog
  16017. this._fogEnabled = true;
  16018. this._fogMode = Scene.FOGMODE_NONE;
  16019. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16020. this.fogDensity = 0.1;
  16021. this.fogStart = 0;
  16022. this.fogEnd = 1000.0;
  16023. // Lights
  16024. /**
  16025. * is shadow enabled on this scene.
  16026. * @type {boolean}
  16027. */
  16028. this._shadowsEnabled = true;
  16029. /**
  16030. * is light enabled on this scene.
  16031. * @type {boolean}
  16032. */
  16033. this._lightsEnabled = true;
  16034. /**
  16035. * All of the lights added to this scene.
  16036. * @see BABYLON.Light
  16037. * @type {BABYLON.Light[]}
  16038. */
  16039. this.lights = new Array();
  16040. // Cameras
  16041. /** All of the cameras added to this scene. */
  16042. this.cameras = new Array();
  16043. /** All of the active cameras added to this scene. */
  16044. this.activeCameras = new Array();
  16045. // Meshes
  16046. /**
  16047. * All of the (abstract) meshes added to this scene.
  16048. * @see BABYLON.AbstractMesh
  16049. * @type {BABYLON.AbstractMesh[]}
  16050. */
  16051. this.meshes = new Array();
  16052. // Geometries
  16053. this._geometries = new Array();
  16054. this.materials = new Array();
  16055. this.multiMaterials = new Array();
  16056. // Textures
  16057. this._texturesEnabled = true;
  16058. this.textures = new Array();
  16059. // Particles
  16060. this.particlesEnabled = true;
  16061. this.particleSystems = new Array();
  16062. // Sprites
  16063. this.spritesEnabled = true;
  16064. this.spriteManagers = new Array();
  16065. // Layers
  16066. this.layers = new Array();
  16067. this.highlightLayers = new Array();
  16068. // Skeletons
  16069. this._skeletonsEnabled = true;
  16070. this.skeletons = new Array();
  16071. // Morph targets
  16072. this.morphTargetManagers = new Array();
  16073. // Lens flares
  16074. this.lensFlaresEnabled = true;
  16075. this.lensFlareSystems = new Array();
  16076. // Collisions
  16077. this.collisionsEnabled = true;
  16078. /** Defines the gravity applied to this scene */
  16079. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  16080. // Postprocesses
  16081. this.postProcessesEnabled = true;
  16082. // Customs render targets
  16083. this.renderTargetsEnabled = true;
  16084. this.dumpNextRenderTargets = false;
  16085. this.customRenderTargets = new Array();
  16086. // Imported meshes
  16087. this.importedMeshesFiles = new Array();
  16088. // Probes
  16089. this.probesEnabled = true;
  16090. this.reflectionProbes = new Array();
  16091. this._actionManagers = new Array();
  16092. this._meshesForIntersections = new BABYLON.SmartArray(256);
  16093. // Procedural textures
  16094. this.proceduralTexturesEnabled = true;
  16095. this._proceduralTextures = new Array();
  16096. this.soundTracks = new Array();
  16097. this._audioEnabled = true;
  16098. this._headphone = false;
  16099. // Performance counters
  16100. this._totalMeshesCounter = new BABYLON.PerfCounter();
  16101. this._totalLightsCounter = new BABYLON.PerfCounter();
  16102. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  16103. this._totalTexturesCounter = new BABYLON.PerfCounter();
  16104. this._totalVertices = new BABYLON.PerfCounter();
  16105. this._activeIndices = new BABYLON.PerfCounter();
  16106. this._activeParticles = new BABYLON.PerfCounter();
  16107. this._lastFrameDuration = new BABYLON.PerfCounter();
  16108. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  16109. this._renderTargetsDuration = new BABYLON.PerfCounter();
  16110. this._particlesDuration = new BABYLON.PerfCounter();
  16111. this._renderDuration = new BABYLON.PerfCounter();
  16112. this._spritesDuration = new BABYLON.PerfCounter();
  16113. this._activeBones = new BABYLON.PerfCounter();
  16114. this._animationTime = 0;
  16115. this.animationTimeScale = 1;
  16116. this._renderId = 0;
  16117. this._executeWhenReadyTimeoutId = -1;
  16118. this._intermediateRendering = false;
  16119. this._viewUpdateFlag = -1;
  16120. this._projectionUpdateFlag = -1;
  16121. this._toBeDisposed = new BABYLON.SmartArray(256);
  16122. this._pendingData = []; //ANY
  16123. this._activeMeshes = new BABYLON.SmartArray(256);
  16124. this._processedMaterials = new BABYLON.SmartArray(256);
  16125. this._renderTargets = new BABYLON.SmartArray(256);
  16126. this._activeParticleSystems = new BABYLON.SmartArray(256);
  16127. this._activeSkeletons = new BABYLON.SmartArray(32);
  16128. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  16129. this._activeAnimatables = new Array();
  16130. this._transformMatrix = BABYLON.Matrix.Zero();
  16131. this.requireLightSorting = false;
  16132. this._uniqueIdCounter = 0;
  16133. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  16134. this._engine.scenes.push(this);
  16135. this._uid = null;
  16136. this._renderingManager = new BABYLON.RenderingManager(this);
  16137. this.postProcessManager = new BABYLON.PostProcessManager(this);
  16138. if (BABYLON.OutlineRenderer) {
  16139. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  16140. }
  16141. this.attachControl();
  16142. if (BABYLON.SoundTrack) {
  16143. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  16144. }
  16145. //simplification queue
  16146. if (BABYLON.SimplificationQueue) {
  16147. this.simplificationQueue = new BABYLON.SimplificationQueue();
  16148. }
  16149. //collision coordinator initialization. For now legacy per default.
  16150. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  16151. // Uniform Buffer
  16152. this._createUbo();
  16153. // Default Image processing definition.
  16154. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  16155. }
  16156. Object.defineProperty(Scene, "FOGMODE_NONE", {
  16157. /** The fog is deactivated */
  16158. get: function () {
  16159. return Scene._FOGMODE_NONE;
  16160. },
  16161. enumerable: true,
  16162. configurable: true
  16163. });
  16164. Object.defineProperty(Scene, "FOGMODE_EXP", {
  16165. /** The fog density is following an exponential function */
  16166. get: function () {
  16167. return Scene._FOGMODE_EXP;
  16168. },
  16169. enumerable: true,
  16170. configurable: true
  16171. });
  16172. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  16173. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  16174. get: function () {
  16175. return Scene._FOGMODE_EXP2;
  16176. },
  16177. enumerable: true,
  16178. configurable: true
  16179. });
  16180. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  16181. /** The fog density is following a linear function. */
  16182. get: function () {
  16183. return Scene._FOGMODE_LINEAR;
  16184. },
  16185. enumerable: true,
  16186. configurable: true
  16187. });
  16188. Object.defineProperty(Scene.prototype, "environmentTexture", {
  16189. /**
  16190. * Texture used in all pbr material as the reflection texture.
  16191. * As in the majority of the scene they are the same (exception for multi room and so on),
  16192. * this is easier to reference from here than from all the materials.
  16193. */
  16194. get: function () {
  16195. return this._environmentTexture;
  16196. },
  16197. /**
  16198. * Texture used in all pbr material as the reflection texture.
  16199. * As in the majority of the scene they are the same (exception for multi room and so on),
  16200. * this is easier to set here than in all the materials.
  16201. */
  16202. set: function (value) {
  16203. this._environmentTexture = value;
  16204. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  16205. },
  16206. enumerable: true,
  16207. configurable: true
  16208. });
  16209. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  16210. /**
  16211. * Default image processing configuration used either in the rendering
  16212. * Forward main pass or through the imageProcessingPostProcess if present.
  16213. * As in the majority of the scene they are the same (exception for multi camera),
  16214. * this is easier to reference from here than from all the materials and post process.
  16215. *
  16216. * No setter as we it is a shared configuration, you can set the values instead.
  16217. */
  16218. get: function () {
  16219. return this._imageProcessingConfiguration;
  16220. },
  16221. enumerable: true,
  16222. configurable: true
  16223. });
  16224. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  16225. get: function () {
  16226. return this._forcePointsCloud;
  16227. },
  16228. set: function (value) {
  16229. if (this._forcePointsCloud === value) {
  16230. return;
  16231. }
  16232. this._forcePointsCloud = value;
  16233. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16234. },
  16235. enumerable: true,
  16236. configurable: true
  16237. });
  16238. Object.defineProperty(Scene.prototype, "onDispose", {
  16239. /** A function to be executed when this scene is disposed. */
  16240. set: function (callback) {
  16241. if (this._onDisposeObserver) {
  16242. this.onDisposeObservable.remove(this._onDisposeObserver);
  16243. }
  16244. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  16245. },
  16246. enumerable: true,
  16247. configurable: true
  16248. });
  16249. Object.defineProperty(Scene.prototype, "beforeRender", {
  16250. /** A function to be executed before rendering this scene */
  16251. set: function (callback) {
  16252. if (this._onBeforeRenderObserver) {
  16253. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  16254. }
  16255. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  16256. },
  16257. enumerable: true,
  16258. configurable: true
  16259. });
  16260. Object.defineProperty(Scene.prototype, "afterRender", {
  16261. /** A function to be executed after rendering this scene */
  16262. set: function (callback) {
  16263. if (this._onAfterRenderObserver) {
  16264. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  16265. }
  16266. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  16267. },
  16268. enumerable: true,
  16269. configurable: true
  16270. });
  16271. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  16272. set: function (callback) {
  16273. if (this._onBeforeCameraRenderObserver) {
  16274. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  16275. }
  16276. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  16277. },
  16278. enumerable: true,
  16279. configurable: true
  16280. });
  16281. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  16282. set: function (callback) {
  16283. if (this._onAfterCameraRenderObserver) {
  16284. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  16285. }
  16286. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  16287. },
  16288. enumerable: true,
  16289. configurable: true
  16290. });
  16291. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  16292. get: function () {
  16293. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  16294. },
  16295. enumerable: true,
  16296. configurable: true
  16297. });
  16298. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  16299. get: function () {
  16300. return this._useRightHandedSystem;
  16301. },
  16302. set: function (value) {
  16303. if (this._useRightHandedSystem === value) {
  16304. return;
  16305. }
  16306. this._useRightHandedSystem = value;
  16307. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16308. },
  16309. enumerable: true,
  16310. configurable: true
  16311. });
  16312. Scene.prototype.setStepId = function (newStepId) {
  16313. this._currentStepId = newStepId;
  16314. };
  16315. ;
  16316. Scene.prototype.getStepId = function () {
  16317. return this._currentStepId;
  16318. };
  16319. ;
  16320. Scene.prototype.getInternalStep = function () {
  16321. return this._currentInternalStep;
  16322. };
  16323. ;
  16324. Object.defineProperty(Scene.prototype, "fogEnabled", {
  16325. get: function () {
  16326. return this._fogEnabled;
  16327. },
  16328. /**
  16329. * is fog enabled on this scene.
  16330. */
  16331. set: function (value) {
  16332. if (this._fogEnabled === value) {
  16333. return;
  16334. }
  16335. this._fogEnabled = value;
  16336. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16337. },
  16338. enumerable: true,
  16339. configurable: true
  16340. });
  16341. Object.defineProperty(Scene.prototype, "fogMode", {
  16342. get: function () {
  16343. return this._fogMode;
  16344. },
  16345. set: function (value) {
  16346. if (this._fogMode === value) {
  16347. return;
  16348. }
  16349. this._fogMode = value;
  16350. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16351. },
  16352. enumerable: true,
  16353. configurable: true
  16354. });
  16355. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  16356. get: function () {
  16357. return this._shadowsEnabled;
  16358. },
  16359. set: function (value) {
  16360. if (this._shadowsEnabled === value) {
  16361. return;
  16362. }
  16363. this._shadowsEnabled = value;
  16364. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  16365. },
  16366. enumerable: true,
  16367. configurable: true
  16368. });
  16369. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  16370. get: function () {
  16371. return this._lightsEnabled;
  16372. },
  16373. set: function (value) {
  16374. if (this._lightsEnabled === value) {
  16375. return;
  16376. }
  16377. this._lightsEnabled = value;
  16378. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  16379. },
  16380. enumerable: true,
  16381. configurable: true
  16382. });
  16383. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  16384. /** The default material used on meshes when no material is affected */
  16385. get: function () {
  16386. if (!this._defaultMaterial) {
  16387. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  16388. }
  16389. return this._defaultMaterial;
  16390. },
  16391. /** The default material used on meshes when no material is affected */
  16392. set: function (value) {
  16393. this._defaultMaterial = value;
  16394. },
  16395. enumerable: true,
  16396. configurable: true
  16397. });
  16398. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  16399. get: function () {
  16400. return this._texturesEnabled;
  16401. },
  16402. set: function (value) {
  16403. if (this._texturesEnabled === value) {
  16404. return;
  16405. }
  16406. this._texturesEnabled = value;
  16407. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  16408. },
  16409. enumerable: true,
  16410. configurable: true
  16411. });
  16412. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  16413. get: function () {
  16414. return this._skeletonsEnabled;
  16415. },
  16416. set: function (value) {
  16417. if (this._skeletonsEnabled === value) {
  16418. return;
  16419. }
  16420. this._skeletonsEnabled = value;
  16421. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  16422. },
  16423. enumerable: true,
  16424. configurable: true
  16425. });
  16426. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  16427. get: function () {
  16428. if (!this._postProcessRenderPipelineManager) {
  16429. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  16430. }
  16431. return this._postProcessRenderPipelineManager;
  16432. },
  16433. enumerable: true,
  16434. configurable: true
  16435. });
  16436. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  16437. get: function () {
  16438. return this._frustumPlanes;
  16439. },
  16440. enumerable: true,
  16441. configurable: true
  16442. });
  16443. Object.defineProperty(Scene.prototype, "debugLayer", {
  16444. // Properties
  16445. get: function () {
  16446. if (!this._debugLayer) {
  16447. this._debugLayer = new BABYLON.DebugLayer(this);
  16448. }
  16449. return this._debugLayer;
  16450. },
  16451. enumerable: true,
  16452. configurable: true
  16453. });
  16454. Object.defineProperty(Scene.prototype, "workerCollisions", {
  16455. get: function () {
  16456. return this._workerCollisions;
  16457. },
  16458. set: function (enabled) {
  16459. if (!BABYLON.CollisionCoordinatorLegacy) {
  16460. return;
  16461. }
  16462. enabled = (enabled && !!Worker);
  16463. this._workerCollisions = enabled;
  16464. if (this.collisionCoordinator) {
  16465. this.collisionCoordinator.destroy();
  16466. }
  16467. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  16468. this.collisionCoordinator.init(this);
  16469. },
  16470. enumerable: true,
  16471. configurable: true
  16472. });
  16473. Object.defineProperty(Scene.prototype, "selectionOctree", {
  16474. get: function () {
  16475. return this._selectionOctree;
  16476. },
  16477. enumerable: true,
  16478. configurable: true
  16479. });
  16480. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  16481. /**
  16482. * The mesh that is currently under the pointer.
  16483. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  16484. */
  16485. get: function () {
  16486. return this._pointerOverMesh;
  16487. },
  16488. enumerable: true,
  16489. configurable: true
  16490. });
  16491. Object.defineProperty(Scene.prototype, "pointerX", {
  16492. /**
  16493. * Current on-screen X position of the pointer
  16494. * @return {number} X position of the pointer
  16495. */
  16496. get: function () {
  16497. return this._pointerX;
  16498. },
  16499. enumerable: true,
  16500. configurable: true
  16501. });
  16502. Object.defineProperty(Scene.prototype, "pointerY", {
  16503. /**
  16504. * Current on-screen Y position of the pointer
  16505. * @return {number} Y position of the pointer
  16506. */
  16507. get: function () {
  16508. return this._pointerY;
  16509. },
  16510. enumerable: true,
  16511. configurable: true
  16512. });
  16513. Scene.prototype.getCachedMaterial = function () {
  16514. return this._cachedMaterial;
  16515. };
  16516. Scene.prototype.getCachedEffect = function () {
  16517. return this._cachedEffect;
  16518. };
  16519. Scene.prototype.getCachedVisibility = function () {
  16520. return this._cachedVisibility;
  16521. };
  16522. Scene.prototype.isCachedMaterialValid = function (material, effect, visibility) {
  16523. if (visibility === void 0) { visibility = 0; }
  16524. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  16525. };
  16526. Scene.prototype.getBoundingBoxRenderer = function () {
  16527. if (!this._boundingBoxRenderer) {
  16528. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  16529. }
  16530. return this._boundingBoxRenderer;
  16531. };
  16532. Scene.prototype.getOutlineRenderer = function () {
  16533. return this._outlineRenderer;
  16534. };
  16535. Scene.prototype.getEngine = function () {
  16536. return this._engine;
  16537. };
  16538. Scene.prototype.getTotalVertices = function () {
  16539. return this._totalVertices.current;
  16540. };
  16541. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  16542. get: function () {
  16543. return this._totalVertices;
  16544. },
  16545. enumerable: true,
  16546. configurable: true
  16547. });
  16548. Scene.prototype.getActiveIndices = function () {
  16549. return this._activeIndices.current;
  16550. };
  16551. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  16552. get: function () {
  16553. return this._activeIndices;
  16554. },
  16555. enumerable: true,
  16556. configurable: true
  16557. });
  16558. Scene.prototype.getActiveParticles = function () {
  16559. return this._activeParticles.current;
  16560. };
  16561. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  16562. get: function () {
  16563. return this._activeParticles;
  16564. },
  16565. enumerable: true,
  16566. configurable: true
  16567. });
  16568. Scene.prototype.getActiveBones = function () {
  16569. return this._activeBones.current;
  16570. };
  16571. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  16572. get: function () {
  16573. return this._activeBones;
  16574. },
  16575. enumerable: true,
  16576. configurable: true
  16577. });
  16578. // Stats
  16579. Scene.prototype.getLastFrameDuration = function () {
  16580. return this._lastFrameDuration.current;
  16581. };
  16582. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  16583. get: function () {
  16584. return this._lastFrameDuration;
  16585. },
  16586. enumerable: true,
  16587. configurable: true
  16588. });
  16589. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  16590. return this._evaluateActiveMeshesDuration.current;
  16591. };
  16592. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  16593. get: function () {
  16594. return this._evaluateActiveMeshesDuration;
  16595. },
  16596. enumerable: true,
  16597. configurable: true
  16598. });
  16599. Scene.prototype.getActiveMeshes = function () {
  16600. return this._activeMeshes;
  16601. };
  16602. Scene.prototype.getRenderTargetsDuration = function () {
  16603. return this._renderTargetsDuration.current;
  16604. };
  16605. Scene.prototype.getRenderDuration = function () {
  16606. return this._renderDuration.current;
  16607. };
  16608. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  16609. get: function () {
  16610. return this._renderDuration;
  16611. },
  16612. enumerable: true,
  16613. configurable: true
  16614. });
  16615. Scene.prototype.getParticlesDuration = function () {
  16616. return this._particlesDuration.current;
  16617. };
  16618. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  16619. get: function () {
  16620. return this._particlesDuration;
  16621. },
  16622. enumerable: true,
  16623. configurable: true
  16624. });
  16625. Scene.prototype.getSpritesDuration = function () {
  16626. return this._spritesDuration.current;
  16627. };
  16628. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  16629. get: function () {
  16630. return this._spritesDuration;
  16631. },
  16632. enumerable: true,
  16633. configurable: true
  16634. });
  16635. Scene.prototype.getAnimationRatio = function () {
  16636. return this._animationRatio;
  16637. };
  16638. Scene.prototype.getRenderId = function () {
  16639. return this._renderId;
  16640. };
  16641. Scene.prototype.incrementRenderId = function () {
  16642. this._renderId++;
  16643. };
  16644. Scene.prototype._updatePointerPosition = function (evt) {
  16645. var canvasRect = this._engine.getRenderingCanvasClientRect();
  16646. this._pointerX = evt.clientX - canvasRect.left;
  16647. this._pointerY = evt.clientY - canvasRect.top;
  16648. this._unTranslatedPointerX = this._pointerX;
  16649. this._unTranslatedPointerY = this._pointerY;
  16650. };
  16651. Scene.prototype._createUbo = function () {
  16652. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  16653. this._sceneUbo.addUniform("viewProjection", 16);
  16654. this._sceneUbo.addUniform("view", 16);
  16655. };
  16656. // Pointers handling
  16657. /**
  16658. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  16659. * @param attachUp defines if you want to attach events to pointerup
  16660. * @param attachDown defines if you want to attach events to pointerdown
  16661. * @param attachMove defines if you want to attach events to pointermove
  16662. */
  16663. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  16664. var _this = this;
  16665. if (attachUp === void 0) { attachUp = true; }
  16666. if (attachDown === void 0) { attachDown = true; }
  16667. if (attachMove === void 0) { attachMove = true; }
  16668. this._initActionManager = function (act, clickInfo) {
  16669. if (!_this._meshPickProceed) {
  16670. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16671. _this._currentPickResult = pickResult;
  16672. if (pickResult) {
  16673. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  16674. }
  16675. _this._meshPickProceed = true;
  16676. }
  16677. return act;
  16678. };
  16679. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  16680. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  16681. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  16682. btn !== _this._previousButtonPressed) {
  16683. _this._doubleClickOccured = false;
  16684. clickInfo.singleClick = true;
  16685. clickInfo.ignore = false;
  16686. cb(clickInfo, _this._currentPickResult);
  16687. }
  16688. };
  16689. this._initClickEvent = function (obs1, obs2, evt, cb) {
  16690. var clickInfo = new ClickInfo();
  16691. _this._currentPickResult = null;
  16692. var act;
  16693. var checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  16694. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  16695. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16696. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  16697. act = _this._initActionManager(act, clickInfo);
  16698. if (act)
  16699. checkPicking = act.hasPickTriggers;
  16700. }
  16701. if (checkPicking) {
  16702. var btn = evt.button;
  16703. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  16704. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  16705. if (!clickInfo.hasSwiped) {
  16706. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  16707. if (!checkSingleClickImmediately) {
  16708. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  16709. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16710. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16711. act = _this._initActionManager(act, clickInfo);
  16712. if (act)
  16713. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  16714. }
  16715. }
  16716. if (checkSingleClickImmediately) {
  16717. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  16718. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  16719. btn !== _this._previousButtonPressed) {
  16720. clickInfo.singleClick = true;
  16721. cb(clickInfo, _this._currentPickResult);
  16722. }
  16723. }
  16724. else {
  16725. // wait that no double click has been raised during the double click delay
  16726. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16727. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  16728. }
  16729. var checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  16730. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16731. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16732. act = _this._initActionManager(act, clickInfo);
  16733. if (act)
  16734. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  16735. }
  16736. if (checkDoubleClick) {
  16737. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  16738. if (btn === _this._previousButtonPressed &&
  16739. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  16740. !_this._doubleClickOccured) {
  16741. // pointer has not moved for 2 clicks, it's a double click
  16742. if (!clickInfo.hasSwiped &&
  16743. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  16744. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  16745. _this._previousStartingPointerTime = 0;
  16746. _this._doubleClickOccured = true;
  16747. clickInfo.doubleClick = true;
  16748. clickInfo.ignore = false;
  16749. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  16750. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  16751. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16752. cb(clickInfo, _this._currentPickResult);
  16753. }
  16754. else {
  16755. _this._doubleClickOccured = false;
  16756. _this._previousStartingPointerTime = _this._startingPointerTime;
  16757. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  16758. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  16759. _this._previousButtonPressed = btn;
  16760. _this._previousHasSwiped = clickInfo.hasSwiped;
  16761. if (Scene.ExclusiveDoubleClickMode) {
  16762. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  16763. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  16764. }
  16765. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16766. cb(clickInfo, _this._previousPickResult);
  16767. }
  16768. else {
  16769. cb(clickInfo, _this._currentPickResult);
  16770. }
  16771. }
  16772. }
  16773. else {
  16774. _this._doubleClickOccured = false;
  16775. _this._previousStartingPointerTime = _this._startingPointerTime;
  16776. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  16777. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  16778. _this._previousButtonPressed = btn;
  16779. _this._previousHasSwiped = clickInfo.hasSwiped;
  16780. }
  16781. }
  16782. }
  16783. }
  16784. clickInfo.ignore = true;
  16785. cb(clickInfo, _this._currentPickResult);
  16786. };
  16787. var spritePredicate = function (sprite) {
  16788. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  16789. };
  16790. this._onPointerMove = function (evt) {
  16791. _this._updatePointerPosition(evt);
  16792. // PreObservable support
  16793. if (_this.onPrePointerObservable.hasObservers()) {
  16794. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16795. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16796. _this.onPrePointerObservable.notifyObservers(pi, type);
  16797. if (pi.skipOnPointerObservable) {
  16798. return;
  16799. }
  16800. }
  16801. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16802. return;
  16803. }
  16804. var canvas = _this._engine.getRenderingCanvas();
  16805. if (!_this.pointerMovePredicate) {
  16806. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  16807. }
  16808. // Meshes
  16809. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  16810. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16811. _this.setPointerOverSprite(null);
  16812. _this.setPointerOverMesh(pickResult.pickedMesh);
  16813. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  16814. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  16815. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  16816. }
  16817. else {
  16818. canvas.style.cursor = _this.hoverCursor;
  16819. }
  16820. }
  16821. else {
  16822. canvas.style.cursor = _this.defaultCursor;
  16823. }
  16824. }
  16825. else {
  16826. _this.setPointerOverMesh(null);
  16827. // Sprites
  16828. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16829. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  16830. _this.setPointerOverSprite(pickResult.pickedSprite);
  16831. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  16832. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  16833. }
  16834. else {
  16835. canvas.style.cursor = _this.hoverCursor;
  16836. }
  16837. }
  16838. else {
  16839. _this.setPointerOverSprite(null);
  16840. // Restore pointer
  16841. canvas.style.cursor = _this.defaultCursor;
  16842. }
  16843. }
  16844. if (_this.onPointerMove) {
  16845. _this.onPointerMove(evt, pickResult);
  16846. }
  16847. if (_this.onPointerObservable.hasObservers()) {
  16848. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16849. var pi = new PointerInfo(type, evt, pickResult);
  16850. _this.onPointerObservable.notifyObservers(pi, type);
  16851. }
  16852. };
  16853. this._onPointerDown = function (evt) {
  16854. _this._isButtonPressed = true;
  16855. _this._pickedDownMesh = null;
  16856. _this._meshPickProceed = false;
  16857. _this._updatePointerPosition(evt);
  16858. // PreObservable support
  16859. if (_this.onPrePointerObservable.hasObservers()) {
  16860. var type = PointerEventTypes.POINTERDOWN;
  16861. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16862. _this.onPrePointerObservable.notifyObservers(pi, type);
  16863. if (pi.skipOnPointerObservable) {
  16864. return;
  16865. }
  16866. }
  16867. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16868. return;
  16869. }
  16870. _this._startingPointerPosition.x = _this._pointerX;
  16871. _this._startingPointerPosition.y = _this._pointerY;
  16872. _this._startingPointerTime = new Date().getTime();
  16873. if (!_this.pointerDownPredicate) {
  16874. _this.pointerDownPredicate = function (mesh) {
  16875. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  16876. };
  16877. }
  16878. // Meshes
  16879. _this._pickedDownMesh = null;
  16880. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16881. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16882. _this._pickedDownMesh = pickResult.pickedMesh;
  16883. var actionManager = pickResult.pickedMesh.actionManager;
  16884. if (actionManager) {
  16885. if (actionManager.hasPickTriggers) {
  16886. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16887. switch (evt.button) {
  16888. case 0:
  16889. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16890. break;
  16891. case 1:
  16892. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16893. break;
  16894. case 2:
  16895. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16896. break;
  16897. }
  16898. }
  16899. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  16900. window.setTimeout((function () {
  16901. var _this = this;
  16902. 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);
  16903. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16904. if (this._isButtonPressed &&
  16905. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  16906. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  16907. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  16908. this._startingPointerTime = 0;
  16909. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16910. }
  16911. }
  16912. }).bind(_this), Scene.LongPressDelay);
  16913. }
  16914. }
  16915. }
  16916. if (_this.onPointerDown) {
  16917. _this.onPointerDown(evt, pickResult);
  16918. }
  16919. if (_this.onPointerObservable.hasObservers()) {
  16920. var type = PointerEventTypes.POINTERDOWN;
  16921. var pi = new PointerInfo(type, evt, pickResult);
  16922. _this.onPointerObservable.notifyObservers(pi, type);
  16923. }
  16924. // Sprites
  16925. _this._pickedDownSprite = null;
  16926. if (_this.spriteManagers.length > 0) {
  16927. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16928. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  16929. if (pickResult.pickedSprite.actionManager) {
  16930. _this._pickedDownSprite = pickResult.pickedSprite;
  16931. switch (evt.button) {
  16932. case 0:
  16933. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16934. break;
  16935. case 1:
  16936. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16937. break;
  16938. case 2:
  16939. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16940. break;
  16941. }
  16942. if (pickResult.pickedSprite.actionManager) {
  16943. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16944. }
  16945. }
  16946. }
  16947. }
  16948. };
  16949. this._onPointerUp = function (evt) {
  16950. _this._isButtonPressed = false;
  16951. _this._pickedUpMesh = null;
  16952. _this._meshPickProceed = false;
  16953. _this._updatePointerPosition(evt);
  16954. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  16955. // PreObservable support
  16956. if (this.onPrePointerObservable.hasObservers()) {
  16957. if (!clickInfo.ignore) {
  16958. if (!clickInfo.hasSwiped) {
  16959. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  16960. var type = PointerEventTypes.POINTERTAP;
  16961. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16962. this.onPrePointerObservable.notifyObservers(pi, type);
  16963. if (pi.skipOnPointerObservable) {
  16964. return;
  16965. }
  16966. }
  16967. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  16968. var type = PointerEventTypes.POINTERDOUBLETAP;
  16969. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16970. this.onPrePointerObservable.notifyObservers(pi, type);
  16971. if (pi.skipOnPointerObservable) {
  16972. return;
  16973. }
  16974. }
  16975. }
  16976. }
  16977. else {
  16978. var type = PointerEventTypes.POINTERUP;
  16979. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16980. this.onPrePointerObservable.notifyObservers(pi, type);
  16981. if (pi.skipOnPointerObservable) {
  16982. return;
  16983. }
  16984. }
  16985. }
  16986. if (!this.cameraToUseForPointers && !this.activeCamera) {
  16987. return;
  16988. }
  16989. if (!this.pointerUpPredicate) {
  16990. this.pointerUpPredicate = function (mesh) {
  16991. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  16992. };
  16993. }
  16994. // Meshes
  16995. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  16996. this._initActionManager(null, clickInfo);
  16997. }
  16998. if (!pickResult) {
  16999. pickResult = this._currentPickResult;
  17000. }
  17001. if (pickResult && pickResult && pickResult.pickedMesh) {
  17002. this._pickedUpMesh = pickResult.pickedMesh;
  17003. if (this._pickedDownMesh === this._pickedUpMesh) {
  17004. if (this.onPointerPick) {
  17005. this.onPointerPick(evt, pickResult);
  17006. }
  17007. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  17008. var type = PointerEventTypes.POINTERPICK;
  17009. var pi = new PointerInfo(type, evt, pickResult);
  17010. this.onPointerObservable.notifyObservers(pi, type);
  17011. }
  17012. }
  17013. if (pickResult.pickedMesh.actionManager) {
  17014. if (clickInfo.ignore) {
  17015. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17016. }
  17017. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  17018. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17019. }
  17020. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17021. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17022. }
  17023. }
  17024. }
  17025. if (this._pickedDownMesh &&
  17026. this._pickedDownMesh.actionManager &&
  17027. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  17028. this._pickedDownMesh !== this._pickedUpMesh) {
  17029. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  17030. }
  17031. if (this.onPointerUp) {
  17032. this.onPointerUp(evt, pickResult);
  17033. }
  17034. if (this.onPointerObservable.hasObservers()) {
  17035. if (!clickInfo.ignore) {
  17036. if (!clickInfo.hasSwiped) {
  17037. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  17038. var type = PointerEventTypes.POINTERTAP;
  17039. var pi = new PointerInfo(type, evt, pickResult);
  17040. this.onPointerObservable.notifyObservers(pi, type);
  17041. }
  17042. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  17043. var type = PointerEventTypes.POINTERDOUBLETAP;
  17044. var pi = new PointerInfo(type, evt, pickResult);
  17045. this.onPointerObservable.notifyObservers(pi, type);
  17046. }
  17047. }
  17048. }
  17049. else {
  17050. var type = PointerEventTypes.POINTERUP;
  17051. var pi = new PointerInfo(type, evt, pickResult);
  17052. this.onPointerObservable.notifyObservers(pi, type);
  17053. }
  17054. }
  17055. // Sprites
  17056. if (this.spriteManagers.length > 0) {
  17057. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  17058. if (pickResult.hit && pickResult.pickedSprite) {
  17059. if (pickResult.pickedSprite.actionManager) {
  17060. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  17061. if (pickResult.pickedSprite.actionManager) {
  17062. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  17063. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  17064. }
  17065. }
  17066. }
  17067. }
  17068. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  17069. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  17070. }
  17071. }
  17072. this._previousPickResult = this._currentPickResult;
  17073. }).bind(_this));
  17074. };
  17075. this._onKeyDown = function (evt) {
  17076. if (_this.actionManager) {
  17077. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17078. }
  17079. };
  17080. this._onKeyUp = function (evt) {
  17081. if (_this.actionManager) {
  17082. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17083. }
  17084. };
  17085. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17086. var canvas = this._engine.getRenderingCanvas();
  17087. if (attachMove) {
  17088. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  17089. // Wheel
  17090. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  17091. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  17092. }
  17093. if (attachDown) {
  17094. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  17095. }
  17096. if (attachUp) {
  17097. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  17098. }
  17099. canvas.tabIndex = 1;
  17100. canvas.addEventListener("keydown", this._onKeyDown, false);
  17101. canvas.addEventListener("keyup", this._onKeyUp, false);
  17102. };
  17103. Scene.prototype.detachControl = function () {
  17104. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17105. var canvas = this._engine.getRenderingCanvas();
  17106. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  17107. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  17108. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  17109. // Wheel
  17110. canvas.removeEventListener('mousewheel', this._onPointerMove);
  17111. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  17112. canvas.removeEventListener("keydown", this._onKeyDown);
  17113. canvas.removeEventListener("keyup", this._onKeyUp);
  17114. };
  17115. // Ready
  17116. Scene.prototype.isReady = function () {
  17117. if (this._pendingData.length > 0) {
  17118. return false;
  17119. }
  17120. var index;
  17121. // Geometries
  17122. for (index = 0; index < this._geometries.length; index++) {
  17123. var geometry = this._geometries[index];
  17124. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17125. return false;
  17126. }
  17127. }
  17128. // Meshes
  17129. for (index = 0; index < this.meshes.length; index++) {
  17130. var mesh = this.meshes[index];
  17131. if (!mesh.isEnabled()) {
  17132. continue;
  17133. }
  17134. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  17135. continue;
  17136. }
  17137. if (!mesh.isReady()) {
  17138. return false;
  17139. }
  17140. var mat = mesh.material;
  17141. if (mat) {
  17142. if (!mat.isReady(mesh)) {
  17143. return false;
  17144. }
  17145. }
  17146. }
  17147. return true;
  17148. };
  17149. Scene.prototype.resetCachedMaterial = function () {
  17150. this._cachedMaterial = null;
  17151. this._cachedEffect = null;
  17152. this._cachedVisibility = null;
  17153. };
  17154. Scene.prototype.registerBeforeRender = function (func) {
  17155. this.onBeforeRenderObservable.add(func);
  17156. };
  17157. Scene.prototype.unregisterBeforeRender = function (func) {
  17158. this.onBeforeRenderObservable.removeCallback(func);
  17159. };
  17160. Scene.prototype.registerAfterRender = function (func) {
  17161. this.onAfterRenderObservable.add(func);
  17162. };
  17163. Scene.prototype.unregisterAfterRender = function (func) {
  17164. this.onAfterRenderObservable.removeCallback(func);
  17165. };
  17166. Scene.prototype._addPendingData = function (data) {
  17167. this._pendingData.push(data);
  17168. };
  17169. Scene.prototype._removePendingData = function (data) {
  17170. var index = this._pendingData.indexOf(data);
  17171. if (index !== -1) {
  17172. this._pendingData.splice(index, 1);
  17173. }
  17174. };
  17175. Scene.prototype.getWaitingItemsCount = function () {
  17176. return this._pendingData.length;
  17177. };
  17178. /**
  17179. * Registers a function to be executed when the scene is ready.
  17180. * @param {Function} func - the function to be executed.
  17181. */
  17182. Scene.prototype.executeWhenReady = function (func) {
  17183. var _this = this;
  17184. this.onReadyObservable.add(func);
  17185. if (this._executeWhenReadyTimeoutId !== -1) {
  17186. return;
  17187. }
  17188. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17189. _this._checkIsReady();
  17190. }, 150);
  17191. };
  17192. Scene.prototype._checkIsReady = function () {
  17193. var _this = this;
  17194. if (this.isReady()) {
  17195. this.onReadyObservable.notifyObservers(this);
  17196. this.onReadyObservable.clear();
  17197. this._executeWhenReadyTimeoutId = -1;
  17198. return;
  17199. }
  17200. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17201. _this._checkIsReady();
  17202. }, 150);
  17203. };
  17204. // Animations
  17205. /**
  17206. * Will start the animation sequence of a given target
  17207. * @param target - the target
  17208. * @param {number} from - from which frame should animation start
  17209. * @param {number} to - till which frame should animation run.
  17210. * @param {boolean} [loop] - should the animation loop
  17211. * @param {number} [speedRatio] - the speed in which to run the animation
  17212. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  17213. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  17214. * Returns {BABYLON.Animatable} the animatable object created for this animation
  17215. * See BABYLON.Animatable
  17216. */
  17217. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  17218. if (speedRatio === void 0) { speedRatio = 1.0; }
  17219. if (from > to && speedRatio > 0) {
  17220. speedRatio *= -1;
  17221. }
  17222. this.stopAnimation(target);
  17223. if (!animatable) {
  17224. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  17225. }
  17226. // Local animations
  17227. if (target.animations) {
  17228. animatable.appendAnimations(target, target.animations);
  17229. }
  17230. // Children animations
  17231. if (target.getAnimatables) {
  17232. var animatables = target.getAnimatables();
  17233. for (var index = 0; index < animatables.length; index++) {
  17234. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  17235. }
  17236. }
  17237. animatable.reset();
  17238. return animatable;
  17239. };
  17240. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  17241. if (speedRatio === undefined) {
  17242. speedRatio = 1.0;
  17243. }
  17244. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  17245. return animatable;
  17246. };
  17247. Scene.prototype.getAnimatableByTarget = function (target) {
  17248. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17249. if (this._activeAnimatables[index].target === target) {
  17250. return this._activeAnimatables[index];
  17251. }
  17252. }
  17253. return null;
  17254. };
  17255. Object.defineProperty(Scene.prototype, "Animatables", {
  17256. get: function () {
  17257. return this._activeAnimatables;
  17258. },
  17259. enumerable: true,
  17260. configurable: true
  17261. });
  17262. /**
  17263. * Will stop the animation of the given target
  17264. * @param target - the target
  17265. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  17266. * @see beginAnimation
  17267. */
  17268. Scene.prototype.stopAnimation = function (target, animationName) {
  17269. var animatable = this.getAnimatableByTarget(target);
  17270. if (animatable) {
  17271. animatable.stop(animationName);
  17272. }
  17273. };
  17274. Scene.prototype._animate = function () {
  17275. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  17276. return;
  17277. }
  17278. // Getting time
  17279. var now = BABYLON.Tools.Now;
  17280. if (!this._animationTimeLast) {
  17281. if (this._pendingData.length > 0) {
  17282. return;
  17283. }
  17284. this._animationTimeLast = now;
  17285. }
  17286. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  17287. this._animationTime += deltaTime;
  17288. this._animationTimeLast = now;
  17289. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17290. this._activeAnimatables[index]._animate(this._animationTime);
  17291. }
  17292. };
  17293. // Matrix
  17294. Scene.prototype.getViewMatrix = function () {
  17295. return this._viewMatrix;
  17296. };
  17297. Scene.prototype.getProjectionMatrix = function () {
  17298. return this._projectionMatrix;
  17299. };
  17300. Scene.prototype.getTransformMatrix = function () {
  17301. return this._transformMatrix;
  17302. };
  17303. Scene.prototype.setTransformMatrix = function (view, projection) {
  17304. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  17305. return;
  17306. }
  17307. this._viewUpdateFlag = view.updateFlag;
  17308. this._projectionUpdateFlag = projection.updateFlag;
  17309. this._viewMatrix = view;
  17310. this._projectionMatrix = projection;
  17311. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  17312. // Update frustum
  17313. if (!this._frustumPlanes) {
  17314. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  17315. }
  17316. else {
  17317. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  17318. }
  17319. if (this._sceneUbo.useUbo) {
  17320. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  17321. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  17322. this._sceneUbo.update();
  17323. }
  17324. };
  17325. Scene.prototype.getSceneUniformBuffer = function () {
  17326. return this._sceneUbo;
  17327. };
  17328. // Methods
  17329. Scene.prototype.getUniqueId = function () {
  17330. var result = this._uniqueIdCounter;
  17331. this._uniqueIdCounter++;
  17332. return result;
  17333. };
  17334. Scene.prototype.addMesh = function (newMesh) {
  17335. newMesh.uniqueId = this.getUniqueId();
  17336. var position = this.meshes.push(newMesh);
  17337. //notify the collision coordinator
  17338. if (this.collisionCoordinator) {
  17339. this.collisionCoordinator.onMeshAdded(newMesh);
  17340. }
  17341. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  17342. };
  17343. Scene.prototype.removeMesh = function (toRemove) {
  17344. var index = this.meshes.indexOf(toRemove);
  17345. if (index !== -1) {
  17346. // Remove from the scene if mesh found
  17347. this.meshes.splice(index, 1);
  17348. }
  17349. //notify the collision coordinator
  17350. if (this.collisionCoordinator) {
  17351. this.collisionCoordinator.onMeshRemoved(toRemove);
  17352. }
  17353. this.onMeshRemovedObservable.notifyObservers(toRemove);
  17354. return index;
  17355. };
  17356. Scene.prototype.removeSkeleton = function (toRemove) {
  17357. var index = this.skeletons.indexOf(toRemove);
  17358. if (index !== -1) {
  17359. // Remove from the scene if found
  17360. this.skeletons.splice(index, 1);
  17361. }
  17362. return index;
  17363. };
  17364. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  17365. var index = this.morphTargetManagers.indexOf(toRemove);
  17366. if (index !== -1) {
  17367. // Remove from the scene if found
  17368. this.morphTargetManagers.splice(index, 1);
  17369. }
  17370. return index;
  17371. };
  17372. Scene.prototype.removeLight = function (toRemove) {
  17373. var index = this.lights.indexOf(toRemove);
  17374. if (index !== -1) {
  17375. // Remove from the scene if mesh found
  17376. this.lights.splice(index, 1);
  17377. this.sortLightsByPriority();
  17378. }
  17379. this.onLightRemovedObservable.notifyObservers(toRemove);
  17380. return index;
  17381. };
  17382. Scene.prototype.removeCamera = function (toRemove) {
  17383. var index = this.cameras.indexOf(toRemove);
  17384. if (index !== -1) {
  17385. // Remove from the scene if mesh found
  17386. this.cameras.splice(index, 1);
  17387. }
  17388. // Remove from activeCameras
  17389. var index2 = this.activeCameras.indexOf(toRemove);
  17390. if (index2 !== -1) {
  17391. // Remove from the scene if mesh found
  17392. this.activeCameras.splice(index2, 1);
  17393. }
  17394. // Reset the activeCamera
  17395. if (this.activeCamera === toRemove) {
  17396. if (this.cameras.length > 0) {
  17397. this.activeCamera = this.cameras[0];
  17398. }
  17399. else {
  17400. this.activeCamera = null;
  17401. }
  17402. }
  17403. this.onCameraRemovedObservable.notifyObservers(toRemove);
  17404. return index;
  17405. };
  17406. Scene.prototype.addLight = function (newLight) {
  17407. newLight.uniqueId = this.getUniqueId();
  17408. this.lights.push(newLight);
  17409. this.sortLightsByPriority();
  17410. this.onNewLightAddedObservable.notifyObservers(newLight);
  17411. };
  17412. Scene.prototype.sortLightsByPriority = function () {
  17413. if (this.requireLightSorting) {
  17414. this.lights.sort(BABYLON.Light.compareLightsPriority);
  17415. }
  17416. };
  17417. Scene.prototype.addCamera = function (newCamera) {
  17418. newCamera.uniqueId = this.getUniqueId();
  17419. var position = this.cameras.push(newCamera);
  17420. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  17421. };
  17422. /**
  17423. * Switch active camera
  17424. * @param {Camera} newCamera - new active camera
  17425. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  17426. */
  17427. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  17428. if (attachControl === void 0) { attachControl = true; }
  17429. var canvas = this._engine.getRenderingCanvas();
  17430. this.activeCamera.detachControl(canvas);
  17431. this.activeCamera = newCamera;
  17432. if (attachControl) {
  17433. newCamera.attachControl(canvas);
  17434. }
  17435. };
  17436. /**
  17437. * sets the active camera of the scene using its ID
  17438. * @param {string} id - the camera's ID
  17439. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17440. * @see activeCamera
  17441. */
  17442. Scene.prototype.setActiveCameraByID = function (id) {
  17443. var camera = this.getCameraByID(id);
  17444. if (camera) {
  17445. this.activeCamera = camera;
  17446. return camera;
  17447. }
  17448. return null;
  17449. };
  17450. /**
  17451. * sets the active camera of the scene using its name
  17452. * @param {string} name - the camera's name
  17453. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17454. * @see activeCamera
  17455. */
  17456. Scene.prototype.setActiveCameraByName = function (name) {
  17457. var camera = this.getCameraByName(name);
  17458. if (camera) {
  17459. this.activeCamera = camera;
  17460. return camera;
  17461. }
  17462. return null;
  17463. };
  17464. /**
  17465. * get a material using its id
  17466. * @param {string} the material's ID
  17467. * @return {BABYLON.Material|null} the material or null if none found.
  17468. */
  17469. Scene.prototype.getMaterialByID = function (id) {
  17470. for (var index = 0; index < this.materials.length; index++) {
  17471. if (this.materials[index].id === id) {
  17472. return this.materials[index];
  17473. }
  17474. }
  17475. return null;
  17476. };
  17477. /**
  17478. * get a material using its name
  17479. * @param {string} the material's name
  17480. * @return {BABYLON.Material|null} the material or null if none found.
  17481. */
  17482. Scene.prototype.getMaterialByName = function (name) {
  17483. for (var index = 0; index < this.materials.length; index++) {
  17484. if (this.materials[index].name === name) {
  17485. return this.materials[index];
  17486. }
  17487. }
  17488. return null;
  17489. };
  17490. Scene.prototype.getLensFlareSystemByName = function (name) {
  17491. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17492. if (this.lensFlareSystems[index].name === name) {
  17493. return this.lensFlareSystems[index];
  17494. }
  17495. }
  17496. return null;
  17497. };
  17498. Scene.prototype.getLensFlareSystemByID = function (id) {
  17499. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17500. if (this.lensFlareSystems[index].id === id) {
  17501. return this.lensFlareSystems[index];
  17502. }
  17503. }
  17504. return null;
  17505. };
  17506. Scene.prototype.getCameraByID = function (id) {
  17507. for (var index = 0; index < this.cameras.length; index++) {
  17508. if (this.cameras[index].id === id) {
  17509. return this.cameras[index];
  17510. }
  17511. }
  17512. return null;
  17513. };
  17514. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  17515. for (var index = 0; index < this.cameras.length; index++) {
  17516. if (this.cameras[index].uniqueId === uniqueId) {
  17517. return this.cameras[index];
  17518. }
  17519. }
  17520. return null;
  17521. };
  17522. /**
  17523. * get a camera using its name
  17524. * @param {string} the camera's name
  17525. * @return {BABYLON.Camera|null} the camera or null if none found.
  17526. */
  17527. Scene.prototype.getCameraByName = function (name) {
  17528. for (var index = 0; index < this.cameras.length; index++) {
  17529. if (this.cameras[index].name === name) {
  17530. return this.cameras[index];
  17531. }
  17532. }
  17533. return null;
  17534. };
  17535. /**
  17536. * get a bone using its id
  17537. * @param {string} the bone's id
  17538. * @return {BABYLON.Bone|null} the bone or null if not found
  17539. */
  17540. Scene.prototype.getBoneByID = function (id) {
  17541. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17542. var skeleton = this.skeletons[skeletonIndex];
  17543. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17544. if (skeleton.bones[boneIndex].id === id) {
  17545. return skeleton.bones[boneIndex];
  17546. }
  17547. }
  17548. }
  17549. return null;
  17550. };
  17551. /**
  17552. * get a bone using its id
  17553. * @param {string} the bone's name
  17554. * @return {BABYLON.Bone|null} the bone or null if not found
  17555. */
  17556. Scene.prototype.getBoneByName = function (name) {
  17557. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17558. var skeleton = this.skeletons[skeletonIndex];
  17559. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17560. if (skeleton.bones[boneIndex].name === name) {
  17561. return skeleton.bones[boneIndex];
  17562. }
  17563. }
  17564. }
  17565. return null;
  17566. };
  17567. /**
  17568. * get a light node using its name
  17569. * @param {string} the light's name
  17570. * @return {BABYLON.Light|null} the light or null if none found.
  17571. */
  17572. Scene.prototype.getLightByName = function (name) {
  17573. for (var index = 0; index < this.lights.length; index++) {
  17574. if (this.lights[index].name === name) {
  17575. return this.lights[index];
  17576. }
  17577. }
  17578. return null;
  17579. };
  17580. /**
  17581. * get a light node using its ID
  17582. * @param {string} the light's id
  17583. * @return {BABYLON.Light|null} the light or null if none found.
  17584. */
  17585. Scene.prototype.getLightByID = function (id) {
  17586. for (var index = 0; index < this.lights.length; index++) {
  17587. if (this.lights[index].id === id) {
  17588. return this.lights[index];
  17589. }
  17590. }
  17591. return null;
  17592. };
  17593. /**
  17594. * get a light node using its scene-generated unique ID
  17595. * @param {number} the light's unique id
  17596. * @return {BABYLON.Light|null} the light or null if none found.
  17597. */
  17598. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  17599. for (var index = 0; index < this.lights.length; index++) {
  17600. if (this.lights[index].uniqueId === uniqueId) {
  17601. return this.lights[index];
  17602. }
  17603. }
  17604. return null;
  17605. };
  17606. /**
  17607. * get a particle system by id
  17608. * @param id {number} the particle system id
  17609. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  17610. */
  17611. Scene.prototype.getParticleSystemByID = function (id) {
  17612. for (var index = 0; index < this.particleSystems.length; index++) {
  17613. if (this.particleSystems[index].id === id) {
  17614. return this.particleSystems[index];
  17615. }
  17616. }
  17617. return null;
  17618. };
  17619. /**
  17620. * get a geometry using its ID
  17621. * @param {string} the geometry's id
  17622. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  17623. */
  17624. Scene.prototype.getGeometryByID = function (id) {
  17625. for (var index = 0; index < this._geometries.length; index++) {
  17626. if (this._geometries[index].id === id) {
  17627. return this._geometries[index];
  17628. }
  17629. }
  17630. return null;
  17631. };
  17632. /**
  17633. * add a new geometry to this scene.
  17634. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  17635. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  17636. * @return {boolean} was the geometry added or not
  17637. */
  17638. Scene.prototype.pushGeometry = function (geometry, force) {
  17639. if (!force && this.getGeometryByID(geometry.id)) {
  17640. return false;
  17641. }
  17642. this._geometries.push(geometry);
  17643. //notify the collision coordinator
  17644. if (this.collisionCoordinator) {
  17645. this.collisionCoordinator.onGeometryAdded(geometry);
  17646. }
  17647. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  17648. return true;
  17649. };
  17650. /**
  17651. * Removes an existing geometry
  17652. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  17653. * @return {boolean} was the geometry removed or not
  17654. */
  17655. Scene.prototype.removeGeometry = function (geometry) {
  17656. var index = this._geometries.indexOf(geometry);
  17657. if (index > -1) {
  17658. this._geometries.splice(index, 1);
  17659. //notify the collision coordinator
  17660. if (this.collisionCoordinator) {
  17661. this.collisionCoordinator.onGeometryDeleted(geometry);
  17662. }
  17663. this.onGeometryRemovedObservable.notifyObservers(geometry);
  17664. return true;
  17665. }
  17666. return false;
  17667. };
  17668. Scene.prototype.getGeometries = function () {
  17669. return this._geometries;
  17670. };
  17671. /**
  17672. * Get the first added mesh found of a given ID
  17673. * @param {string} id - the id to search for
  17674. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17675. */
  17676. Scene.prototype.getMeshByID = function (id) {
  17677. for (var index = 0; index < this.meshes.length; index++) {
  17678. if (this.meshes[index].id === id) {
  17679. return this.meshes[index];
  17680. }
  17681. }
  17682. return null;
  17683. };
  17684. Scene.prototype.getMeshesByID = function (id) {
  17685. return this.meshes.filter(function (m) {
  17686. return m.id === id;
  17687. });
  17688. };
  17689. /**
  17690. * Get a mesh with its auto-generated unique id
  17691. * @param {number} uniqueId - the unique id to search for
  17692. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17693. */
  17694. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  17695. for (var index = 0; index < this.meshes.length; index++) {
  17696. if (this.meshes[index].uniqueId === uniqueId) {
  17697. return this.meshes[index];
  17698. }
  17699. }
  17700. return null;
  17701. };
  17702. /**
  17703. * Get a the last added mesh found of a given ID
  17704. * @param {string} id - the id to search for
  17705. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17706. */
  17707. Scene.prototype.getLastMeshByID = function (id) {
  17708. for (var index = this.meshes.length - 1; index >= 0; index--) {
  17709. if (this.meshes[index].id === id) {
  17710. return this.meshes[index];
  17711. }
  17712. }
  17713. return null;
  17714. };
  17715. /**
  17716. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  17717. * @param {string} id - the id to search for
  17718. * @return {BABYLON.Node|null} the node found or null if not found at all.
  17719. */
  17720. Scene.prototype.getLastEntryByID = function (id) {
  17721. var index;
  17722. for (index = this.meshes.length - 1; index >= 0; index--) {
  17723. if (this.meshes[index].id === id) {
  17724. return this.meshes[index];
  17725. }
  17726. }
  17727. for (index = this.cameras.length - 1; index >= 0; index--) {
  17728. if (this.cameras[index].id === id) {
  17729. return this.cameras[index];
  17730. }
  17731. }
  17732. for (index = this.lights.length - 1; index >= 0; index--) {
  17733. if (this.lights[index].id === id) {
  17734. return this.lights[index];
  17735. }
  17736. }
  17737. return null;
  17738. };
  17739. Scene.prototype.getNodeByID = function (id) {
  17740. var mesh = this.getMeshByID(id);
  17741. if (mesh) {
  17742. return mesh;
  17743. }
  17744. var light = this.getLightByID(id);
  17745. if (light) {
  17746. return light;
  17747. }
  17748. var camera = this.getCameraByID(id);
  17749. if (camera) {
  17750. return camera;
  17751. }
  17752. var bone = this.getBoneByID(id);
  17753. return bone;
  17754. };
  17755. Scene.prototype.getNodeByName = function (name) {
  17756. var mesh = this.getMeshByName(name);
  17757. if (mesh) {
  17758. return mesh;
  17759. }
  17760. var light = this.getLightByName(name);
  17761. if (light) {
  17762. return light;
  17763. }
  17764. var camera = this.getCameraByName(name);
  17765. if (camera) {
  17766. return camera;
  17767. }
  17768. var bone = this.getBoneByName(name);
  17769. return bone;
  17770. };
  17771. Scene.prototype.getMeshByName = function (name) {
  17772. for (var index = 0; index < this.meshes.length; index++) {
  17773. if (this.meshes[index].name === name) {
  17774. return this.meshes[index];
  17775. }
  17776. }
  17777. return null;
  17778. };
  17779. Scene.prototype.getSoundByName = function (name) {
  17780. var index;
  17781. if (BABYLON.AudioEngine) {
  17782. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  17783. if (this.mainSoundTrack.soundCollection[index].name === name) {
  17784. return this.mainSoundTrack.soundCollection[index];
  17785. }
  17786. }
  17787. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  17788. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  17789. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  17790. return this.soundTracks[sdIndex].soundCollection[index];
  17791. }
  17792. }
  17793. }
  17794. }
  17795. return null;
  17796. };
  17797. Scene.prototype.getLastSkeletonByID = function (id) {
  17798. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  17799. if (this.skeletons[index].id === id) {
  17800. return this.skeletons[index];
  17801. }
  17802. }
  17803. return null;
  17804. };
  17805. Scene.prototype.getSkeletonById = function (id) {
  17806. for (var index = 0; index < this.skeletons.length; index++) {
  17807. if (this.skeletons[index].id === id) {
  17808. return this.skeletons[index];
  17809. }
  17810. }
  17811. return null;
  17812. };
  17813. Scene.prototype.getSkeletonByName = function (name) {
  17814. for (var index = 0; index < this.skeletons.length; index++) {
  17815. if (this.skeletons[index].name === name) {
  17816. return this.skeletons[index];
  17817. }
  17818. }
  17819. return null;
  17820. };
  17821. Scene.prototype.getMorphTargetManagerById = function (id) {
  17822. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  17823. if (this.morphTargetManagers[index].uniqueId === id) {
  17824. return this.morphTargetManagers[index];
  17825. }
  17826. }
  17827. return null;
  17828. };
  17829. Scene.prototype.isActiveMesh = function (mesh) {
  17830. return (this._activeMeshes.indexOf(mesh) !== -1);
  17831. };
  17832. /**
  17833. * Return a the first highlight layer of the scene with a given name.
  17834. * @param name The name of the highlight layer to look for.
  17835. * @return The highlight layer if found otherwise null.
  17836. */
  17837. Scene.prototype.getHighlightLayerByName = function (name) {
  17838. for (var index = 0; index < this.highlightLayers.length; index++) {
  17839. if (this.highlightLayers[index].name === name) {
  17840. return this.highlightLayers[index];
  17841. }
  17842. }
  17843. return null;
  17844. };
  17845. Object.defineProperty(Scene.prototype, "uid", {
  17846. /**
  17847. * Return a unique id as a string which can serve as an identifier for the scene
  17848. */
  17849. get: function () {
  17850. if (!this._uid) {
  17851. this._uid = BABYLON.Tools.RandomId();
  17852. }
  17853. return this._uid;
  17854. },
  17855. enumerable: true,
  17856. configurable: true
  17857. });
  17858. /**
  17859. * Add an externaly attached data from its key.
  17860. * This method call will fail and return false, if such key already exists.
  17861. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17862. * @param key the unique key that identifies the data
  17863. * @param data the data object to associate to the key for this Engine instance
  17864. * @return true if no such key were already present and the data was added successfully, false otherwise
  17865. */
  17866. Scene.prototype.addExternalData = function (key, data) {
  17867. if (!this._externalData) {
  17868. this._externalData = new BABYLON.StringDictionary();
  17869. }
  17870. return this._externalData.add(key, data);
  17871. };
  17872. /**
  17873. * Get an externaly attached data from its key
  17874. * @param key the unique key that identifies the data
  17875. * @return the associated data, if present (can be null), or undefined if not present
  17876. */
  17877. Scene.prototype.getExternalData = function (key) {
  17878. if (!this._externalData) {
  17879. return null;
  17880. }
  17881. return this._externalData.get(key);
  17882. };
  17883. /**
  17884. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17885. * @param key the unique key that identifies the data
  17886. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17887. * @return the associated data, can be null if the factory returned null.
  17888. */
  17889. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17890. if (!this._externalData) {
  17891. this._externalData = new BABYLON.StringDictionary();
  17892. }
  17893. return this._externalData.getOrAddWithFactory(key, factory);
  17894. };
  17895. /**
  17896. * Remove an externaly attached data from the Engine instance
  17897. * @param key the unique key that identifies the data
  17898. * @return true if the data was successfully removed, false if it doesn't exist
  17899. */
  17900. Scene.prototype.removeExternalData = function (key) {
  17901. return this._externalData.remove(key);
  17902. };
  17903. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  17904. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  17905. var material = subMesh.getMaterial();
  17906. if (mesh.showSubMeshesBoundingBox) {
  17907. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  17908. }
  17909. if (material) {
  17910. // Render targets
  17911. if (material.getRenderTargetTextures) {
  17912. if (this._processedMaterials.indexOf(material) === -1) {
  17913. this._processedMaterials.push(material);
  17914. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  17915. }
  17916. }
  17917. // Dispatch
  17918. this._activeIndices.addCount(subMesh.indexCount, false);
  17919. this._renderingManager.dispatch(subMesh);
  17920. }
  17921. }
  17922. };
  17923. Scene.prototype._isInIntermediateRendering = function () {
  17924. return this._intermediateRendering;
  17925. };
  17926. Scene.prototype._evaluateActiveMeshes = function () {
  17927. this.activeCamera._activeMeshes.reset();
  17928. this._activeMeshes.reset();
  17929. this._renderingManager.reset();
  17930. this._processedMaterials.reset();
  17931. this._activeParticleSystems.reset();
  17932. this._activeSkeletons.reset();
  17933. this._softwareSkinnedMeshes.reset();
  17934. if (this._boundingBoxRenderer) {
  17935. this._boundingBoxRenderer.reset();
  17936. }
  17937. // Meshes
  17938. var meshes;
  17939. var len;
  17940. if (this._selectionOctree) {
  17941. var selection = this._selectionOctree.select(this._frustumPlanes);
  17942. meshes = selection.data;
  17943. len = selection.length;
  17944. }
  17945. else {
  17946. len = this.meshes.length;
  17947. meshes = this.meshes;
  17948. }
  17949. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  17950. var mesh = meshes[meshIndex];
  17951. if (mesh.isBlocked) {
  17952. continue;
  17953. }
  17954. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  17955. if (!mesh.isReady() || !mesh.isEnabled()) {
  17956. continue;
  17957. }
  17958. mesh.computeWorldMatrix();
  17959. // Intersections
  17960. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  17961. this._meshesForIntersections.pushNoDuplicate(mesh);
  17962. }
  17963. // Switch to current LOD
  17964. var meshLOD = mesh.getLOD(this.activeCamera);
  17965. if (!meshLOD) {
  17966. continue;
  17967. }
  17968. mesh._preActivate();
  17969. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  17970. this._activeMeshes.push(mesh);
  17971. this.activeCamera._activeMeshes.push(mesh);
  17972. mesh._activate(this._renderId);
  17973. this._activeMesh(mesh, meshLOD);
  17974. }
  17975. }
  17976. // Particle systems
  17977. this._particlesDuration.beginMonitoring();
  17978. var beforeParticlesDate = BABYLON.Tools.Now;
  17979. if (this.particlesEnabled) {
  17980. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  17981. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  17982. var particleSystem = this.particleSystems[particleIndex];
  17983. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  17984. continue;
  17985. }
  17986. var emitter = particleSystem.emitter;
  17987. if (!emitter.position || emitter.isEnabled()) {
  17988. this._activeParticleSystems.push(particleSystem);
  17989. particleSystem.animate();
  17990. this._renderingManager.dispatchParticles(particleSystem);
  17991. }
  17992. }
  17993. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  17994. }
  17995. this._particlesDuration.endMonitoring(false);
  17996. };
  17997. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  17998. if (mesh.skeleton && this.skeletonsEnabled) {
  17999. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  18000. mesh.skeleton.prepare();
  18001. }
  18002. if (!mesh.computeBonesUsingShaders) {
  18003. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  18004. }
  18005. }
  18006. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  18007. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  18008. }
  18009. if (mesh && mesh.subMeshes) {
  18010. // Submeshes Octrees
  18011. var len;
  18012. var subMeshes;
  18013. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  18014. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  18015. len = intersections.length;
  18016. subMeshes = intersections.data;
  18017. }
  18018. else {
  18019. subMeshes = mesh.subMeshes;
  18020. len = subMeshes.length;
  18021. }
  18022. for (var subIndex = 0; subIndex < len; subIndex++) {
  18023. var subMesh = subMeshes[subIndex];
  18024. this._evaluateSubMesh(subMesh, mesh);
  18025. }
  18026. }
  18027. };
  18028. Scene.prototype.updateTransformMatrix = function (force) {
  18029. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  18030. };
  18031. Scene.prototype._renderForCamera = function (camera) {
  18032. var engine = this._engine;
  18033. var startTime = BABYLON.Tools.Now;
  18034. this.activeCamera = camera;
  18035. if (!this.activeCamera)
  18036. throw new Error("Active camera not set");
  18037. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18038. // Viewport
  18039. engine.setViewport(this.activeCamera.viewport);
  18040. // Camera
  18041. this.resetCachedMaterial();
  18042. this._renderId++;
  18043. this.updateTransformMatrix();
  18044. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  18045. // Meshes
  18046. this._evaluateActiveMeshesDuration.beginMonitoring();
  18047. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  18048. this._evaluateActiveMeshes();
  18049. this._evaluateActiveMeshesDuration.endMonitoring(false);
  18050. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  18051. // Software skinning
  18052. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  18053. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  18054. mesh.applySkeleton(mesh.skeleton);
  18055. }
  18056. // Render targets
  18057. this._renderTargetsDuration.beginMonitoring();
  18058. var needsRestoreFrameBuffer = false;
  18059. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18060. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  18061. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  18062. }
  18063. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  18064. this._intermediateRendering = true;
  18065. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18066. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  18067. var renderTarget = this._renderTargets.data[renderIndex];
  18068. if (renderTarget._shouldRender()) {
  18069. this._renderId++;
  18070. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  18071. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  18072. }
  18073. }
  18074. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18075. this._intermediateRendering = false;
  18076. this._renderId++;
  18077. needsRestoreFrameBuffer = true; // Restore back buffer
  18078. }
  18079. // Render HighlightLayer Texture
  18080. var stencilState = this._engine.getStencilBuffer();
  18081. var renderhighlights = false;
  18082. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  18083. this._intermediateRendering = true;
  18084. for (var i = 0; i < this.highlightLayers.length; i++) {
  18085. var highlightLayer = this.highlightLayers[i];
  18086. if (highlightLayer.shouldRender() &&
  18087. (!highlightLayer.camera ||
  18088. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  18089. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  18090. renderhighlights = true;
  18091. var renderTarget = highlightLayer._mainTexture;
  18092. if (renderTarget._shouldRender()) {
  18093. this._renderId++;
  18094. renderTarget.render(false, false);
  18095. needsRestoreFrameBuffer = true;
  18096. }
  18097. }
  18098. }
  18099. this._intermediateRendering = false;
  18100. this._renderId++;
  18101. }
  18102. if (needsRestoreFrameBuffer) {
  18103. engine.restoreDefaultFramebuffer(); // Restore back buffer
  18104. }
  18105. this._renderTargetsDuration.endMonitoring(false);
  18106. // Prepare Frame
  18107. this.postProcessManager._prepareFrame();
  18108. this._renderDuration.beginMonitoring();
  18109. // Backgrounds
  18110. var layerIndex;
  18111. var layer;
  18112. if (this.layers.length) {
  18113. engine.setDepthBuffer(false);
  18114. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18115. layer = this.layers[layerIndex];
  18116. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  18117. layer.render();
  18118. }
  18119. }
  18120. engine.setDepthBuffer(true);
  18121. }
  18122. // Render
  18123. BABYLON.Tools.StartPerformanceCounter("Main render");
  18124. // Activate HighlightLayer stencil
  18125. if (renderhighlights) {
  18126. this._engine.setStencilBuffer(true);
  18127. }
  18128. this._renderingManager.render(null, null, true, true);
  18129. // Restore HighlightLayer stencil
  18130. if (renderhighlights) {
  18131. this._engine.setStencilBuffer(stencilState);
  18132. }
  18133. BABYLON.Tools.EndPerformanceCounter("Main render");
  18134. // Bounding boxes
  18135. if (this._boundingBoxRenderer) {
  18136. this._boundingBoxRenderer.render();
  18137. }
  18138. // Lens flares
  18139. if (this.lensFlaresEnabled) {
  18140. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18141. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  18142. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  18143. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  18144. lensFlareSystem.render();
  18145. }
  18146. }
  18147. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18148. }
  18149. // Foregrounds
  18150. if (this.layers.length) {
  18151. engine.setDepthBuffer(false);
  18152. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18153. layer = this.layers[layerIndex];
  18154. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  18155. layer.render();
  18156. }
  18157. }
  18158. engine.setDepthBuffer(true);
  18159. }
  18160. // Highlight Layer
  18161. if (renderhighlights) {
  18162. engine.setDepthBuffer(false);
  18163. for (var i = 0; i < this.highlightLayers.length; i++) {
  18164. if (this.highlightLayers[i].shouldRender()) {
  18165. this.highlightLayers[i].render();
  18166. }
  18167. }
  18168. engine.setDepthBuffer(true);
  18169. }
  18170. this._renderDuration.endMonitoring(false);
  18171. // Finalize frame
  18172. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  18173. // Update camera
  18174. this.activeCamera._updateFromScene();
  18175. // Reset some special arrays
  18176. this._renderTargets.reset();
  18177. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  18178. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18179. };
  18180. Scene.prototype._processSubCameras = function (camera) {
  18181. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  18182. this._renderForCamera(camera);
  18183. return;
  18184. }
  18185. // rig cameras
  18186. for (var index = 0; index < camera._rigCameras.length; index++) {
  18187. this._renderForCamera(camera._rigCameras[index]);
  18188. }
  18189. this.activeCamera = camera;
  18190. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  18191. // Update camera
  18192. this.activeCamera._updateFromScene();
  18193. };
  18194. Scene.prototype._checkIntersections = function () {
  18195. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  18196. var sourceMesh = this._meshesForIntersections.data[index];
  18197. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  18198. var action = sourceMesh.actionManager.actions[actionIndex];
  18199. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18200. var parameters = action.getTriggerParameter();
  18201. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  18202. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  18203. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  18204. if (areIntersecting && currentIntersectionInProgress === -1) {
  18205. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  18206. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18207. sourceMesh._intersectionsInProgress.push(otherMesh);
  18208. }
  18209. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18210. sourceMesh._intersectionsInProgress.push(otherMesh);
  18211. }
  18212. }
  18213. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  18214. //They intersected, and now they don't.
  18215. //is this trigger an exit trigger? execute an event.
  18216. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18217. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18218. }
  18219. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  18220. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18221. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  18222. }
  18223. }
  18224. }
  18225. }
  18226. }
  18227. };
  18228. Scene.prototype.render = function () {
  18229. if (this.isDisposed) {
  18230. return;
  18231. }
  18232. this._lastFrameDuration.beginMonitoring();
  18233. this._particlesDuration.fetchNewFrame();
  18234. this._spritesDuration.fetchNewFrame();
  18235. this._activeParticles.fetchNewFrame();
  18236. this._renderDuration.fetchNewFrame();
  18237. this._renderTargetsDuration.fetchNewFrame();
  18238. this._evaluateActiveMeshesDuration.fetchNewFrame();
  18239. this._totalVertices.fetchNewFrame();
  18240. this._activeIndices.fetchNewFrame();
  18241. this._activeBones.fetchNewFrame();
  18242. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  18243. this._meshesForIntersections.reset();
  18244. this.resetCachedMaterial();
  18245. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  18246. // Actions
  18247. if (this.actionManager) {
  18248. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  18249. }
  18250. //Simplification Queue
  18251. if (this.simplificationQueue && !this.simplificationQueue.running) {
  18252. this.simplificationQueue.executeNext();
  18253. }
  18254. if (this._engine.isDeterministicLockStep()) {
  18255. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) / 1000;
  18256. var defaultTimeStep = (60.0 / 1000.0);
  18257. if (this._physicsEngine) {
  18258. defaultTimeStep = this._physicsEngine.getTimeStep();
  18259. }
  18260. var maxSubSteps = this._engine.getLockstepMaxSteps();
  18261. this._timeAccumulator += deltaTime;
  18262. // compute the amount of fixed steps we should have taken since the last step
  18263. var internalSteps = Math.floor(this._timeAccumulator / defaultTimeStep);
  18264. internalSteps = Math.min(internalSteps, maxSubSteps);
  18265. for (this._currentInternalStep = 0; this._currentInternalStep < internalSteps; this._currentInternalStep++) {
  18266. this.onBeforeStepObservable.notifyObservers(this);
  18267. // Animations
  18268. this._animationRatio = defaultTimeStep * (60.0 / 1000.0);
  18269. this._animate();
  18270. // Physics
  18271. if (this._physicsEngine) {
  18272. BABYLON.Tools.StartPerformanceCounter("Physics");
  18273. this._physicsEngine._step(defaultTimeStep);
  18274. BABYLON.Tools.EndPerformanceCounter("Physics");
  18275. }
  18276. this._timeAccumulator -= defaultTimeStep;
  18277. this.onAfterStepObservable.notifyObservers(this);
  18278. this._currentStepId++;
  18279. if ((internalSteps > 1) && (this._currentInternalStep != internalSteps - 1)) {
  18280. // Q: can this be optimized by putting some code in the afterStep callback?
  18281. // I had to put this code here, otherwise mesh attached to bones of another mesh skeleton,
  18282. // would return incorrect positions for internal stepIds (non-rendered steps)
  18283. this._evaluateActiveMeshes();
  18284. }
  18285. }
  18286. }
  18287. else {
  18288. // Animations
  18289. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  18290. this._animationRatio = deltaTime * (60.0 / 1000.0);
  18291. this._animate();
  18292. // Physics
  18293. if (this._physicsEngine) {
  18294. BABYLON.Tools.StartPerformanceCounter("Physics");
  18295. this._physicsEngine._step(deltaTime / 1000.0);
  18296. BABYLON.Tools.EndPerformanceCounter("Physics");
  18297. }
  18298. }
  18299. // Before render
  18300. this.onBeforeRenderObservable.notifyObservers(this);
  18301. // Customs render targets
  18302. this._renderTargetsDuration.beginMonitoring();
  18303. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18304. var engine = this.getEngine();
  18305. var currentActiveCamera = this.activeCamera;
  18306. if (this.renderTargetsEnabled) {
  18307. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18308. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  18309. var renderTarget = this.customRenderTargets[customIndex];
  18310. if (renderTarget._shouldRender()) {
  18311. this._renderId++;
  18312. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  18313. if (!this.activeCamera)
  18314. throw new Error("Active camera not set");
  18315. // Viewport
  18316. engine.setViewport(this.activeCamera.viewport);
  18317. // Camera
  18318. this.updateTransformMatrix();
  18319. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  18320. }
  18321. }
  18322. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18323. this._renderId++;
  18324. }
  18325. // Restore back buffer
  18326. if (this.customRenderTargets.length > 0) {
  18327. engine.restoreDefaultFramebuffer();
  18328. }
  18329. this._renderTargetsDuration.endMonitoring();
  18330. this.activeCamera = currentActiveCamera;
  18331. // Procedural textures
  18332. if (this.proceduralTexturesEnabled) {
  18333. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18334. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  18335. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  18336. if (proceduralTexture._shouldRender()) {
  18337. proceduralTexture.render();
  18338. }
  18339. }
  18340. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18341. }
  18342. // Clear
  18343. if (this.autoClearDepthAndStencil || this.autoClear) {
  18344. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  18345. }
  18346. // Shadows
  18347. if (this.shadowsEnabled) {
  18348. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  18349. var light = this.lights[lightIndex];
  18350. var shadowGenerator = light.getShadowGenerator();
  18351. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  18352. var shadowMap = shadowGenerator.getShadowMap();
  18353. if (shadowMap.getScene().textures.indexOf(shadowMap) !== -1) {
  18354. this._renderTargets.push(shadowMap);
  18355. }
  18356. }
  18357. }
  18358. }
  18359. // Depth renderer
  18360. if (this._depthRenderer) {
  18361. this._renderTargets.push(this._depthRenderer.getDepthMap());
  18362. }
  18363. // Geometry renderer
  18364. if (this._geometryBufferRenderer) {
  18365. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  18366. }
  18367. // RenderPipeline
  18368. if (this._postProcessRenderPipelineManager) {
  18369. this._postProcessRenderPipelineManager.update();
  18370. }
  18371. // Multi-cameras?
  18372. if (this.activeCameras.length > 0) {
  18373. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  18374. if (cameraIndex > 0) {
  18375. this._engine.clear(null, false, true, true);
  18376. }
  18377. this._processSubCameras(this.activeCameras[cameraIndex]);
  18378. }
  18379. }
  18380. else {
  18381. if (!this.activeCamera) {
  18382. throw new Error("No camera defined");
  18383. }
  18384. this._processSubCameras(this.activeCamera);
  18385. }
  18386. // Intersection checks
  18387. this._checkIntersections();
  18388. // Update the audio listener attached to the camera
  18389. if (BABYLON.AudioEngine) {
  18390. this._updateAudioParameters();
  18391. }
  18392. // After render
  18393. if (this.afterRender) {
  18394. this.afterRender();
  18395. }
  18396. this.onAfterRenderObservable.notifyObservers(this);
  18397. // Cleaning
  18398. for (var index = 0; index < this._toBeDisposed.length; index++) {
  18399. this._toBeDisposed.data[index].dispose();
  18400. this._toBeDisposed[index] = null;
  18401. }
  18402. this._toBeDisposed.reset();
  18403. if (this.dumpNextRenderTargets) {
  18404. this.dumpNextRenderTargets = false;
  18405. }
  18406. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  18407. this._lastFrameDuration.endMonitoring();
  18408. this._totalMeshesCounter.addCount(this.meshes.length, true);
  18409. this._totalLightsCounter.addCount(this.lights.length, true);
  18410. this._totalMaterialsCounter.addCount(this.materials.length, true);
  18411. this._totalTexturesCounter.addCount(this.textures.length, true);
  18412. this._activeBones.addCount(0, true);
  18413. this._activeIndices.addCount(0, true);
  18414. this._activeParticles.addCount(0, true);
  18415. };
  18416. Scene.prototype._updateAudioParameters = function () {
  18417. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  18418. return;
  18419. }
  18420. var listeningCamera;
  18421. var audioEngine = BABYLON.Engine.audioEngine;
  18422. if (this.activeCameras.length > 0) {
  18423. listeningCamera = this.activeCameras[0];
  18424. }
  18425. else {
  18426. listeningCamera = this.activeCamera;
  18427. }
  18428. if (listeningCamera && audioEngine.canUseWebAudio) {
  18429. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  18430. // for VR cameras
  18431. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  18432. listeningCamera = listeningCamera.rigCameras[0];
  18433. }
  18434. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  18435. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  18436. cameraDirection.normalize();
  18437. // To avoid some errors on GearVR
  18438. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  18439. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  18440. }
  18441. var i;
  18442. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18443. var sound = this.mainSoundTrack.soundCollection[i];
  18444. if (sound.useCustomAttenuation) {
  18445. sound.updateDistanceFromListener();
  18446. }
  18447. }
  18448. for (i = 0; i < this.soundTracks.length; i++) {
  18449. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18450. sound = this.soundTracks[i].soundCollection[j];
  18451. if (sound.useCustomAttenuation) {
  18452. sound.updateDistanceFromListener();
  18453. }
  18454. }
  18455. }
  18456. }
  18457. };
  18458. Object.defineProperty(Scene.prototype, "audioEnabled", {
  18459. // Audio
  18460. get: function () {
  18461. return this._audioEnabled;
  18462. },
  18463. set: function (value) {
  18464. this._audioEnabled = value;
  18465. if (BABYLON.AudioEngine) {
  18466. if (this._audioEnabled) {
  18467. this._enableAudio();
  18468. }
  18469. else {
  18470. this._disableAudio();
  18471. }
  18472. }
  18473. },
  18474. enumerable: true,
  18475. configurable: true
  18476. });
  18477. Scene.prototype._disableAudio = function () {
  18478. var i;
  18479. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18480. this.mainSoundTrack.soundCollection[i].pause();
  18481. }
  18482. for (i = 0; i < this.soundTracks.length; i++) {
  18483. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18484. this.soundTracks[i].soundCollection[j].pause();
  18485. }
  18486. }
  18487. };
  18488. Scene.prototype._enableAudio = function () {
  18489. var i;
  18490. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18491. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  18492. this.mainSoundTrack.soundCollection[i].play();
  18493. }
  18494. }
  18495. for (i = 0; i < this.soundTracks.length; i++) {
  18496. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18497. if (this.soundTracks[i].soundCollection[j].isPaused) {
  18498. this.soundTracks[i].soundCollection[j].play();
  18499. }
  18500. }
  18501. }
  18502. };
  18503. Object.defineProperty(Scene.prototype, "headphone", {
  18504. get: function () {
  18505. return this._headphone;
  18506. },
  18507. set: function (value) {
  18508. this._headphone = value;
  18509. if (BABYLON.AudioEngine) {
  18510. if (this._headphone) {
  18511. this._switchAudioModeForHeadphones();
  18512. }
  18513. else {
  18514. this._switchAudioModeForNormalSpeakers();
  18515. }
  18516. }
  18517. },
  18518. enumerable: true,
  18519. configurable: true
  18520. });
  18521. Scene.prototype._switchAudioModeForHeadphones = function () {
  18522. this.mainSoundTrack.switchPanningModelToHRTF();
  18523. for (var i = 0; i < this.soundTracks.length; i++) {
  18524. this.soundTracks[i].switchPanningModelToHRTF();
  18525. }
  18526. };
  18527. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  18528. this.mainSoundTrack.switchPanningModelToEqualPower();
  18529. for (var i = 0; i < this.soundTracks.length; i++) {
  18530. this.soundTracks[i].switchPanningModelToEqualPower();
  18531. }
  18532. };
  18533. Scene.prototype.enableDepthRenderer = function () {
  18534. if (this._depthRenderer) {
  18535. return this._depthRenderer;
  18536. }
  18537. this._depthRenderer = new BABYLON.DepthRenderer(this);
  18538. return this._depthRenderer;
  18539. };
  18540. Scene.prototype.disableDepthRenderer = function () {
  18541. if (!this._depthRenderer) {
  18542. return;
  18543. }
  18544. this._depthRenderer.dispose();
  18545. this._depthRenderer = null;
  18546. };
  18547. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  18548. if (ratio === void 0) { ratio = 1; }
  18549. if (this._geometryBufferRenderer) {
  18550. return this._geometryBufferRenderer;
  18551. }
  18552. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  18553. if (!this._geometryBufferRenderer.isSupported) {
  18554. this._geometryBufferRenderer = null;
  18555. }
  18556. return this._geometryBufferRenderer;
  18557. };
  18558. Scene.prototype.disableGeometryBufferRenderer = function () {
  18559. if (!this._geometryBufferRenderer) {
  18560. return;
  18561. }
  18562. this._geometryBufferRenderer.dispose();
  18563. this._geometryBufferRenderer = null;
  18564. };
  18565. Scene.prototype.freezeMaterials = function () {
  18566. for (var i = 0; i < this.materials.length; i++) {
  18567. this.materials[i].freeze();
  18568. }
  18569. };
  18570. Scene.prototype.unfreezeMaterials = function () {
  18571. for (var i = 0; i < this.materials.length; i++) {
  18572. this.materials[i].unfreeze();
  18573. }
  18574. };
  18575. Scene.prototype.dispose = function () {
  18576. this.beforeRender = null;
  18577. this.afterRender = null;
  18578. this.skeletons = [];
  18579. this.morphTargetManagers = [];
  18580. this.importedMeshesFiles = new Array();
  18581. this.resetCachedMaterial();
  18582. if (this._depthRenderer) {
  18583. this._depthRenderer.dispose();
  18584. }
  18585. // Smart arrays
  18586. if (this.activeCamera) {
  18587. this.activeCamera._activeMeshes.dispose();
  18588. this.activeCamera = null;
  18589. }
  18590. this._activeMeshes.dispose();
  18591. this._renderingManager.dispose();
  18592. this._processedMaterials.dispose();
  18593. this._activeParticleSystems.dispose();
  18594. this._activeSkeletons.dispose();
  18595. this._softwareSkinnedMeshes.dispose();
  18596. this._renderTargets.dispose();
  18597. if (this._boundingBoxRenderer) {
  18598. this._boundingBoxRenderer.dispose();
  18599. }
  18600. this._meshesForIntersections.dispose();
  18601. this._toBeDisposed.dispose();
  18602. // Debug layer
  18603. if (this._debugLayer) {
  18604. this._debugLayer.hide();
  18605. }
  18606. // Events
  18607. this.onDisposeObservable.notifyObservers(this);
  18608. this.onDisposeObservable.clear();
  18609. this.onBeforeRenderObservable.clear();
  18610. this.onAfterRenderObservable.clear();
  18611. this.detachControl();
  18612. // Release sounds & sounds tracks
  18613. if (BABYLON.AudioEngine) {
  18614. this.disposeSounds();
  18615. }
  18616. // VR Helper
  18617. if (this.VRHelper) {
  18618. this.VRHelper.dispose();
  18619. }
  18620. // Detach cameras
  18621. var canvas = this._engine.getRenderingCanvas();
  18622. var index;
  18623. for (index = 0; index < this.cameras.length; index++) {
  18624. this.cameras[index].detachControl(canvas);
  18625. }
  18626. // Release lights
  18627. while (this.lights.length) {
  18628. this.lights[0].dispose();
  18629. }
  18630. // Release meshes
  18631. while (this.meshes.length) {
  18632. this.meshes[0].dispose(true);
  18633. }
  18634. // Release cameras
  18635. while (this.cameras.length) {
  18636. this.cameras[0].dispose();
  18637. }
  18638. // Release materials
  18639. if (this.defaultMaterial) {
  18640. this.defaultMaterial.dispose();
  18641. }
  18642. while (this.multiMaterials.length) {
  18643. this.multiMaterials[0].dispose();
  18644. }
  18645. while (this.materials.length) {
  18646. this.materials[0].dispose();
  18647. }
  18648. // Release particles
  18649. while (this.particleSystems.length) {
  18650. this.particleSystems[0].dispose();
  18651. }
  18652. // Release sprites
  18653. while (this.spriteManagers.length) {
  18654. this.spriteManagers[0].dispose();
  18655. }
  18656. // Release layers
  18657. while (this.layers.length) {
  18658. this.layers[0].dispose();
  18659. }
  18660. while (this.highlightLayers.length) {
  18661. this.highlightLayers[0].dispose();
  18662. }
  18663. // Release textures
  18664. while (this.textures.length) {
  18665. this.textures[0].dispose();
  18666. }
  18667. // Release UBO
  18668. this._sceneUbo.dispose();
  18669. // Post-processes
  18670. this.postProcessManager.dispose();
  18671. // Physics
  18672. if (this._physicsEngine) {
  18673. this.disablePhysicsEngine();
  18674. }
  18675. // Remove from engine
  18676. index = this._engine.scenes.indexOf(this);
  18677. if (index > -1) {
  18678. this._engine.scenes.splice(index, 1);
  18679. }
  18680. this._engine.wipeCaches();
  18681. this._engine = null;
  18682. this.defaultMaterial = null;
  18683. this.multiMaterials = null;
  18684. this.materials = null;
  18685. };
  18686. Object.defineProperty(Scene.prototype, "isDisposed", {
  18687. get: function () {
  18688. return !this._engine;
  18689. },
  18690. enumerable: true,
  18691. configurable: true
  18692. });
  18693. // Release sounds & sounds tracks
  18694. Scene.prototype.disposeSounds = function () {
  18695. this.mainSoundTrack.dispose();
  18696. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  18697. this.soundTracks[scIndex].dispose();
  18698. }
  18699. };
  18700. // Octrees
  18701. Scene.prototype.getWorldExtends = function () {
  18702. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18703. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18704. for (var index = 0; index < this.meshes.length; index++) {
  18705. var mesh = this.meshes[index];
  18706. mesh.computeWorldMatrix(true);
  18707. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  18708. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  18709. BABYLON.Tools.CheckExtends(minBox, min, max);
  18710. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18711. }
  18712. return {
  18713. min: min,
  18714. max: max
  18715. };
  18716. };
  18717. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  18718. if (maxCapacity === void 0) { maxCapacity = 64; }
  18719. if (maxDepth === void 0) { maxDepth = 2; }
  18720. if (!this._selectionOctree) {
  18721. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  18722. }
  18723. var worldExtends = this.getWorldExtends();
  18724. // Update octree
  18725. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  18726. return this._selectionOctree;
  18727. };
  18728. // Picking
  18729. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  18730. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  18731. var engine = this._engine;
  18732. if (!camera) {
  18733. if (!this.activeCamera)
  18734. throw new Error("Active camera not set");
  18735. camera = this.activeCamera;
  18736. }
  18737. var cameraViewport = camera.viewport;
  18738. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18739. // Moving coordinates to local viewport world
  18740. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18741. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18742. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  18743. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  18744. };
  18745. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  18746. if (!BABYLON.PickingInfo) {
  18747. return null;
  18748. }
  18749. var engine = this._engine;
  18750. if (!camera) {
  18751. if (!this.activeCamera)
  18752. throw new Error("Active camera not set");
  18753. camera = this.activeCamera;
  18754. }
  18755. var cameraViewport = camera.viewport;
  18756. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18757. var identity = BABYLON.Matrix.Identity();
  18758. // Moving coordinates to local viewport world
  18759. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18760. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18761. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  18762. };
  18763. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  18764. if (!BABYLON.PickingInfo) {
  18765. return null;
  18766. }
  18767. var pickingInfo = null;
  18768. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18769. var mesh = this.meshes[meshIndex];
  18770. if (predicate) {
  18771. if (!predicate(mesh)) {
  18772. continue;
  18773. }
  18774. }
  18775. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18776. continue;
  18777. }
  18778. var world = mesh.getWorldMatrix();
  18779. var ray = rayFunction(world);
  18780. var result = mesh.intersects(ray, fastCheck);
  18781. if (!result || !result.hit)
  18782. continue;
  18783. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18784. continue;
  18785. pickingInfo = result;
  18786. if (fastCheck) {
  18787. break;
  18788. }
  18789. }
  18790. return pickingInfo || new BABYLON.PickingInfo();
  18791. };
  18792. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  18793. if (!BABYLON.PickingInfo) {
  18794. return null;
  18795. }
  18796. var pickingInfos = new Array();
  18797. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18798. var mesh = this.meshes[meshIndex];
  18799. if (predicate) {
  18800. if (!predicate(mesh)) {
  18801. continue;
  18802. }
  18803. }
  18804. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18805. continue;
  18806. }
  18807. var world = mesh.getWorldMatrix();
  18808. var ray = rayFunction(world);
  18809. var result = mesh.intersects(ray, false);
  18810. if (!result || !result.hit)
  18811. continue;
  18812. pickingInfos.push(result);
  18813. }
  18814. return pickingInfos;
  18815. };
  18816. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  18817. if (!BABYLON.PickingInfo) {
  18818. return null;
  18819. }
  18820. var pickingInfo = null;
  18821. camera = camera || this.activeCamera;
  18822. if (this.spriteManagers.length > 0) {
  18823. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  18824. var spriteManager = this.spriteManagers[spriteIndex];
  18825. if (!spriteManager.isPickable) {
  18826. continue;
  18827. }
  18828. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  18829. if (!result || !result.hit)
  18830. continue;
  18831. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18832. continue;
  18833. pickingInfo = result;
  18834. if (fastCheck) {
  18835. break;
  18836. }
  18837. }
  18838. }
  18839. return pickingInfo || new BABYLON.PickingInfo();
  18840. };
  18841. /** Launch a ray to try to pick a mesh in the scene
  18842. * @param x position on screen
  18843. * @param y position on screen
  18844. * @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
  18845. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  18846. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  18847. */
  18848. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  18849. var _this = this;
  18850. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  18851. };
  18852. /** Launch a ray to try to pick a sprite in the scene
  18853. * @param x position on screen
  18854. * @param y position on screen
  18855. * @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
  18856. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  18857. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  18858. */
  18859. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  18860. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  18861. };
  18862. /** Use the given ray to pick a mesh in the scene
  18863. * @param ray The ray to use to pick meshes
  18864. * @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
  18865. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  18866. */
  18867. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  18868. var _this = this;
  18869. return this._internalPick(function (world) {
  18870. if (!_this._pickWithRayInverseMatrix) {
  18871. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18872. }
  18873. world.invertToRef(_this._pickWithRayInverseMatrix);
  18874. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18875. }, predicate, fastCheck);
  18876. };
  18877. /**
  18878. * Launch a ray to try to pick a mesh in the scene
  18879. * @param x X position on screen
  18880. * @param y Y position on screen
  18881. * @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
  18882. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  18883. */
  18884. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  18885. var _this = this;
  18886. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  18887. };
  18888. /**
  18889. * Launch a ray to try to pick a mesh in the scene
  18890. * @param ray Ray to use
  18891. * @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
  18892. */
  18893. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  18894. var _this = this;
  18895. return this._internalMultiPick(function (world) {
  18896. if (!_this._pickWithRayInverseMatrix) {
  18897. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18898. }
  18899. world.invertToRef(_this._pickWithRayInverseMatrix);
  18900. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18901. }, predicate);
  18902. };
  18903. Scene.prototype.setPointerOverMesh = function (mesh) {
  18904. if (this._pointerOverMesh === mesh) {
  18905. return;
  18906. }
  18907. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18908. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18909. }
  18910. this._pointerOverMesh = mesh;
  18911. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18912. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18913. }
  18914. };
  18915. Scene.prototype.getPointerOverMesh = function () {
  18916. return this._pointerOverMesh;
  18917. };
  18918. Scene.prototype.setPointerOverSprite = function (sprite) {
  18919. if (this._pointerOverSprite === sprite) {
  18920. return;
  18921. }
  18922. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18923. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18924. }
  18925. this._pointerOverSprite = sprite;
  18926. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18927. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18928. }
  18929. };
  18930. Scene.prototype.getPointerOverSprite = function () {
  18931. return this._pointerOverSprite;
  18932. };
  18933. // Physics
  18934. Scene.prototype.getPhysicsEngine = function () {
  18935. return this._physicsEngine;
  18936. };
  18937. /**
  18938. * Enables physics to the current scene
  18939. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  18940. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  18941. * @return {boolean} was the physics engine initialized
  18942. */
  18943. Scene.prototype.enablePhysics = function (gravity, plugin) {
  18944. if (this._physicsEngine) {
  18945. return true;
  18946. }
  18947. try {
  18948. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  18949. return true;
  18950. }
  18951. catch (e) {
  18952. BABYLON.Tools.Error(e.message);
  18953. return false;
  18954. }
  18955. };
  18956. Scene.prototype.disablePhysicsEngine = function () {
  18957. if (!this._physicsEngine) {
  18958. return;
  18959. }
  18960. this._physicsEngine.dispose();
  18961. this._physicsEngine = undefined;
  18962. };
  18963. Scene.prototype.isPhysicsEnabled = function () {
  18964. return this._physicsEngine !== undefined;
  18965. };
  18966. Scene.prototype.deleteCompoundImpostor = function (compound) {
  18967. var mesh = compound.parts[0].mesh;
  18968. mesh.physicsImpostor.dispose();
  18969. mesh.physicsImpostor = null;
  18970. };
  18971. // Misc.
  18972. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  18973. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  18974. if (replace === void 0) { replace = false; }
  18975. if (attachCameraControls === void 0) { attachCameraControls = false; }
  18976. // Dispose existing camera or light in replace mode.
  18977. if (replace) {
  18978. if (this.activeCamera) {
  18979. this.activeCamera.dispose();
  18980. this.activeCamera = null;
  18981. }
  18982. if (this.lights) {
  18983. for (var i = 0; i < this.lights.length; i++) {
  18984. this.lights[i].dispose();
  18985. }
  18986. }
  18987. }
  18988. // Light
  18989. if (this.lights.length === 0) {
  18990. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  18991. }
  18992. // Camera
  18993. if (!this.activeCamera) {
  18994. var worldExtends = this.getWorldExtends();
  18995. var worldSize = worldExtends.max.subtract(worldExtends.min);
  18996. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  18997. var camera;
  18998. var radius = worldSize.length() * 1.5;
  18999. if (createArcRotateCamera) {
  19000. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  19001. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  19002. arcRotateCamera.wheelPrecision = 100 / radius;
  19003. camera = arcRotateCamera;
  19004. }
  19005. else {
  19006. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  19007. freeCamera.setTarget(worldCenter);
  19008. camera = freeCamera;
  19009. }
  19010. camera.minZ = radius * 0.01;
  19011. camera.maxZ = radius * 100;
  19012. camera.speed = radius * 0.2;
  19013. this.activeCamera = camera;
  19014. if (attachCameraControls) {
  19015. camera.attachControl(this.getEngine().getRenderingCanvas());
  19016. }
  19017. }
  19018. };
  19019. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  19020. if (pbr === void 0) { pbr = false; }
  19021. if (scale === void 0) { scale = 1000; }
  19022. if (blur === void 0) { blur = 0; }
  19023. if (environmentTexture) {
  19024. this.environmentTexture = environmentTexture;
  19025. }
  19026. if (!this.environmentTexture) {
  19027. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  19028. return;
  19029. }
  19030. // Skybox
  19031. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  19032. if (pbr) {
  19033. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  19034. hdrSkyboxMaterial.backFaceCulling = false;
  19035. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  19036. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  19037. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  19038. hdrSkyboxMaterial.disableLighting = true;
  19039. hdrSkyboxMaterial.twoSidedLighting = true;
  19040. hdrSkybox.infiniteDistance = true;
  19041. hdrSkybox.material = hdrSkyboxMaterial;
  19042. }
  19043. else {
  19044. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  19045. skyboxMaterial.backFaceCulling = false;
  19046. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  19047. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  19048. skyboxMaterial.disableLighting = true;
  19049. hdrSkybox.infiniteDistance = true;
  19050. hdrSkybox.material = skyboxMaterial;
  19051. }
  19052. return hdrSkybox;
  19053. };
  19054. Scene.prototype.createDefaultVRExperience = function () {
  19055. this.VRHelper = new BABYLON.VRExperienceHelper(this, null);
  19056. };
  19057. // Tags
  19058. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  19059. if (tagsQuery === undefined) {
  19060. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  19061. return list;
  19062. }
  19063. var listByTags = [];
  19064. forEach = forEach || (function (item) { return; });
  19065. for (var i in list) {
  19066. var item = list[i];
  19067. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  19068. listByTags.push(item);
  19069. forEach(item);
  19070. }
  19071. }
  19072. return listByTags;
  19073. };
  19074. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  19075. return this._getByTags(this.meshes, tagsQuery, forEach);
  19076. };
  19077. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  19078. return this._getByTags(this.cameras, tagsQuery, forEach);
  19079. };
  19080. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  19081. return this._getByTags(this.lights, tagsQuery, forEach);
  19082. };
  19083. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  19084. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  19085. };
  19086. /**
  19087. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  19088. * This allowed control for front to back rendering or reversly depending of the special needs.
  19089. *
  19090. * @param renderingGroupId The rendering group id corresponding to its index
  19091. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  19092. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  19093. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  19094. */
  19095. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19096. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19097. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19098. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19099. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  19100. };
  19101. /**
  19102. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19103. *
  19104. * @param renderingGroupId The rendering group id corresponding to its index
  19105. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19106. * @param depth Automatically clears depth between groups if true and autoClear is true.
  19107. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  19108. */
  19109. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  19110. if (depth === void 0) { depth = true; }
  19111. if (stencil === void 0) { stencil = true; }
  19112. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  19113. };
  19114. /**
  19115. * Will flag all materials as dirty to trigger new shader compilation
  19116. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  19117. */
  19118. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  19119. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  19120. var material = _a[_i];
  19121. if (predicate && !predicate(material)) {
  19122. continue;
  19123. }
  19124. material.markAsDirty(flag);
  19125. }
  19126. };
  19127. return Scene;
  19128. }());
  19129. // Statics
  19130. Scene._FOGMODE_NONE = 0;
  19131. Scene._FOGMODE_EXP = 1;
  19132. Scene._FOGMODE_EXP2 = 2;
  19133. Scene._FOGMODE_LINEAR = 3;
  19134. Scene.MinDeltaTime = 1.0;
  19135. Scene.MaxDeltaTime = 1000.0;
  19136. /** The distance in pixel that you have to move to prevent some events */
  19137. Scene.DragMovementThreshold = 10; // in pixels
  19138. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  19139. Scene.LongPressDelay = 500; // in milliseconds
  19140. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  19141. Scene.DoubleClickDelay = 300; // in milliseconds
  19142. /** If you need to check double click without raising a single click at first click, enable this flag */
  19143. Scene.ExclusiveDoubleClickMode = false;
  19144. BABYLON.Scene = Scene;
  19145. })(BABYLON || (BABYLON = {}));
  19146. //# sourceMappingURL=babylon.scene.js.map
  19147. var BABYLON;
  19148. (function (BABYLON) {
  19149. var Buffer = (function () {
  19150. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  19151. if (engine instanceof BABYLON.Mesh) {
  19152. this._engine = engine.getScene().getEngine();
  19153. }
  19154. else {
  19155. this._engine = engine;
  19156. }
  19157. this._updatable = updatable;
  19158. this._data = data;
  19159. this._strideSize = stride;
  19160. if (!postponeInternalCreation) {
  19161. this.create();
  19162. }
  19163. this._instanced = instanced;
  19164. this._instanceDivisor = instanced ? 1 : 0;
  19165. }
  19166. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  19167. // a lot of these parameters are ignored as they are overriden by the buffer
  19168. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  19169. };
  19170. // Properties
  19171. Buffer.prototype.isUpdatable = function () {
  19172. return this._updatable;
  19173. };
  19174. Buffer.prototype.getData = function () {
  19175. return this._data;
  19176. };
  19177. Buffer.prototype.getBuffer = function () {
  19178. return this._buffer;
  19179. };
  19180. Buffer.prototype.getStrideSize = function () {
  19181. return this._strideSize;
  19182. };
  19183. Buffer.prototype.getIsInstanced = function () {
  19184. return this._instanced;
  19185. };
  19186. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  19187. get: function () {
  19188. return this._instanceDivisor;
  19189. },
  19190. set: function (value) {
  19191. this._instanceDivisor = value;
  19192. if (value == 0) {
  19193. this._instanced = false;
  19194. }
  19195. else {
  19196. this._instanced = true;
  19197. }
  19198. },
  19199. enumerable: true,
  19200. configurable: true
  19201. });
  19202. // Methods
  19203. Buffer.prototype.create = function (data) {
  19204. if (!data && this._buffer) {
  19205. return; // nothing to do
  19206. }
  19207. data = data || this._data;
  19208. if (!this._buffer) {
  19209. if (this._updatable) {
  19210. this._buffer = this._engine.createDynamicVertexBuffer(data);
  19211. this._data = data;
  19212. }
  19213. else {
  19214. this._buffer = this._engine.createVertexBuffer(data);
  19215. }
  19216. }
  19217. else if (this._updatable) {
  19218. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  19219. this._data = data;
  19220. }
  19221. };
  19222. Buffer.prototype.update = function (data) {
  19223. this.create(data);
  19224. };
  19225. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  19226. if (!this._buffer) {
  19227. return;
  19228. }
  19229. if (this._updatable) {
  19230. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  19231. this._data = null;
  19232. }
  19233. };
  19234. Buffer.prototype.dispose = function () {
  19235. if (!this._buffer) {
  19236. return;
  19237. }
  19238. if (this._engine._releaseBuffer(this._buffer)) {
  19239. this._buffer = null;
  19240. }
  19241. };
  19242. return Buffer;
  19243. }());
  19244. BABYLON.Buffer = Buffer;
  19245. })(BABYLON || (BABYLON = {}));
  19246. //# sourceMappingURL=babylon.buffer.js.map
  19247. var BABYLON;
  19248. (function (BABYLON) {
  19249. var VertexBuffer = (function () {
  19250. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  19251. if (!stride) {
  19252. // Deduce stride from kind
  19253. switch (kind) {
  19254. case VertexBuffer.PositionKind:
  19255. stride = 3;
  19256. break;
  19257. case VertexBuffer.NormalKind:
  19258. stride = 3;
  19259. break;
  19260. case VertexBuffer.UVKind:
  19261. case VertexBuffer.UV2Kind:
  19262. case VertexBuffer.UV3Kind:
  19263. case VertexBuffer.UV4Kind:
  19264. case VertexBuffer.UV5Kind:
  19265. case VertexBuffer.UV6Kind:
  19266. stride = 2;
  19267. break;
  19268. case VertexBuffer.TangentKind:
  19269. case VertexBuffer.ColorKind:
  19270. stride = 4;
  19271. break;
  19272. case VertexBuffer.MatricesIndicesKind:
  19273. case VertexBuffer.MatricesIndicesExtraKind:
  19274. stride = 4;
  19275. break;
  19276. case VertexBuffer.MatricesWeightsKind:
  19277. case VertexBuffer.MatricesWeightsExtraKind:
  19278. stride = 4;
  19279. break;
  19280. }
  19281. }
  19282. if (data instanceof BABYLON.Buffer) {
  19283. if (!stride) {
  19284. stride = data.getStrideSize();
  19285. }
  19286. this._buffer = data;
  19287. this._ownsBuffer = false;
  19288. }
  19289. else {
  19290. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  19291. this._ownsBuffer = true;
  19292. }
  19293. this._stride = stride;
  19294. this._offset = offset ? offset : 0;
  19295. this._size = size ? size : stride;
  19296. this._kind = kind;
  19297. }
  19298. /**
  19299. * Returns the kind of the VertexBuffer (string).
  19300. */
  19301. VertexBuffer.prototype.getKind = function () {
  19302. return this._kind;
  19303. };
  19304. // Properties
  19305. /**
  19306. * Boolean : is the VertexBuffer updatable ?
  19307. */
  19308. VertexBuffer.prototype.isUpdatable = function () {
  19309. return this._buffer.isUpdatable();
  19310. };
  19311. /**
  19312. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  19313. */
  19314. VertexBuffer.prototype.getData = function () {
  19315. return this._buffer.getData();
  19316. };
  19317. /**
  19318. * Returns the WebGLBuffer associated to the VertexBuffer.
  19319. */
  19320. VertexBuffer.prototype.getBuffer = function () {
  19321. return this._buffer.getBuffer();
  19322. };
  19323. /**
  19324. * Returns the stride of the VertexBuffer (integer).
  19325. */
  19326. VertexBuffer.prototype.getStrideSize = function () {
  19327. return this._stride;
  19328. };
  19329. /**
  19330. * Returns the offset (integer).
  19331. */
  19332. VertexBuffer.prototype.getOffset = function () {
  19333. return this._offset;
  19334. };
  19335. /**
  19336. * Returns the VertexBuffer total size (integer).
  19337. */
  19338. VertexBuffer.prototype.getSize = function () {
  19339. return this._size;
  19340. };
  19341. /**
  19342. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  19343. */
  19344. VertexBuffer.prototype.getIsInstanced = function () {
  19345. return this._buffer.getIsInstanced();
  19346. };
  19347. /**
  19348. * Returns the instancing divisor, zero for non-instanced (integer).
  19349. */
  19350. VertexBuffer.prototype.getInstanceDivisor = function () {
  19351. return this._buffer.instanceDivisor;
  19352. };
  19353. // Methods
  19354. /**
  19355. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  19356. * Returns the created WebGLBuffer.
  19357. */
  19358. VertexBuffer.prototype.create = function (data) {
  19359. return this._buffer.create(data);
  19360. };
  19361. /**
  19362. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  19363. * Returns the updated WebGLBuffer.
  19364. */
  19365. VertexBuffer.prototype.update = function (data) {
  19366. return this._buffer.update(data);
  19367. };
  19368. /**
  19369. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  19370. * Returns the directly updated WebGLBuffer.
  19371. */
  19372. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  19373. return this._buffer.updateDirectly(data, offset);
  19374. };
  19375. /**
  19376. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  19377. */
  19378. VertexBuffer.prototype.dispose = function () {
  19379. if (this._ownsBuffer) {
  19380. this._buffer.dispose();
  19381. }
  19382. };
  19383. Object.defineProperty(VertexBuffer, "PositionKind", {
  19384. get: function () {
  19385. return VertexBuffer._PositionKind;
  19386. },
  19387. enumerable: true,
  19388. configurable: true
  19389. });
  19390. Object.defineProperty(VertexBuffer, "NormalKind", {
  19391. get: function () {
  19392. return VertexBuffer._NormalKind;
  19393. },
  19394. enumerable: true,
  19395. configurable: true
  19396. });
  19397. Object.defineProperty(VertexBuffer, "TangentKind", {
  19398. get: function () {
  19399. return VertexBuffer._TangentKind;
  19400. },
  19401. enumerable: true,
  19402. configurable: true
  19403. });
  19404. Object.defineProperty(VertexBuffer, "UVKind", {
  19405. get: function () {
  19406. return VertexBuffer._UVKind;
  19407. },
  19408. enumerable: true,
  19409. configurable: true
  19410. });
  19411. Object.defineProperty(VertexBuffer, "UV2Kind", {
  19412. get: function () {
  19413. return VertexBuffer._UV2Kind;
  19414. },
  19415. enumerable: true,
  19416. configurable: true
  19417. });
  19418. Object.defineProperty(VertexBuffer, "UV3Kind", {
  19419. get: function () {
  19420. return VertexBuffer._UV3Kind;
  19421. },
  19422. enumerable: true,
  19423. configurable: true
  19424. });
  19425. Object.defineProperty(VertexBuffer, "UV4Kind", {
  19426. get: function () {
  19427. return VertexBuffer._UV4Kind;
  19428. },
  19429. enumerable: true,
  19430. configurable: true
  19431. });
  19432. Object.defineProperty(VertexBuffer, "UV5Kind", {
  19433. get: function () {
  19434. return VertexBuffer._UV5Kind;
  19435. },
  19436. enumerable: true,
  19437. configurable: true
  19438. });
  19439. Object.defineProperty(VertexBuffer, "UV6Kind", {
  19440. get: function () {
  19441. return VertexBuffer._UV6Kind;
  19442. },
  19443. enumerable: true,
  19444. configurable: true
  19445. });
  19446. Object.defineProperty(VertexBuffer, "ColorKind", {
  19447. get: function () {
  19448. return VertexBuffer._ColorKind;
  19449. },
  19450. enumerable: true,
  19451. configurable: true
  19452. });
  19453. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  19454. get: function () {
  19455. return VertexBuffer._MatricesIndicesKind;
  19456. },
  19457. enumerable: true,
  19458. configurable: true
  19459. });
  19460. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  19461. get: function () {
  19462. return VertexBuffer._MatricesWeightsKind;
  19463. },
  19464. enumerable: true,
  19465. configurable: true
  19466. });
  19467. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  19468. get: function () {
  19469. return VertexBuffer._MatricesIndicesExtraKind;
  19470. },
  19471. enumerable: true,
  19472. configurable: true
  19473. });
  19474. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  19475. get: function () {
  19476. return VertexBuffer._MatricesWeightsExtraKind;
  19477. },
  19478. enumerable: true,
  19479. configurable: true
  19480. });
  19481. return VertexBuffer;
  19482. }());
  19483. // Enums
  19484. VertexBuffer._PositionKind = "position";
  19485. VertexBuffer._NormalKind = "normal";
  19486. VertexBuffer._TangentKind = "tangent";
  19487. VertexBuffer._UVKind = "uv";
  19488. VertexBuffer._UV2Kind = "uv2";
  19489. VertexBuffer._UV3Kind = "uv3";
  19490. VertexBuffer._UV4Kind = "uv4";
  19491. VertexBuffer._UV5Kind = "uv5";
  19492. VertexBuffer._UV6Kind = "uv6";
  19493. VertexBuffer._ColorKind = "color";
  19494. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  19495. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  19496. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  19497. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  19498. BABYLON.VertexBuffer = VertexBuffer;
  19499. })(BABYLON || (BABYLON = {}));
  19500. //# sourceMappingURL=babylon.vertexBuffer.js.map
  19501. var BABYLON;
  19502. (function (BABYLON) {
  19503. var BaseTexture = (function () {
  19504. function BaseTexture(scene) {
  19505. this._hasAlpha = false;
  19506. this.getAlphaFromRGB = false;
  19507. this.level = 1;
  19508. this.coordinatesIndex = 0;
  19509. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  19510. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  19511. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  19512. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  19513. this.isCube = false;
  19514. this.gammaSpace = true;
  19515. this.invertZ = false;
  19516. this.lodLevelInAlpha = false;
  19517. this.lodGenerationOffset = 0.0;
  19518. this.lodGenerationScale = 0.8;
  19519. this.isRenderTarget = false;
  19520. this.animations = new Array();
  19521. /**
  19522. * An event triggered when the texture is disposed.
  19523. * @type {BABYLON.Observable}
  19524. */
  19525. this.onDisposeObservable = new BABYLON.Observable();
  19526. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19527. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  19528. this._scene.textures.push(this);
  19529. this._uid = null;
  19530. }
  19531. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  19532. get: function () {
  19533. return this._hasAlpha;
  19534. },
  19535. set: function (value) {
  19536. if (this._hasAlpha === value) {
  19537. return;
  19538. }
  19539. this._hasAlpha = value;
  19540. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19541. },
  19542. enumerable: true,
  19543. configurable: true
  19544. });
  19545. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  19546. get: function () {
  19547. return this._coordinatesMode;
  19548. },
  19549. set: function (value) {
  19550. if (this._coordinatesMode === value) {
  19551. return;
  19552. }
  19553. this._coordinatesMode = value;
  19554. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19555. },
  19556. enumerable: true,
  19557. configurable: true
  19558. });
  19559. Object.defineProperty(BaseTexture.prototype, "uid", {
  19560. get: function () {
  19561. if (!this._uid) {
  19562. this._uid = BABYLON.Tools.RandomId();
  19563. }
  19564. return this._uid;
  19565. },
  19566. enumerable: true,
  19567. configurable: true
  19568. });
  19569. BaseTexture.prototype.toString = function () {
  19570. return this.name;
  19571. };
  19572. BaseTexture.prototype.getClassName = function () {
  19573. return "BaseTexture";
  19574. };
  19575. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  19576. set: function (callback) {
  19577. if (this._onDisposeObserver) {
  19578. this.onDisposeObservable.remove(this._onDisposeObserver);
  19579. }
  19580. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  19581. },
  19582. enumerable: true,
  19583. configurable: true
  19584. });
  19585. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  19586. get: function () {
  19587. return true;
  19588. },
  19589. enumerable: true,
  19590. configurable: true
  19591. });
  19592. BaseTexture.prototype.getScene = function () {
  19593. return this._scene;
  19594. };
  19595. BaseTexture.prototype.getTextureMatrix = function () {
  19596. return null;
  19597. };
  19598. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  19599. return null;
  19600. };
  19601. BaseTexture.prototype.getInternalTexture = function () {
  19602. return this._texture;
  19603. };
  19604. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  19605. return !this.isBlocking || this.isReady();
  19606. };
  19607. BaseTexture.prototype.isReady = function () {
  19608. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19609. this.delayLoad();
  19610. return false;
  19611. }
  19612. if (this._texture) {
  19613. return this._texture.isReady;
  19614. }
  19615. return false;
  19616. };
  19617. BaseTexture.prototype.getSize = function () {
  19618. if (this._texture._width) {
  19619. return new BABYLON.Size(this._texture._width, this._texture._height);
  19620. }
  19621. if (this._texture._size) {
  19622. return new BABYLON.Size(this._texture._size, this._texture._size);
  19623. }
  19624. return BABYLON.Size.Zero();
  19625. };
  19626. BaseTexture.prototype.getBaseSize = function () {
  19627. if (!this.isReady() || !this._texture)
  19628. return BABYLON.Size.Zero();
  19629. if (this._texture._size) {
  19630. return new BABYLON.Size(this._texture._size, this._texture._size);
  19631. }
  19632. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  19633. };
  19634. BaseTexture.prototype.scale = function (ratio) {
  19635. };
  19636. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  19637. get: function () {
  19638. return false;
  19639. },
  19640. enumerable: true,
  19641. configurable: true
  19642. });
  19643. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  19644. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  19645. for (var index = 0; index < texturesCache.length; index++) {
  19646. var texturesCacheEntry = texturesCache[index];
  19647. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  19648. texturesCache.splice(index, 1);
  19649. return;
  19650. }
  19651. }
  19652. };
  19653. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  19654. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  19655. for (var index = 0; index < texturesCache.length; index++) {
  19656. var texturesCacheEntry = texturesCache[index];
  19657. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  19658. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  19659. texturesCacheEntry.references++;
  19660. return texturesCacheEntry;
  19661. }
  19662. }
  19663. }
  19664. return null;
  19665. };
  19666. BaseTexture.prototype.delayLoad = function () {
  19667. };
  19668. BaseTexture.prototype.clone = function () {
  19669. return null;
  19670. };
  19671. Object.defineProperty(BaseTexture.prototype, "textureType", {
  19672. get: function () {
  19673. if (!this._texture) {
  19674. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  19675. }
  19676. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  19677. },
  19678. enumerable: true,
  19679. configurable: true
  19680. });
  19681. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  19682. get: function () {
  19683. if (!this._texture) {
  19684. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  19685. }
  19686. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  19687. },
  19688. enumerable: true,
  19689. configurable: true
  19690. });
  19691. BaseTexture.prototype.readPixels = function (faceIndex) {
  19692. if (faceIndex === void 0) { faceIndex = 0; }
  19693. if (!this._texture) {
  19694. return null;
  19695. }
  19696. var size = this.getSize();
  19697. var engine = this.getScene().getEngine();
  19698. if (this._texture.isCube) {
  19699. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  19700. }
  19701. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  19702. };
  19703. BaseTexture.prototype.releaseInternalTexture = function () {
  19704. if (this._texture) {
  19705. this._scene.getEngine().releaseInternalTexture(this._texture);
  19706. delete this._texture;
  19707. }
  19708. };
  19709. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  19710. get: function () {
  19711. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  19712. return null;
  19713. }
  19714. if (!this._texture._sphericalPolynomial) {
  19715. this._texture._sphericalPolynomial =
  19716. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  19717. }
  19718. return this._texture._sphericalPolynomial;
  19719. },
  19720. set: function (value) {
  19721. if (this._texture) {
  19722. this._texture._sphericalPolynomial = value;
  19723. }
  19724. },
  19725. enumerable: true,
  19726. configurable: true
  19727. });
  19728. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  19729. get: function () {
  19730. if (this._texture) {
  19731. return this._texture._lodTextureHigh;
  19732. }
  19733. return null;
  19734. },
  19735. enumerable: true,
  19736. configurable: true
  19737. });
  19738. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  19739. get: function () {
  19740. if (this._texture) {
  19741. return this._texture._lodTextureMid;
  19742. }
  19743. return null;
  19744. },
  19745. enumerable: true,
  19746. configurable: true
  19747. });
  19748. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  19749. get: function () {
  19750. if (this._texture) {
  19751. return this._texture._lodTextureLow;
  19752. }
  19753. return null;
  19754. },
  19755. enumerable: true,
  19756. configurable: true
  19757. });
  19758. BaseTexture.prototype.dispose = function () {
  19759. // Animations
  19760. this.getScene().stopAnimation(this);
  19761. // Remove from scene
  19762. this._scene._removePendingData(this);
  19763. var index = this._scene.textures.indexOf(this);
  19764. if (index >= 0) {
  19765. this._scene.textures.splice(index, 1);
  19766. }
  19767. if (this._texture === undefined) {
  19768. return;
  19769. }
  19770. // Release
  19771. this.releaseInternalTexture();
  19772. // Callback
  19773. this.onDisposeObservable.notifyObservers(this);
  19774. this.onDisposeObservable.clear();
  19775. };
  19776. BaseTexture.prototype.serialize = function () {
  19777. if (!this.name) {
  19778. return null;
  19779. }
  19780. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19781. // Animations
  19782. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19783. return serializationObject;
  19784. };
  19785. BaseTexture.WhenAllReady = function (textures, callback) {
  19786. var numRemaining = textures.length;
  19787. if (numRemaining === 0) {
  19788. callback();
  19789. return;
  19790. }
  19791. var _loop_1 = function () {
  19792. texture = textures[i];
  19793. if (texture.isReady()) {
  19794. if (--numRemaining === 0) {
  19795. callback();
  19796. }
  19797. }
  19798. else {
  19799. onLoadObservable = texture.onLoadObservable;
  19800. var onLoadCallback_1 = function () {
  19801. onLoadObservable.removeCallback(onLoadCallback_1);
  19802. if (--numRemaining === 0) {
  19803. callback();
  19804. }
  19805. };
  19806. onLoadObservable.add(onLoadCallback_1);
  19807. }
  19808. };
  19809. var texture, onLoadObservable;
  19810. for (var i = 0; i < textures.length; i++) {
  19811. _loop_1();
  19812. }
  19813. };
  19814. return BaseTexture;
  19815. }());
  19816. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  19817. __decorate([
  19818. BABYLON.serialize()
  19819. ], BaseTexture.prototype, "name", void 0);
  19820. __decorate([
  19821. BABYLON.serialize("hasAlpha")
  19822. ], BaseTexture.prototype, "_hasAlpha", void 0);
  19823. __decorate([
  19824. BABYLON.serialize()
  19825. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  19826. __decorate([
  19827. BABYLON.serialize()
  19828. ], BaseTexture.prototype, "level", void 0);
  19829. __decorate([
  19830. BABYLON.serialize()
  19831. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  19832. __decorate([
  19833. BABYLON.serialize("coordinatesMode")
  19834. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  19835. __decorate([
  19836. BABYLON.serialize()
  19837. ], BaseTexture.prototype, "wrapU", void 0);
  19838. __decorate([
  19839. BABYLON.serialize()
  19840. ], BaseTexture.prototype, "wrapV", void 0);
  19841. __decorate([
  19842. BABYLON.serialize()
  19843. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  19844. __decorate([
  19845. BABYLON.serialize()
  19846. ], BaseTexture.prototype, "isCube", void 0);
  19847. __decorate([
  19848. BABYLON.serialize()
  19849. ], BaseTexture.prototype, "gammaSpace", void 0);
  19850. __decorate([
  19851. BABYLON.serialize()
  19852. ], BaseTexture.prototype, "invertZ", void 0);
  19853. __decorate([
  19854. BABYLON.serialize()
  19855. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  19856. __decorate([
  19857. BABYLON.serialize()
  19858. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  19859. __decorate([
  19860. BABYLON.serialize()
  19861. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  19862. __decorate([
  19863. BABYLON.serialize()
  19864. ], BaseTexture.prototype, "isRenderTarget", void 0);
  19865. BABYLON.BaseTexture = BaseTexture;
  19866. })(BABYLON || (BABYLON = {}));
  19867. //# sourceMappingURL=babylon.baseTexture.js.map
  19868. var BABYLON;
  19869. (function (BABYLON) {
  19870. var Texture = (function (_super) {
  19871. __extends(Texture, _super);
  19872. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  19873. if (noMipmap === void 0) { noMipmap = false; }
  19874. if (invertY === void 0) { invertY = true; }
  19875. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19876. if (onLoad === void 0) { onLoad = null; }
  19877. if (onError === void 0) { onError = null; }
  19878. if (buffer === void 0) { buffer = null; }
  19879. if (deleteBuffer === void 0) { deleteBuffer = false; }
  19880. var _this = _super.call(this, scene) || this;
  19881. _this.uOffset = 0;
  19882. _this.vOffset = 0;
  19883. _this.uScale = 1.0;
  19884. _this.vScale = 1.0;
  19885. _this.uAng = 0;
  19886. _this.vAng = 0;
  19887. _this.wAng = 0;
  19888. _this._isBlocking = true;
  19889. _this.name = url;
  19890. _this.url = url;
  19891. _this._noMipmap = noMipmap;
  19892. _this._invertY = invertY;
  19893. _this._samplingMode = samplingMode;
  19894. _this._buffer = buffer;
  19895. _this._deleteBuffer = deleteBuffer;
  19896. _this._format = format;
  19897. scene = _this.getScene();
  19898. var load = function () {
  19899. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  19900. _this.onLoadObservable.notifyObservers(_this);
  19901. }
  19902. if (onLoad) {
  19903. onLoad();
  19904. }
  19905. if (!_this.isBlocking) {
  19906. scene.resetCachedMaterial();
  19907. }
  19908. };
  19909. if (!url) {
  19910. _this._delayedOnLoad = load;
  19911. _this._delayedOnError = onError;
  19912. return _this;
  19913. }
  19914. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  19915. if (!_this._texture) {
  19916. if (!scene.useDelayedTextureLoading) {
  19917. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  19918. if (deleteBuffer) {
  19919. delete _this._buffer;
  19920. }
  19921. }
  19922. else {
  19923. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19924. _this._delayedOnLoad = load;
  19925. _this._delayedOnError = onError;
  19926. }
  19927. }
  19928. else {
  19929. if (_this._texture.isReady) {
  19930. BABYLON.Tools.SetImmediate(function () { return load(); });
  19931. }
  19932. else {
  19933. _this._texture.onLoadedCallbacks.push(load);
  19934. }
  19935. }
  19936. return _this;
  19937. }
  19938. Object.defineProperty(Texture.prototype, "noMipmap", {
  19939. get: function () {
  19940. return this._noMipmap;
  19941. },
  19942. enumerable: true,
  19943. configurable: true
  19944. });
  19945. Object.defineProperty(Texture.prototype, "isBlocking", {
  19946. get: function () {
  19947. return this._isBlocking;
  19948. },
  19949. set: function (value) {
  19950. this._isBlocking = value;
  19951. },
  19952. enumerable: true,
  19953. configurable: true
  19954. });
  19955. Object.defineProperty(Texture.prototype, "samplingMode", {
  19956. get: function () {
  19957. return this._samplingMode;
  19958. },
  19959. enumerable: true,
  19960. configurable: true
  19961. });
  19962. Texture.prototype.updateURL = function (url) {
  19963. this.url = url;
  19964. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19965. this.delayLoad();
  19966. };
  19967. Texture.prototype.delayLoad = function () {
  19968. var _this = this;
  19969. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19970. return;
  19971. }
  19972. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19973. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  19974. if (!this._texture) {
  19975. 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);
  19976. if (this._deleteBuffer) {
  19977. delete this._buffer;
  19978. }
  19979. }
  19980. else {
  19981. if (this._texture.isReady) {
  19982. BABYLON.Tools.SetImmediate(function () { return _this._delayedOnLoad(); });
  19983. }
  19984. else {
  19985. this._texture.onLoadedCallbacks.push(this._delayedOnLoad);
  19986. }
  19987. }
  19988. };
  19989. Texture.prototype.updateSamplingMode = function (samplingMode) {
  19990. if (!this._texture) {
  19991. return;
  19992. }
  19993. this._samplingMode = samplingMode;
  19994. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  19995. };
  19996. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  19997. x *= this.uScale;
  19998. y *= this.vScale;
  19999. x -= 0.5 * this.uScale;
  20000. y -= 0.5 * this.vScale;
  20001. z -= 0.5;
  20002. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  20003. t.x += 0.5 * this.uScale + this.uOffset;
  20004. t.y += 0.5 * this.vScale + this.vOffset;
  20005. t.z += 0.5;
  20006. };
  20007. Texture.prototype.getTextureMatrix = function () {
  20008. var _this = this;
  20009. if (this.uOffset === this._cachedUOffset &&
  20010. this.vOffset === this._cachedVOffset &&
  20011. this.uScale === this._cachedUScale &&
  20012. this.vScale === this._cachedVScale &&
  20013. this.uAng === this._cachedUAng &&
  20014. this.vAng === this._cachedVAng &&
  20015. this.wAng === this._cachedWAng) {
  20016. return this._cachedTextureMatrix;
  20017. }
  20018. this._cachedUOffset = this.uOffset;
  20019. this._cachedVOffset = this.vOffset;
  20020. this._cachedUScale = this.uScale;
  20021. this._cachedVScale = this.vScale;
  20022. this._cachedUAng = this.uAng;
  20023. this._cachedVAng = this.vAng;
  20024. this._cachedWAng = this.wAng;
  20025. if (!this._cachedTextureMatrix) {
  20026. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20027. this._rowGenerationMatrix = new BABYLON.Matrix();
  20028. this._t0 = BABYLON.Vector3.Zero();
  20029. this._t1 = BABYLON.Vector3.Zero();
  20030. this._t2 = BABYLON.Vector3.Zero();
  20031. }
  20032. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  20033. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  20034. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  20035. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  20036. this._t1.subtractInPlace(this._t0);
  20037. this._t2.subtractInPlace(this._t0);
  20038. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20039. this._cachedTextureMatrix.m[0] = this._t1.x;
  20040. this._cachedTextureMatrix.m[1] = this._t1.y;
  20041. this._cachedTextureMatrix.m[2] = this._t1.z;
  20042. this._cachedTextureMatrix.m[4] = this._t2.x;
  20043. this._cachedTextureMatrix.m[5] = this._t2.y;
  20044. this._cachedTextureMatrix.m[6] = this._t2.z;
  20045. this._cachedTextureMatrix.m[8] = this._t0.x;
  20046. this._cachedTextureMatrix.m[9] = this._t0.y;
  20047. this._cachedTextureMatrix.m[10] = this._t0.z;
  20048. this.getScene().markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  20049. return mat.hasTexture(_this);
  20050. });
  20051. return this._cachedTextureMatrix;
  20052. };
  20053. Texture.prototype.getReflectionTextureMatrix = function () {
  20054. var _this = this;
  20055. var scene = this.getScene();
  20056. if (this.uOffset === this._cachedUOffset &&
  20057. this.vOffset === this._cachedVOffset &&
  20058. this.uScale === this._cachedUScale &&
  20059. this.vScale === this._cachedVScale &&
  20060. this.coordinatesMode === this._cachedCoordinatesMode) {
  20061. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  20062. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  20063. return this._cachedTextureMatrix;
  20064. }
  20065. }
  20066. else {
  20067. return this._cachedTextureMatrix;
  20068. }
  20069. }
  20070. if (!this._cachedTextureMatrix) {
  20071. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20072. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  20073. }
  20074. this._cachedUOffset = this.uOffset;
  20075. this._cachedVOffset = this.vOffset;
  20076. this._cachedUScale = this.uScale;
  20077. this._cachedVScale = this.vScale;
  20078. this._cachedCoordinatesMode = this.coordinatesMode;
  20079. switch (this.coordinatesMode) {
  20080. case Texture.PLANAR_MODE:
  20081. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20082. this._cachedTextureMatrix[0] = this.uScale;
  20083. this._cachedTextureMatrix[5] = this.vScale;
  20084. this._cachedTextureMatrix[12] = this.uOffset;
  20085. this._cachedTextureMatrix[13] = this.vOffset;
  20086. break;
  20087. case Texture.PROJECTION_MODE:
  20088. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  20089. this._projectionModeMatrix.m[0] = 0.5;
  20090. this._projectionModeMatrix.m[5] = -0.5;
  20091. this._projectionModeMatrix.m[10] = 0.0;
  20092. this._projectionModeMatrix.m[12] = 0.5;
  20093. this._projectionModeMatrix.m[13] = 0.5;
  20094. this._projectionModeMatrix.m[14] = 1.0;
  20095. this._projectionModeMatrix.m[15] = 1.0;
  20096. var projectionMatrix = scene.getProjectionMatrix();
  20097. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  20098. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  20099. break;
  20100. default:
  20101. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20102. break;
  20103. }
  20104. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  20105. return (mat.getActiveTextures().indexOf(_this) !== -1);
  20106. });
  20107. return this._cachedTextureMatrix;
  20108. };
  20109. Texture.prototype.clone = function () {
  20110. var _this = this;
  20111. return BABYLON.SerializationHelper.Clone(function () {
  20112. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  20113. }, this);
  20114. };
  20115. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  20116. get: function () {
  20117. if (!this._onLoadObservable) {
  20118. this._onLoadObservable = new BABYLON.Observable();
  20119. }
  20120. return this._onLoadObservable;
  20121. },
  20122. enumerable: true,
  20123. configurable: true
  20124. });
  20125. Texture.prototype.serialize = function () {
  20126. var serializationObject = _super.prototype.serialize.call(this);
  20127. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  20128. serializationObject.base64String = this._buffer;
  20129. serializationObject.name = serializationObject.name.replace("data:", "");
  20130. }
  20131. return serializationObject;
  20132. };
  20133. Texture.prototype.getClassName = function () {
  20134. return "Texture";
  20135. };
  20136. Texture.prototype.dispose = function () {
  20137. _super.prototype.dispose.call(this);
  20138. if (this.onLoadObservable) {
  20139. this.onLoadObservable.clear();
  20140. this._onLoadObservable = null;
  20141. }
  20142. this._delayedOnLoad = null;
  20143. this._delayedOnError = null;
  20144. };
  20145. // Statics
  20146. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  20147. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20148. if (onLoad === void 0) { onLoad = null; }
  20149. if (onError === void 0) { onError = null; }
  20150. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  20151. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  20152. };
  20153. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  20154. if (parsedTexture.customType) {
  20155. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  20156. // Update Sampling Mode
  20157. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  20158. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  20159. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  20160. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  20161. }
  20162. }
  20163. return parsedCustomTexture;
  20164. }
  20165. if (parsedTexture.isCube) {
  20166. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  20167. }
  20168. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  20169. return null;
  20170. }
  20171. var texture = BABYLON.SerializationHelper.Parse(function () {
  20172. if (parsedTexture.mirrorPlane) {
  20173. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20174. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  20175. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  20176. return mirrorTexture;
  20177. }
  20178. else if (parsedTexture.isRenderTarget) {
  20179. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20180. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  20181. return renderTargetTexture;
  20182. }
  20183. else {
  20184. var texture;
  20185. if (parsedTexture.base64String) {
  20186. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  20187. }
  20188. else {
  20189. texture = new Texture(rootUrl + parsedTexture.name, scene);
  20190. }
  20191. return texture;
  20192. }
  20193. }, parsedTexture, scene);
  20194. // Update Sampling Mode
  20195. if (parsedTexture.samplingMode) {
  20196. var sampling = parsedTexture.samplingMode;
  20197. if (texture._samplingMode !== sampling) {
  20198. texture.updateSamplingMode(sampling);
  20199. }
  20200. }
  20201. // Animations
  20202. if (parsedTexture.animations) {
  20203. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  20204. var parsedAnimation = parsedTexture.animations[animationIndex];
  20205. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20206. }
  20207. }
  20208. return texture;
  20209. };
  20210. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  20211. if (deleteBuffer === void 0) { deleteBuffer = false; }
  20212. if (noMipmap === void 0) { noMipmap = false; }
  20213. if (invertY === void 0) { invertY = true; }
  20214. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20215. if (onLoad === void 0) { onLoad = null; }
  20216. if (onError === void 0) { onError = null; }
  20217. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  20218. if (name.substr(0, 5) !== "data:") {
  20219. name = "data:" + name;
  20220. }
  20221. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  20222. };
  20223. return Texture;
  20224. }(BABYLON.BaseTexture));
  20225. // Constants
  20226. Texture.NEAREST_SAMPLINGMODE = 1;
  20227. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  20228. Texture.BILINEAR_SAMPLINGMODE = 2;
  20229. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  20230. Texture.TRILINEAR_SAMPLINGMODE = 3;
  20231. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  20232. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  20233. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  20234. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  20235. Texture.NEAREST_LINEAR = 7;
  20236. Texture.NEAREST_NEAREST = 8;
  20237. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  20238. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  20239. Texture.LINEAR_LINEAR = 11;
  20240. Texture.LINEAR_NEAREST = 12;
  20241. Texture.EXPLICIT_MODE = 0;
  20242. Texture.SPHERICAL_MODE = 1;
  20243. Texture.PLANAR_MODE = 2;
  20244. Texture.CUBIC_MODE = 3;
  20245. Texture.PROJECTION_MODE = 4;
  20246. Texture.SKYBOX_MODE = 5;
  20247. Texture.INVCUBIC_MODE = 6;
  20248. Texture.EQUIRECTANGULAR_MODE = 7;
  20249. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  20250. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  20251. Texture.CLAMP_ADDRESSMODE = 0;
  20252. Texture.WRAP_ADDRESSMODE = 1;
  20253. Texture.MIRROR_ADDRESSMODE = 2;
  20254. __decorate([
  20255. BABYLON.serialize()
  20256. ], Texture.prototype, "url", void 0);
  20257. __decorate([
  20258. BABYLON.serialize()
  20259. ], Texture.prototype, "uOffset", void 0);
  20260. __decorate([
  20261. BABYLON.serialize()
  20262. ], Texture.prototype, "vOffset", void 0);
  20263. __decorate([
  20264. BABYLON.serialize()
  20265. ], Texture.prototype, "uScale", void 0);
  20266. __decorate([
  20267. BABYLON.serialize()
  20268. ], Texture.prototype, "vScale", void 0);
  20269. __decorate([
  20270. BABYLON.serialize()
  20271. ], Texture.prototype, "uAng", void 0);
  20272. __decorate([
  20273. BABYLON.serialize()
  20274. ], Texture.prototype, "vAng", void 0);
  20275. __decorate([
  20276. BABYLON.serialize()
  20277. ], Texture.prototype, "wAng", void 0);
  20278. __decorate([
  20279. BABYLON.serialize()
  20280. ], Texture.prototype, "isBlocking", null);
  20281. BABYLON.Texture = Texture;
  20282. })(BABYLON || (BABYLON = {}));
  20283. //# sourceMappingURL=babylon.texture.js.map
  20284. var BABYLON;
  20285. (function (BABYLON) {
  20286. var _InstancesBatch = (function () {
  20287. function _InstancesBatch() {
  20288. this.mustReturn = false;
  20289. this.visibleInstances = new Array();
  20290. this.renderSelf = new Array();
  20291. }
  20292. return _InstancesBatch;
  20293. }());
  20294. BABYLON._InstancesBatch = _InstancesBatch;
  20295. var Mesh = (function (_super) {
  20296. __extends(Mesh, _super);
  20297. /**
  20298. * @constructor
  20299. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  20300. * @param {Scene} scene The scene to add this mesh to.
  20301. * @param {Node} parent The parent of this mesh, if it has one
  20302. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  20303. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  20304. * When false, achieved by calling a clone(), also passing False.
  20305. * This will make creation of children, recursive.
  20306. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  20307. */
  20308. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  20309. if (parent === void 0) { parent = null; }
  20310. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20311. var _this = _super.call(this, name, scene) || this;
  20312. // Events
  20313. /**
  20314. * An event triggered before rendering the mesh
  20315. * @type {BABYLON.Observable}
  20316. */
  20317. _this.onBeforeRenderObservable = new BABYLON.Observable();
  20318. /**
  20319. * An event triggered after rendering the mesh
  20320. * @type {BABYLON.Observable}
  20321. */
  20322. _this.onAfterRenderObservable = new BABYLON.Observable();
  20323. /**
  20324. * An event triggered before drawing the mesh
  20325. * @type {BABYLON.Observable}
  20326. */
  20327. _this.onBeforeDrawObservable = new BABYLON.Observable();
  20328. // Members
  20329. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20330. _this.instances = new Array();
  20331. _this._LODLevels = new Array();
  20332. _this._visibleInstances = {};
  20333. _this._renderIdForInstances = new Array();
  20334. _this._batchCache = new _InstancesBatch();
  20335. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  20336. _this._sideOrientation = Mesh._DEFAULTSIDE;
  20337. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  20338. // Will be used to save a source mesh reference, If any
  20339. _this._source = null;
  20340. if (source) {
  20341. // Source mesh
  20342. _this._source = source;
  20343. // Geometry
  20344. if (source._geometry) {
  20345. source._geometry.applyToMesh(_this);
  20346. }
  20347. // Deep copy
  20348. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  20349. // Parent
  20350. _this.parent = source.parent;
  20351. // Pivot
  20352. _this.setPivotMatrix(source.getPivotMatrix());
  20353. _this.id = name + "." + source.id;
  20354. // Material
  20355. _this.material = source.material;
  20356. var index;
  20357. if (!doNotCloneChildren) {
  20358. // Children
  20359. for (index = 0; index < scene.meshes.length; index++) {
  20360. var mesh = scene.meshes[index];
  20361. if (mesh.parent === source) {
  20362. // doNotCloneChildren is always going to be False
  20363. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  20364. }
  20365. }
  20366. }
  20367. // Physics clone
  20368. var physicsEngine = _this.getScene().getPhysicsEngine();
  20369. if (clonePhysicsImpostor && physicsEngine) {
  20370. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  20371. if (impostor) {
  20372. _this.physicsImpostor = impostor.clone(_this);
  20373. }
  20374. }
  20375. // Particles
  20376. for (index = 0; index < scene.particleSystems.length; index++) {
  20377. var system = scene.particleSystems[index];
  20378. if (system.emitter === source) {
  20379. system.clone(system.name, _this);
  20380. }
  20381. }
  20382. _this.computeWorldMatrix(true);
  20383. }
  20384. // Parent
  20385. if (parent !== null) {
  20386. _this.parent = parent;
  20387. }
  20388. return _this;
  20389. }
  20390. Object.defineProperty(Mesh, "FRONTSIDE", {
  20391. /**
  20392. * Mesh side orientation : usually the external or front surface
  20393. */
  20394. get: function () {
  20395. return Mesh._FRONTSIDE;
  20396. },
  20397. enumerable: true,
  20398. configurable: true
  20399. });
  20400. Object.defineProperty(Mesh, "BACKSIDE", {
  20401. /**
  20402. * Mesh side orientation : usually the internal or back surface
  20403. */
  20404. get: function () {
  20405. return Mesh._BACKSIDE;
  20406. },
  20407. enumerable: true,
  20408. configurable: true
  20409. });
  20410. Object.defineProperty(Mesh, "DOUBLESIDE", {
  20411. /**
  20412. * Mesh side orientation : both internal and external or front and back surfaces
  20413. */
  20414. get: function () {
  20415. return Mesh._DOUBLESIDE;
  20416. },
  20417. enumerable: true,
  20418. configurable: true
  20419. });
  20420. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  20421. /**
  20422. * Mesh side orientation : by default, `FRONTSIDE`
  20423. */
  20424. get: function () {
  20425. return Mesh._DEFAULTSIDE;
  20426. },
  20427. enumerable: true,
  20428. configurable: true
  20429. });
  20430. Object.defineProperty(Mesh, "NO_CAP", {
  20431. /**
  20432. * Mesh cap setting : no cap
  20433. */
  20434. get: function () {
  20435. return Mesh._NO_CAP;
  20436. },
  20437. enumerable: true,
  20438. configurable: true
  20439. });
  20440. Object.defineProperty(Mesh, "CAP_START", {
  20441. /**
  20442. * Mesh cap setting : one cap at the beginning of the mesh
  20443. */
  20444. get: function () {
  20445. return Mesh._CAP_START;
  20446. },
  20447. enumerable: true,
  20448. configurable: true
  20449. });
  20450. Object.defineProperty(Mesh, "CAP_END", {
  20451. /**
  20452. * Mesh cap setting : one cap at the end of the mesh
  20453. */
  20454. get: function () {
  20455. return Mesh._CAP_END;
  20456. },
  20457. enumerable: true,
  20458. configurable: true
  20459. });
  20460. Object.defineProperty(Mesh, "CAP_ALL", {
  20461. /**
  20462. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  20463. */
  20464. get: function () {
  20465. return Mesh._CAP_ALL;
  20466. },
  20467. enumerable: true,
  20468. configurable: true
  20469. });
  20470. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  20471. set: function (callback) {
  20472. if (this._onBeforeDrawObserver) {
  20473. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  20474. }
  20475. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  20476. },
  20477. enumerable: true,
  20478. configurable: true
  20479. });
  20480. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  20481. get: function () {
  20482. return this._morphTargetManager;
  20483. },
  20484. set: function (value) {
  20485. if (this._morphTargetManager === value) {
  20486. return;
  20487. }
  20488. this._morphTargetManager = value;
  20489. this._syncGeometryWithMorphTargetManager();
  20490. },
  20491. enumerable: true,
  20492. configurable: true
  20493. });
  20494. Object.defineProperty(Mesh.prototype, "source", {
  20495. get: function () {
  20496. return this._source;
  20497. },
  20498. enumerable: true,
  20499. configurable: true
  20500. });
  20501. // Methods
  20502. /**
  20503. * Returns the string "Mesh".
  20504. */
  20505. Mesh.prototype.getClassName = function () {
  20506. return "Mesh";
  20507. };
  20508. /**
  20509. * Returns a string.
  20510. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  20511. */
  20512. Mesh.prototype.toString = function (fullDetails) {
  20513. var ret = _super.prototype.toString.call(this, fullDetails);
  20514. ret += ", n vertices: " + this.getTotalVertices();
  20515. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  20516. if (this.animations) {
  20517. for (var i = 0; i < this.animations.length; i++) {
  20518. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  20519. }
  20520. }
  20521. if (fullDetails) {
  20522. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  20523. }
  20524. return ret;
  20525. };
  20526. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  20527. /**
  20528. * True if the mesh has some Levels Of Details (LOD).
  20529. * Returns a boolean.
  20530. */
  20531. get: function () {
  20532. return this._LODLevels.length > 0;
  20533. },
  20534. enumerable: true,
  20535. configurable: true
  20536. });
  20537. Mesh.prototype._sortLODLevels = function () {
  20538. this._LODLevels.sort(function (a, b) {
  20539. if (a.distance < b.distance) {
  20540. return 1;
  20541. }
  20542. if (a.distance > b.distance) {
  20543. return -1;
  20544. }
  20545. return 0;
  20546. });
  20547. };
  20548. /**
  20549. * Add a mesh as LOD level triggered at the given distance.
  20550. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  20551. * @param {number} distance The distance from the center of the object to show this level
  20552. * @param {Mesh} mesh The mesh to be added as LOD level
  20553. * @return {Mesh} This mesh (for chaining)
  20554. */
  20555. Mesh.prototype.addLODLevel = function (distance, mesh) {
  20556. if (mesh && mesh._masterMesh) {
  20557. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  20558. return this;
  20559. }
  20560. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  20561. this._LODLevels.push(level);
  20562. if (mesh) {
  20563. mesh._masterMesh = this;
  20564. }
  20565. this._sortLODLevels();
  20566. return this;
  20567. };
  20568. /**
  20569. * Returns the LOD level mesh at the passed distance or null if not found.
  20570. * It is related to the method `addLODLevel(distance, mesh)`.
  20571. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  20572. * Returns an object Mesh or `null`.
  20573. */
  20574. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  20575. for (var index = 0; index < this._LODLevels.length; index++) {
  20576. var level = this._LODLevels[index];
  20577. if (level.distance === distance) {
  20578. return level.mesh;
  20579. }
  20580. }
  20581. return null;
  20582. };
  20583. /**
  20584. * Remove a mesh from the LOD array
  20585. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  20586. * @param {Mesh} mesh The mesh to be removed.
  20587. * @return {Mesh} This mesh (for chaining)
  20588. */
  20589. Mesh.prototype.removeLODLevel = function (mesh) {
  20590. for (var index = 0; index < this._LODLevels.length; index++) {
  20591. if (this._LODLevels[index].mesh === mesh) {
  20592. this._LODLevels.splice(index, 1);
  20593. if (mesh) {
  20594. mesh._masterMesh = null;
  20595. }
  20596. }
  20597. }
  20598. this._sortLODLevels();
  20599. return this;
  20600. };
  20601. /**
  20602. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  20603. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  20604. */
  20605. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  20606. if (!this._LODLevels || this._LODLevels.length === 0) {
  20607. return this;
  20608. }
  20609. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  20610. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  20611. if (this.onLODLevelSelection) {
  20612. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  20613. }
  20614. return this;
  20615. }
  20616. for (var index = 0; index < this._LODLevels.length; index++) {
  20617. var level = this._LODLevels[index];
  20618. if (level.distance < distanceToCamera) {
  20619. if (level.mesh) {
  20620. level.mesh._preActivate();
  20621. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20622. }
  20623. if (this.onLODLevelSelection) {
  20624. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  20625. }
  20626. return level.mesh;
  20627. }
  20628. }
  20629. if (this.onLODLevelSelection) {
  20630. this.onLODLevelSelection(distanceToCamera, this, this);
  20631. }
  20632. return this;
  20633. };
  20634. Object.defineProperty(Mesh.prototype, "geometry", {
  20635. /**
  20636. * Returns the mesh internal Geometry object.
  20637. */
  20638. get: function () {
  20639. return this._geometry;
  20640. },
  20641. enumerable: true,
  20642. configurable: true
  20643. });
  20644. /**
  20645. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  20646. */
  20647. Mesh.prototype.getTotalVertices = function () {
  20648. if (!this._geometry) {
  20649. return 0;
  20650. }
  20651. return this._geometry.getTotalVertices();
  20652. };
  20653. /**
  20654. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  20655. * 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.
  20656. * You can force the copy with forceCopy === true
  20657. * Returns null if the mesh has no geometry or no vertex buffer.
  20658. * Possible `kind` values :
  20659. * - BABYLON.VertexBuffer.PositionKind
  20660. * - BABYLON.VertexBuffer.UVKind
  20661. * - BABYLON.VertexBuffer.UV2Kind
  20662. * - BABYLON.VertexBuffer.UV3Kind
  20663. * - BABYLON.VertexBuffer.UV4Kind
  20664. * - BABYLON.VertexBuffer.UV5Kind
  20665. * - BABYLON.VertexBuffer.UV6Kind
  20666. * - BABYLON.VertexBuffer.ColorKind
  20667. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20668. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20669. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20670. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20671. */
  20672. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  20673. if (!this._geometry) {
  20674. return null;
  20675. }
  20676. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  20677. };
  20678. /**
  20679. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  20680. * Returns `undefined` if the mesh has no geometry.
  20681. * Possible `kind` values :
  20682. * - BABYLON.VertexBuffer.PositionKind
  20683. * - BABYLON.VertexBuffer.UVKind
  20684. * - BABYLON.VertexBuffer.UV2Kind
  20685. * - BABYLON.VertexBuffer.UV3Kind
  20686. * - BABYLON.VertexBuffer.UV4Kind
  20687. * - BABYLON.VertexBuffer.UV5Kind
  20688. * - BABYLON.VertexBuffer.UV6Kind
  20689. * - BABYLON.VertexBuffer.ColorKind
  20690. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20691. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20692. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20693. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20694. */
  20695. Mesh.prototype.getVertexBuffer = function (kind) {
  20696. if (!this._geometry) {
  20697. return undefined;
  20698. }
  20699. return this._geometry.getVertexBuffer(kind);
  20700. };
  20701. /**
  20702. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  20703. * Possible `kind` values :
  20704. * - BABYLON.VertexBuffer.PositionKind
  20705. * - BABYLON.VertexBuffer.UVKind
  20706. * - BABYLON.VertexBuffer.UV2Kind
  20707. * - BABYLON.VertexBuffer.UV3Kind
  20708. * - BABYLON.VertexBuffer.UV4Kind
  20709. * - BABYLON.VertexBuffer.UV5Kind
  20710. * - BABYLON.VertexBuffer.UV6Kind
  20711. * - BABYLON.VertexBuffer.ColorKind
  20712. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20713. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20714. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20715. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20716. */
  20717. Mesh.prototype.isVerticesDataPresent = function (kind) {
  20718. if (!this._geometry) {
  20719. if (this._delayInfo) {
  20720. return this._delayInfo.indexOf(kind) !== -1;
  20721. }
  20722. return false;
  20723. }
  20724. return this._geometry.isVerticesDataPresent(kind);
  20725. };
  20726. /**
  20727. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  20728. * Possible `kind` values :
  20729. * - BABYLON.VertexBuffer.PositionKind
  20730. * - BABYLON.VertexBuffer.UVKind
  20731. * - BABYLON.VertexBuffer.UV2Kind
  20732. * - BABYLON.VertexBuffer.UV3Kind
  20733. * - BABYLON.VertexBuffer.UV4Kind
  20734. * - BABYLON.VertexBuffer.UV5Kind
  20735. * - BABYLON.VertexBuffer.UV6Kind
  20736. * - BABYLON.VertexBuffer.ColorKind
  20737. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20738. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20739. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20740. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20741. */
  20742. Mesh.prototype.getVerticesDataKinds = function () {
  20743. if (!this._geometry) {
  20744. var result = [];
  20745. if (this._delayInfo) {
  20746. this._delayInfo.forEach(function (kind, index, array) {
  20747. result.push(kind);
  20748. });
  20749. }
  20750. return result;
  20751. }
  20752. return this._geometry.getVerticesDataKinds();
  20753. };
  20754. /**
  20755. * Returns a positive integer : the total number of indices in this mesh geometry.
  20756. * Returns zero if the mesh has no geometry.
  20757. */
  20758. Mesh.prototype.getTotalIndices = function () {
  20759. if (!this._geometry) {
  20760. return 0;
  20761. }
  20762. return this._geometry.getTotalIndices();
  20763. };
  20764. /**
  20765. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  20766. * 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.
  20767. * Returns an empty array if the mesh has no geometry.
  20768. */
  20769. Mesh.prototype.getIndices = function (copyWhenShared) {
  20770. if (!this._geometry) {
  20771. return [];
  20772. }
  20773. return this._geometry.getIndices(copyWhenShared);
  20774. };
  20775. Object.defineProperty(Mesh.prototype, "isBlocked", {
  20776. get: function () {
  20777. return this._masterMesh !== null && this._masterMesh !== undefined;
  20778. },
  20779. enumerable: true,
  20780. configurable: true
  20781. });
  20782. /**
  20783. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  20784. */
  20785. Mesh.prototype.isReady = function () {
  20786. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20787. return false;
  20788. }
  20789. return _super.prototype.isReady.call(this);
  20790. };
  20791. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  20792. get: function () {
  20793. return this._sideOrientation;
  20794. },
  20795. /**
  20796. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  20797. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  20798. */
  20799. set: function (sideO) {
  20800. this._sideOrientation = sideO;
  20801. },
  20802. enumerable: true,
  20803. configurable: true
  20804. });
  20805. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  20806. /**
  20807. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  20808. * This property is pertinent only for updatable parametric shapes.
  20809. */
  20810. get: function () {
  20811. return this._areNormalsFrozen;
  20812. },
  20813. enumerable: true,
  20814. configurable: true
  20815. });
  20816. /**
  20817. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  20818. * It has no effect at all on other shapes.
  20819. * It prevents the mesh normals from being recomputed on next `positions` array update.
  20820. * Returns the Mesh.
  20821. */
  20822. Mesh.prototype.freezeNormals = function () {
  20823. this._areNormalsFrozen = true;
  20824. return this;
  20825. };
  20826. /**
  20827. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  20828. * It has no effect at all on other shapes.
  20829. * It reactivates the mesh normals computation if it was previously frozen.
  20830. * Returns the Mesh.
  20831. */
  20832. Mesh.prototype.unfreezeNormals = function () {
  20833. this._areNormalsFrozen = false;
  20834. return this;
  20835. };
  20836. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  20837. /**
  20838. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  20839. */
  20840. set: function (count) {
  20841. this._overridenInstanceCount = count;
  20842. },
  20843. enumerable: true,
  20844. configurable: true
  20845. });
  20846. // Methods
  20847. Mesh.prototype._preActivate = function () {
  20848. var sceneRenderId = this.getScene().getRenderId();
  20849. if (this._preActivateId === sceneRenderId) {
  20850. return this;
  20851. }
  20852. this._preActivateId = sceneRenderId;
  20853. this._visibleInstances = null;
  20854. return this;
  20855. };
  20856. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20857. if (this._visibleInstances) {
  20858. this._visibleInstances.intermediateDefaultRenderId = renderId;
  20859. }
  20860. return this;
  20861. };
  20862. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  20863. if (!this._visibleInstances) {
  20864. this._visibleInstances = {};
  20865. this._visibleInstances.defaultRenderId = renderId;
  20866. this._visibleInstances.selfDefaultRenderId = this._renderId;
  20867. }
  20868. if (!this._visibleInstances[renderId]) {
  20869. this._visibleInstances[renderId] = new Array();
  20870. }
  20871. this._visibleInstances[renderId].push(instance);
  20872. return this;
  20873. };
  20874. /**
  20875. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  20876. * This means the mesh underlying bounding box and sphere are recomputed.
  20877. * Returns the Mesh.
  20878. */
  20879. Mesh.prototype.refreshBoundingInfo = function () {
  20880. if (this._boundingInfo.isLocked) {
  20881. return;
  20882. }
  20883. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20884. if (data) {
  20885. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  20886. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20887. }
  20888. if (this.subMeshes) {
  20889. for (var index = 0; index < this.subMeshes.length; index++) {
  20890. this.subMeshes[index].refreshBoundingInfo();
  20891. }
  20892. }
  20893. this._updateBoundingInfo();
  20894. return this;
  20895. };
  20896. Mesh.prototype._createGlobalSubMesh = function (force) {
  20897. var totalVertices = this.getTotalVertices();
  20898. if (!totalVertices || !this.getIndices()) {
  20899. return null;
  20900. }
  20901. // Check if we need to recreate the submeshes
  20902. if (this.subMeshes && this.subMeshes.length > 0) {
  20903. var totalIndices = this.getIndices().length;
  20904. var needToRecreate = false;
  20905. if (force) {
  20906. needToRecreate = true;
  20907. }
  20908. else {
  20909. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20910. var submesh = _a[_i];
  20911. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  20912. needToRecreate = true;
  20913. break;
  20914. }
  20915. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  20916. needToRecreate = true;
  20917. break;
  20918. }
  20919. }
  20920. }
  20921. if (!needToRecreate) {
  20922. return;
  20923. }
  20924. }
  20925. this.releaseSubMeshes();
  20926. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  20927. };
  20928. Mesh.prototype.subdivide = function (count) {
  20929. if (count < 1) {
  20930. return;
  20931. }
  20932. var totalIndices = this.getTotalIndices();
  20933. var subdivisionSize = (totalIndices / count) | 0;
  20934. var offset = 0;
  20935. // Ensure that subdivisionSize is a multiple of 3
  20936. while (subdivisionSize % 3 !== 0) {
  20937. subdivisionSize++;
  20938. }
  20939. this.releaseSubMeshes();
  20940. for (var index = 0; index < count; index++) {
  20941. if (offset >= totalIndices) {
  20942. break;
  20943. }
  20944. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  20945. offset += subdivisionSize;
  20946. }
  20947. this.synchronizeInstances();
  20948. };
  20949. /**
  20950. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20951. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20952. * The `data` are either a numeric array either a Float32Array.
  20953. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  20954. * 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).
  20955. * Note that a new underlying VertexBuffer object is created each call.
  20956. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20957. *
  20958. * Possible `kind` values :
  20959. * - BABYLON.VertexBuffer.PositionKind
  20960. * - BABYLON.VertexBuffer.UVKind
  20961. * - BABYLON.VertexBuffer.UV2Kind
  20962. * - BABYLON.VertexBuffer.UV3Kind
  20963. * - BABYLON.VertexBuffer.UV4Kind
  20964. * - BABYLON.VertexBuffer.UV5Kind
  20965. * - BABYLON.VertexBuffer.UV6Kind
  20966. * - BABYLON.VertexBuffer.ColorKind
  20967. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20968. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20969. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20970. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20971. *
  20972. * Returns the Mesh.
  20973. */
  20974. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20975. if (!this._geometry) {
  20976. var vertexData = new BABYLON.VertexData();
  20977. vertexData.set(data, kind);
  20978. var scene = this.getScene();
  20979. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  20980. }
  20981. else {
  20982. this._geometry.setVerticesData(kind, data, updatable, stride);
  20983. }
  20984. return this;
  20985. };
  20986. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  20987. if (updatable === void 0) { updatable = true; }
  20988. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  20989. return;
  20990. }
  20991. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  20992. };
  20993. /**
  20994. * Sets the mesh VertexBuffer.
  20995. * Returns the Mesh.
  20996. */
  20997. Mesh.prototype.setVerticesBuffer = function (buffer) {
  20998. if (!this._geometry) {
  20999. var scene = this.getScene();
  21000. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  21001. }
  21002. this._geometry.setVerticesBuffer(buffer);
  21003. return this;
  21004. };
  21005. /**
  21006. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  21007. * If the mesh has no geometry, it is simply returned as it is.
  21008. * The `data` are either a numeric array either a Float32Array.
  21009. * No new underlying VertexBuffer object is created.
  21010. * 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.
  21011. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  21012. *
  21013. * Possible `kind` values :
  21014. * - BABYLON.VertexBuffer.PositionKind
  21015. * - BABYLON.VertexBuffer.UVKind
  21016. * - BABYLON.VertexBuffer.UV2Kind
  21017. * - BABYLON.VertexBuffer.UV3Kind
  21018. * - BABYLON.VertexBuffer.UV4Kind
  21019. * - BABYLON.VertexBuffer.UV5Kind
  21020. * - BABYLON.VertexBuffer.UV6Kind
  21021. * - BABYLON.VertexBuffer.ColorKind
  21022. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21023. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21024. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21025. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21026. *
  21027. * Returns the Mesh.
  21028. */
  21029. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  21030. if (!this._geometry) {
  21031. return;
  21032. }
  21033. if (!makeItUnique) {
  21034. this._geometry.updateVerticesData(kind, data, updateExtends);
  21035. }
  21036. else {
  21037. this.makeGeometryUnique();
  21038. this.updateVerticesData(kind, data, updateExtends, false);
  21039. }
  21040. return this;
  21041. };
  21042. /**
  21043. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  21044. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  21045. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  21046. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  21047. * Returns the Mesh.
  21048. */
  21049. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  21050. if (computeNormals === void 0) { computeNormals = true; }
  21051. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21052. positionFunction(positions);
  21053. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  21054. if (computeNormals) {
  21055. var indices = this.getIndices();
  21056. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21057. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21058. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  21059. }
  21060. return this;
  21061. };
  21062. /**
  21063. * Creates a un-shared specific occurence of the geometry for the mesh.
  21064. * Returns the Mesh.
  21065. */
  21066. Mesh.prototype.makeGeometryUnique = function () {
  21067. if (!this._geometry) {
  21068. return;
  21069. }
  21070. var oldGeometry = this._geometry;
  21071. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  21072. oldGeometry.releaseForMesh(this, true);
  21073. geometry.applyToMesh(this);
  21074. return this;
  21075. };
  21076. /**
  21077. * Sets the mesh indices.
  21078. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  21079. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  21080. * This method creates a new index buffer each call.
  21081. * Returns the Mesh.
  21082. */
  21083. Mesh.prototype.setIndices = function (indices, totalVertices) {
  21084. if (!this._geometry) {
  21085. var vertexData = new BABYLON.VertexData();
  21086. vertexData.indices = indices;
  21087. var scene = this.getScene();
  21088. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  21089. }
  21090. else {
  21091. this._geometry.setIndices(indices, totalVertices);
  21092. }
  21093. return this;
  21094. };
  21095. /**
  21096. * Invert the geometry to move from a right handed system to a left handed one.
  21097. * Returns the Mesh.
  21098. */
  21099. Mesh.prototype.toLeftHanded = function () {
  21100. if (!this._geometry) {
  21101. return;
  21102. }
  21103. this._geometry.toLeftHanded();
  21104. return this;
  21105. };
  21106. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  21107. var engine = this.getScene().getEngine();
  21108. // Wireframe
  21109. var indexToBind;
  21110. if (this._unIndexed) {
  21111. indexToBind = null;
  21112. }
  21113. else {
  21114. switch (fillMode) {
  21115. case BABYLON.Material.PointFillMode:
  21116. indexToBind = null;
  21117. break;
  21118. case BABYLON.Material.WireFrameFillMode:
  21119. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  21120. break;
  21121. default:
  21122. case BABYLON.Material.TriangleFillMode:
  21123. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  21124. break;
  21125. }
  21126. }
  21127. // VBOs
  21128. this._geometry._bind(effect, indexToBind);
  21129. return this;
  21130. };
  21131. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  21132. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  21133. return this;
  21134. }
  21135. this.onBeforeDrawObservable.notifyObservers(this);
  21136. var engine = this.getScene().getEngine();
  21137. // Draw order
  21138. switch (fillMode) {
  21139. case BABYLON.Material.PointFillMode:
  21140. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21141. break;
  21142. case BABYLON.Material.WireFrameFillMode:
  21143. if (this._unIndexed) {
  21144. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21145. }
  21146. else {
  21147. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  21148. }
  21149. break;
  21150. default:
  21151. if (this._unIndexed) {
  21152. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21153. }
  21154. else {
  21155. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  21156. }
  21157. }
  21158. return this;
  21159. };
  21160. /**
  21161. * Registers for this mesh a javascript function called just before the rendering process.
  21162. * This function is passed the current mesh.
  21163. * Return the Mesh.
  21164. */
  21165. Mesh.prototype.registerBeforeRender = function (func) {
  21166. this.onBeforeRenderObservable.add(func);
  21167. return this;
  21168. };
  21169. /**
  21170. * Disposes a previously registered javascript function called before the rendering.
  21171. * This function is passed the current mesh.
  21172. * Returns the Mesh.
  21173. */
  21174. Mesh.prototype.unregisterBeforeRender = function (func) {
  21175. this.onBeforeRenderObservable.removeCallback(func);
  21176. return this;
  21177. };
  21178. /**
  21179. * Registers for this mesh a javascript function called just after the rendering is complete.
  21180. * This function is passed the current mesh.
  21181. * Returns the Mesh.
  21182. */
  21183. Mesh.prototype.registerAfterRender = function (func) {
  21184. this.onAfterRenderObservable.add(func);
  21185. return this;
  21186. };
  21187. /**
  21188. * Disposes a previously registered javascript function called after the rendering.
  21189. * This function is passed the current mesh.
  21190. * Return the Mesh.
  21191. */
  21192. Mesh.prototype.unregisterAfterRender = function (func) {
  21193. this.onAfterRenderObservable.removeCallback(func);
  21194. return this;
  21195. };
  21196. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  21197. var scene = this.getScene();
  21198. this._batchCache.mustReturn = false;
  21199. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  21200. this._batchCache.visibleInstances[subMeshId] = null;
  21201. if (this._visibleInstances) {
  21202. var currentRenderId = scene.getRenderId();
  21203. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  21204. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  21205. var selfRenderId = this._renderId;
  21206. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  21207. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  21208. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  21209. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  21210. }
  21211. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  21212. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  21213. this._batchCache.mustReturn = true;
  21214. return this._batchCache;
  21215. }
  21216. if (currentRenderId !== selfRenderId) {
  21217. this._batchCache.renderSelf[subMeshId] = false;
  21218. }
  21219. }
  21220. this._renderIdForInstances[subMeshId] = currentRenderId;
  21221. }
  21222. return this._batchCache;
  21223. };
  21224. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  21225. var visibleInstances = batch.visibleInstances[subMesh._id];
  21226. var matricesCount = visibleInstances.length + 1;
  21227. var bufferSize = matricesCount * 16 * 4;
  21228. var currentInstancesBufferSize = this._instancesBufferSize;
  21229. var instancesBuffer = this._instancesBuffer;
  21230. while (this._instancesBufferSize < bufferSize) {
  21231. this._instancesBufferSize *= 2;
  21232. }
  21233. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  21234. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  21235. }
  21236. var offset = 0;
  21237. var instancesCount = 0;
  21238. var world = this.getWorldMatrix();
  21239. if (batch.renderSelf[subMesh._id]) {
  21240. world.copyToArray(this._instancesData, offset);
  21241. offset += 16;
  21242. instancesCount++;
  21243. }
  21244. if (visibleInstances) {
  21245. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  21246. var instance = visibleInstances[instanceIndex];
  21247. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  21248. offset += 16;
  21249. instancesCount++;
  21250. }
  21251. }
  21252. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  21253. if (instancesBuffer) {
  21254. instancesBuffer.dispose();
  21255. }
  21256. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  21257. this._instancesBuffer = instancesBuffer;
  21258. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  21259. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  21260. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  21261. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  21262. }
  21263. else {
  21264. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  21265. }
  21266. this.geometry._bind(effect);
  21267. this._draw(subMesh, fillMode, instancesCount);
  21268. engine.unbindInstanceAttributes();
  21269. return this;
  21270. };
  21271. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  21272. var scene = this.getScene();
  21273. var engine = scene.getEngine();
  21274. if (hardwareInstancedRendering) {
  21275. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  21276. }
  21277. else {
  21278. if (batch.renderSelf[subMesh._id]) {
  21279. // Draw
  21280. if (onBeforeDraw) {
  21281. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  21282. }
  21283. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  21284. }
  21285. if (batch.visibleInstances[subMesh._id]) {
  21286. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  21287. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  21288. // World
  21289. var world = instance.getWorldMatrix();
  21290. if (onBeforeDraw) {
  21291. onBeforeDraw(true, world, effectiveMaterial);
  21292. }
  21293. // Draw
  21294. this._draw(subMesh, fillMode);
  21295. }
  21296. }
  21297. }
  21298. return this;
  21299. };
  21300. /**
  21301. * Triggers the draw call for the mesh.
  21302. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  21303. * Returns the Mesh.
  21304. */
  21305. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  21306. var scene = this.getScene();
  21307. // Managing instances
  21308. var batch = this._getInstancesRenderList(subMesh._id);
  21309. if (batch.mustReturn) {
  21310. return this;
  21311. }
  21312. // Checking geometry state
  21313. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  21314. return this;
  21315. }
  21316. var callbackIndex;
  21317. this.onBeforeRenderObservable.notifyObservers(this);
  21318. var engine = scene.getEngine();
  21319. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  21320. // Material
  21321. var effectiveMaterial = subMesh.getMaterial();
  21322. if (!effectiveMaterial) {
  21323. return this;
  21324. }
  21325. if (effectiveMaterial.storeEffectOnSubMeshes) {
  21326. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  21327. return this;
  21328. }
  21329. }
  21330. else if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  21331. return this;
  21332. }
  21333. // Alpha mode
  21334. if (enableAlphaMode) {
  21335. engine.setAlphaMode(effectiveMaterial.alphaMode);
  21336. }
  21337. // Outline - step 1
  21338. var savedDepthWrite = engine.getDepthWrite();
  21339. if (this.renderOutline) {
  21340. engine.setDepthWrite(false);
  21341. scene.getOutlineRenderer().render(subMesh, batch);
  21342. engine.setDepthWrite(savedDepthWrite);
  21343. }
  21344. var effect;
  21345. if (effectiveMaterial.storeEffectOnSubMeshes) {
  21346. effect = subMesh.effect;
  21347. }
  21348. else {
  21349. effect = effectiveMaterial.getEffect();
  21350. }
  21351. effectiveMaterial._preBind(effect);
  21352. // Bind
  21353. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  21354. this._bind(subMesh, effect, fillMode);
  21355. var world = this.getWorldMatrix();
  21356. if (effectiveMaterial.storeEffectOnSubMeshes) {
  21357. effectiveMaterial.bindForSubMesh(world, this, subMesh);
  21358. }
  21359. else {
  21360. effectiveMaterial.bind(world, this);
  21361. }
  21362. // Draw
  21363. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  21364. // Unbind
  21365. effectiveMaterial.unbind();
  21366. // Outline - step 2
  21367. if (this.renderOutline && savedDepthWrite) {
  21368. engine.setDepthWrite(true);
  21369. engine.setColorWrite(false);
  21370. scene.getOutlineRenderer().render(subMesh, batch);
  21371. engine.setColorWrite(true);
  21372. }
  21373. // Overlay
  21374. if (this.renderOverlay) {
  21375. var currentMode = engine.getAlphaMode();
  21376. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21377. scene.getOutlineRenderer().render(subMesh, batch, true);
  21378. engine.setAlphaMode(currentMode);
  21379. }
  21380. this.onAfterRenderObservable.notifyObservers(this);
  21381. return this;
  21382. };
  21383. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  21384. if (isInstance) {
  21385. effectiveMaterial.bindOnlyWorldMatrix(world);
  21386. }
  21387. return this;
  21388. };
  21389. /**
  21390. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  21391. */
  21392. Mesh.prototype.getEmittedParticleSystems = function () {
  21393. var results = new Array();
  21394. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  21395. var particleSystem = this.getScene().particleSystems[index];
  21396. if (particleSystem.emitter === this) {
  21397. results.push(particleSystem);
  21398. }
  21399. }
  21400. return results;
  21401. };
  21402. /**
  21403. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  21404. */
  21405. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  21406. var results = new Array();
  21407. var descendants = this.getDescendants();
  21408. descendants.push(this);
  21409. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  21410. var particleSystem = this.getScene().particleSystems[index];
  21411. var emitter = particleSystem.emitter;
  21412. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  21413. results.push(particleSystem);
  21414. }
  21415. }
  21416. return results;
  21417. };
  21418. Mesh.prototype._checkDelayState = function () {
  21419. var scene = this.getScene();
  21420. if (this._geometry) {
  21421. this._geometry.load(scene);
  21422. }
  21423. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21424. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  21425. this._queueLoad(this, scene);
  21426. }
  21427. return this;
  21428. };
  21429. Mesh.prototype._queueLoad = function (mesh, scene) {
  21430. var _this = this;
  21431. scene._addPendingData(mesh);
  21432. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  21433. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  21434. if (data instanceof ArrayBuffer) {
  21435. _this._delayLoadingFunction(data, _this);
  21436. }
  21437. else {
  21438. _this._delayLoadingFunction(JSON.parse(data), _this);
  21439. }
  21440. _this.instances.forEach(function (instance) {
  21441. instance._syncSubMeshes();
  21442. });
  21443. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21444. scene._removePendingData(_this);
  21445. }, function () { }, scene.database, getBinaryData);
  21446. return this;
  21447. };
  21448. /**
  21449. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  21450. */
  21451. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  21452. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21453. return false;
  21454. }
  21455. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  21456. return false;
  21457. }
  21458. this._checkDelayState();
  21459. return true;
  21460. };
  21461. /**
  21462. * Sets the mesh material by the material or multiMaterial `id` property.
  21463. * The material `id` is a string identifying the material or the multiMaterial.
  21464. * This method returns the Mesh.
  21465. */
  21466. Mesh.prototype.setMaterialByID = function (id) {
  21467. var materials = this.getScene().materials;
  21468. var index;
  21469. for (index = materials.length - 1; index > -1; index--) {
  21470. if (materials[index].id === id) {
  21471. this.material = materials[index];
  21472. return this;
  21473. }
  21474. }
  21475. // Multi
  21476. var multiMaterials = this.getScene().multiMaterials;
  21477. for (index = multiMaterials.length - 1; index > -1; index--) {
  21478. if (multiMaterials[index].id === id) {
  21479. this.material = multiMaterials[index];
  21480. return this;
  21481. }
  21482. }
  21483. return this;
  21484. };
  21485. /**
  21486. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  21487. */
  21488. Mesh.prototype.getAnimatables = function () {
  21489. var results = [];
  21490. if (this.material) {
  21491. results.push(this.material);
  21492. }
  21493. if (this.skeleton) {
  21494. results.push(this.skeleton);
  21495. }
  21496. return results;
  21497. };
  21498. /**
  21499. * Modifies the mesh geometry according to the passed transformation matrix.
  21500. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  21501. * The mesh normals are modified accordingly the same transformation.
  21502. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  21503. * Note that, under the hood, this method sets a new VertexBuffer each call.
  21504. * Returns the Mesh.
  21505. */
  21506. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  21507. // Position
  21508. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21509. return this;
  21510. }
  21511. var submeshes = this.subMeshes.splice(0);
  21512. this._resetPointsArrayCache();
  21513. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21514. var temp = [];
  21515. var index;
  21516. for (index = 0; index < data.length; index += 3) {
  21517. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  21518. }
  21519. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  21520. // Normals
  21521. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21522. return this;
  21523. }
  21524. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21525. temp = [];
  21526. for (index = 0; index < data.length; index += 3) {
  21527. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  21528. }
  21529. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  21530. // flip faces?
  21531. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  21532. this.flipFaces();
  21533. }
  21534. // Restore submeshes
  21535. this.releaseSubMeshes();
  21536. this.subMeshes = submeshes;
  21537. return this;
  21538. };
  21539. /**
  21540. * Modifies the mesh geometry according to its own current World Matrix.
  21541. * The mesh World Matrix is then reset.
  21542. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  21543. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  21544. * Note that, under the hood, this method sets a new VertexBuffer each call.
  21545. * Returns the Mesh.
  21546. */
  21547. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  21548. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  21549. this.scaling.copyFromFloats(1, 1, 1);
  21550. this.position.copyFromFloats(0, 0, 0);
  21551. this.rotation.copyFromFloats(0, 0, 0);
  21552. //only if quaternion is already set
  21553. if (this.rotationQuaternion) {
  21554. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  21555. }
  21556. this._worldMatrix = BABYLON.Matrix.Identity();
  21557. return this;
  21558. };
  21559. Object.defineProperty(Mesh.prototype, "_positions", {
  21560. // Cache
  21561. get: function () {
  21562. if (this._geometry) {
  21563. return this._geometry._positions;
  21564. }
  21565. return null;
  21566. },
  21567. enumerable: true,
  21568. configurable: true
  21569. });
  21570. Mesh.prototype._resetPointsArrayCache = function () {
  21571. if (this._geometry) {
  21572. this._geometry._resetPointsArrayCache();
  21573. }
  21574. return this;
  21575. };
  21576. Mesh.prototype._generatePointsArray = function () {
  21577. if (this._geometry) {
  21578. return this._geometry._generatePointsArray();
  21579. }
  21580. return false;
  21581. };
  21582. /**
  21583. * Returns a new Mesh object generated from the current mesh properties.
  21584. * This method must not get confused with createInstance().
  21585. * The parameter `name` is a string, the name given to the new mesh.
  21586. * The optional parameter `newParent` can be any Node object (default `null`).
  21587. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  21588. * 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.
  21589. */
  21590. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  21591. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  21592. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  21593. };
  21594. /**
  21595. * Disposes the mesh.
  21596. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  21597. */
  21598. Mesh.prototype.dispose = function (doNotRecurse) {
  21599. var _this = this;
  21600. this.morphTargetManager = undefined;
  21601. if (this._geometry) {
  21602. this._geometry.releaseForMesh(this, true);
  21603. }
  21604. // Sources
  21605. var meshes = this.getScene().meshes;
  21606. meshes.forEach(function (mesh) {
  21607. if (mesh._source && mesh._source === _this) {
  21608. mesh._source = null;
  21609. }
  21610. });
  21611. this._source = null;
  21612. // Instances
  21613. if (this._instancesBuffer) {
  21614. this._instancesBuffer.dispose();
  21615. this._instancesBuffer = null;
  21616. }
  21617. while (this.instances.length) {
  21618. this.instances[0].dispose();
  21619. }
  21620. // Highlight layers.
  21621. var highlightLayers = this.getScene().highlightLayers;
  21622. for (var i = 0; i < highlightLayers.length; i++) {
  21623. var highlightLayer = highlightLayers[i];
  21624. if (highlightLayer) {
  21625. highlightLayer.removeMesh(this);
  21626. highlightLayer.removeExcludedMesh(this);
  21627. }
  21628. }
  21629. _super.prototype.dispose.call(this, doNotRecurse);
  21630. };
  21631. /**
  21632. * Modifies the mesh geometry according to a displacement map.
  21633. * 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.
  21634. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  21635. * This method returns nothing.
  21636. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  21637. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  21638. * 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.
  21639. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  21640. * The parameter `uvScale` is an optional vector2 used to scale UV.
  21641. *
  21642. * Returns the Mesh.
  21643. */
  21644. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  21645. var _this = this;
  21646. var scene = this.getScene();
  21647. var onload = function (img) {
  21648. // Getting height map data
  21649. var canvas = document.createElement("canvas");
  21650. var context = canvas.getContext("2d");
  21651. var heightMapWidth = img.width;
  21652. var heightMapHeight = img.height;
  21653. canvas.width = heightMapWidth;
  21654. canvas.height = heightMapHeight;
  21655. context.drawImage(img, 0, 0);
  21656. // Create VertexData from map data
  21657. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  21658. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  21659. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  21660. //execute success callback, if set
  21661. if (onSuccess) {
  21662. onSuccess(_this);
  21663. }
  21664. };
  21665. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  21666. return this;
  21667. };
  21668. /**
  21669. * Modifies the mesh geometry according to a displacementMap buffer.
  21670. * 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.
  21671. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  21672. * This method returns nothing.
  21673. * 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.
  21674. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  21675. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  21676. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  21677. * The parameter `uvScale` is an optional vector2 used to scale UV.
  21678. *
  21679. * Returns the Mesh.
  21680. */
  21681. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  21682. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  21683. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  21684. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  21685. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  21686. return this;
  21687. }
  21688. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21689. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21690. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  21691. var position = BABYLON.Vector3.Zero();
  21692. var normal = BABYLON.Vector3.Zero();
  21693. var uv = BABYLON.Vector2.Zero();
  21694. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  21695. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  21696. for (var index = 0; index < positions.length; index += 3) {
  21697. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  21698. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  21699. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  21700. // Compute height
  21701. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  21702. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  21703. var pos = (u + v * heightMapWidth) * 4;
  21704. var r = buffer[pos] / 255.0;
  21705. var g = buffer[pos + 1] / 255.0;
  21706. var b = buffer[pos + 2] / 255.0;
  21707. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  21708. normal.normalize();
  21709. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  21710. position = position.add(normal);
  21711. position.toArray(positions, index);
  21712. }
  21713. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  21714. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  21715. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  21716. return this;
  21717. };
  21718. /**
  21719. * Modify the mesh to get a flat shading rendering.
  21720. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  21721. * This method returns the Mesh.
  21722. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  21723. */
  21724. Mesh.prototype.convertToFlatShadedMesh = function () {
  21725. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  21726. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  21727. var kinds = this.getVerticesDataKinds();
  21728. var vbs = [];
  21729. var data = [];
  21730. var newdata = [];
  21731. var updatableNormals = false;
  21732. var kindIndex;
  21733. var kind;
  21734. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21735. kind = kinds[kindIndex];
  21736. var vertexBuffer = this.getVertexBuffer(kind);
  21737. if (kind === BABYLON.VertexBuffer.NormalKind) {
  21738. updatableNormals = vertexBuffer.isUpdatable();
  21739. kinds.splice(kindIndex, 1);
  21740. kindIndex--;
  21741. continue;
  21742. }
  21743. vbs[kind] = vertexBuffer;
  21744. data[kind] = vbs[kind].getData();
  21745. newdata[kind] = [];
  21746. }
  21747. // Save previous submeshes
  21748. var previousSubmeshes = this.subMeshes.slice(0);
  21749. var indices = this.getIndices();
  21750. var totalIndices = this.getTotalIndices();
  21751. // Generating unique vertices per face
  21752. var index;
  21753. for (index = 0; index < totalIndices; index++) {
  21754. var vertexIndex = indices[index];
  21755. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21756. kind = kinds[kindIndex];
  21757. var stride = vbs[kind].getStrideSize();
  21758. for (var offset = 0; offset < stride; offset++) {
  21759. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  21760. }
  21761. }
  21762. }
  21763. // Updating faces & normal
  21764. var normals = [];
  21765. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  21766. for (index = 0; index < totalIndices; index += 3) {
  21767. indices[index] = index;
  21768. indices[index + 1] = index + 1;
  21769. indices[index + 2] = index + 2;
  21770. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  21771. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  21772. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  21773. var p1p2 = p1.subtract(p2);
  21774. var p3p2 = p3.subtract(p2);
  21775. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  21776. // Store same normals for every vertex
  21777. for (var localIndex = 0; localIndex < 3; localIndex++) {
  21778. normals.push(normal.x);
  21779. normals.push(normal.y);
  21780. normals.push(normal.z);
  21781. }
  21782. }
  21783. this.setIndices(indices);
  21784. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  21785. // Updating vertex buffers
  21786. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21787. kind = kinds[kindIndex];
  21788. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  21789. }
  21790. // Updating submeshes
  21791. this.releaseSubMeshes();
  21792. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  21793. var previousOne = previousSubmeshes[submeshIndex];
  21794. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  21795. }
  21796. this.synchronizeInstances();
  21797. return this;
  21798. };
  21799. /**
  21800. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  21801. * In other words, more vertices, no more indices and a single bigger VBO.
  21802. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  21803. * Returns the Mesh.
  21804. */
  21805. Mesh.prototype.convertToUnIndexedMesh = function () {
  21806. /// <summary>Remove indices by unfolding faces into buffers</summary>
  21807. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  21808. var kinds = this.getVerticesDataKinds();
  21809. var vbs = [];
  21810. var data = [];
  21811. var newdata = [];
  21812. var updatableNormals = false;
  21813. var kindIndex;
  21814. var kind;
  21815. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21816. kind = kinds[kindIndex];
  21817. var vertexBuffer = this.getVertexBuffer(kind);
  21818. vbs[kind] = vertexBuffer;
  21819. data[kind] = vbs[kind].getData();
  21820. newdata[kind] = [];
  21821. }
  21822. // Save previous submeshes
  21823. var previousSubmeshes = this.subMeshes.slice(0);
  21824. var indices = this.getIndices();
  21825. var totalIndices = this.getTotalIndices();
  21826. // Generating unique vertices per face
  21827. var index;
  21828. for (index = 0; index < totalIndices; index++) {
  21829. var vertexIndex = indices[index];
  21830. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21831. kind = kinds[kindIndex];
  21832. var stride = vbs[kind].getStrideSize();
  21833. for (var offset = 0; offset < stride; offset++) {
  21834. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  21835. }
  21836. }
  21837. }
  21838. // Updating indices
  21839. for (index = 0; index < totalIndices; index += 3) {
  21840. indices[index] = index;
  21841. indices[index + 1] = index + 1;
  21842. indices[index + 2] = index + 2;
  21843. }
  21844. this.setIndices(indices);
  21845. // Updating vertex buffers
  21846. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21847. kind = kinds[kindIndex];
  21848. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  21849. }
  21850. // Updating submeshes
  21851. this.releaseSubMeshes();
  21852. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  21853. var previousOne = previousSubmeshes[submeshIndex];
  21854. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  21855. }
  21856. this._unIndexed = true;
  21857. this.synchronizeInstances();
  21858. return this;
  21859. };
  21860. /**
  21861. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  21862. * This method returns the Mesh.
  21863. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  21864. */
  21865. Mesh.prototype.flipFaces = function (flipNormals) {
  21866. if (flipNormals === void 0) { flipNormals = false; }
  21867. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  21868. var i;
  21869. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21870. for (i = 0; i < vertex_data.normals.length; i++) {
  21871. vertex_data.normals[i] *= -1;
  21872. }
  21873. }
  21874. var temp;
  21875. for (i = 0; i < vertex_data.indices.length; i += 3) {
  21876. // reassign indices
  21877. temp = vertex_data.indices[i + 1];
  21878. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  21879. vertex_data.indices[i + 2] = temp;
  21880. }
  21881. vertex_data.applyToMesh(this);
  21882. return this;
  21883. };
  21884. // Instances
  21885. /**
  21886. * Creates a new InstancedMesh object from the mesh model.
  21887. * An instance shares the same properties and the same material than its model.
  21888. * Only these properties of each instance can then be set individually :
  21889. * - position
  21890. * - rotation
  21891. * - rotationQuaternion
  21892. * - setPivotMatrix
  21893. * - scaling
  21894. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  21895. * Warning : this method is not supported for Line mesh and LineSystem
  21896. */
  21897. Mesh.prototype.createInstance = function (name) {
  21898. return new BABYLON.InstancedMesh(name, this);
  21899. };
  21900. /**
  21901. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  21902. * After this call, all the mesh instances have the same submeshes than the current mesh.
  21903. * This method returns the Mesh.
  21904. */
  21905. Mesh.prototype.synchronizeInstances = function () {
  21906. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  21907. var instance = this.instances[instanceIndex];
  21908. instance._syncSubMeshes();
  21909. }
  21910. return this;
  21911. };
  21912. /**
  21913. * Simplify the mesh according to the given array of settings.
  21914. * Function will return immediately and will simplify async. It returns the Mesh.
  21915. * @param settings a collection of simplification settings.
  21916. * @param parallelProcessing should all levels calculate parallel or one after the other.
  21917. * @param type the type of simplification to run.
  21918. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  21919. */
  21920. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  21921. if (parallelProcessing === void 0) { parallelProcessing = true; }
  21922. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  21923. this.getScene().simplificationQueue.addTask({
  21924. settings: settings,
  21925. parallelProcessing: parallelProcessing,
  21926. mesh: this,
  21927. simplificationType: simplificationType,
  21928. successCallback: successCallback
  21929. });
  21930. return this;
  21931. };
  21932. /**
  21933. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  21934. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  21935. * This should be used together with the simplification to avoid disappearing triangles.
  21936. * Returns the Mesh.
  21937. * @param successCallback an optional success callback to be called after the optimization finished.
  21938. */
  21939. Mesh.prototype.optimizeIndices = function (successCallback) {
  21940. var _this = this;
  21941. var indices = this.getIndices();
  21942. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21943. var vectorPositions = [];
  21944. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  21945. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  21946. }
  21947. var dupes = [];
  21948. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  21949. var realPos = vectorPositions.length - 1 - iteration;
  21950. var testedPosition = vectorPositions[realPos];
  21951. for (var j = 0; j < realPos; ++j) {
  21952. var againstPosition = vectorPositions[j];
  21953. if (testedPosition.equals(againstPosition)) {
  21954. dupes[realPos] = j;
  21955. break;
  21956. }
  21957. }
  21958. }, function () {
  21959. for (var i = 0; i < indices.length; ++i) {
  21960. indices[i] = dupes[indices[i]] || indices[i];
  21961. }
  21962. //indices are now reordered
  21963. var originalSubMeshes = _this.subMeshes.slice(0);
  21964. _this.setIndices(indices);
  21965. _this.subMeshes = originalSubMeshes;
  21966. if (successCallback) {
  21967. successCallback(_this);
  21968. }
  21969. });
  21970. return this;
  21971. };
  21972. Mesh.prototype.serialize = function (serializationObject) {
  21973. serializationObject.name = this.name;
  21974. serializationObject.id = this.id;
  21975. serializationObject.type = this.getClassName();
  21976. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  21977. serializationObject.tags = BABYLON.Tags.GetTags(this);
  21978. }
  21979. serializationObject.position = this.position.asArray();
  21980. if (this.rotationQuaternion) {
  21981. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  21982. }
  21983. else if (this.rotation) {
  21984. serializationObject.rotation = this.rotation.asArray();
  21985. }
  21986. serializationObject.scaling = this.scaling.asArray();
  21987. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  21988. serializationObject.isEnabled = this.isEnabled();
  21989. serializationObject.isVisible = this.isVisible;
  21990. serializationObject.infiniteDistance = this.infiniteDistance;
  21991. serializationObject.pickable = this.isPickable;
  21992. serializationObject.receiveShadows = this.receiveShadows;
  21993. serializationObject.billboardMode = this.billboardMode;
  21994. serializationObject.visibility = this.visibility;
  21995. serializationObject.checkCollisions = this.checkCollisions;
  21996. serializationObject.isBlocker = this.isBlocker;
  21997. // Parent
  21998. if (this.parent) {
  21999. serializationObject.parentId = this.parent.id;
  22000. }
  22001. // Geometry
  22002. var geometry = this._geometry;
  22003. if (geometry) {
  22004. var geometryId = geometry.id;
  22005. serializationObject.geometryId = geometryId;
  22006. // SubMeshes
  22007. serializationObject.subMeshes = [];
  22008. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  22009. var subMesh = this.subMeshes[subIndex];
  22010. serializationObject.subMeshes.push({
  22011. materialIndex: subMesh.materialIndex,
  22012. verticesStart: subMesh.verticesStart,
  22013. verticesCount: subMesh.verticesCount,
  22014. indexStart: subMesh.indexStart,
  22015. indexCount: subMesh.indexCount
  22016. });
  22017. }
  22018. }
  22019. // Material
  22020. if (this.material) {
  22021. serializationObject.materialId = this.material.id;
  22022. }
  22023. else {
  22024. this.material = null;
  22025. }
  22026. // Morph targets
  22027. if (this.morphTargetManager) {
  22028. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  22029. }
  22030. // Skeleton
  22031. if (this.skeleton) {
  22032. serializationObject.skeletonId = this.skeleton.id;
  22033. }
  22034. // Physics
  22035. //TODO implement correct serialization for physics impostors.
  22036. if (this.getPhysicsImpostor()) {
  22037. var impostor = this.getPhysicsImpostor();
  22038. serializationObject.physicsMass = impostor.getParam("mass");
  22039. serializationObject.physicsFriction = impostor.getParam("friction");
  22040. serializationObject.physicsRestitution = impostor.getParam("mass");
  22041. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  22042. }
  22043. // Metadata
  22044. if (this.metadata) {
  22045. serializationObject.metadata = this.metadata;
  22046. }
  22047. // Instances
  22048. serializationObject.instances = [];
  22049. for (var index = 0; index < this.instances.length; index++) {
  22050. var instance = this.instances[index];
  22051. var serializationInstance = {
  22052. name: instance.name,
  22053. position: instance.position.asArray(),
  22054. scaling: instance.scaling.asArray()
  22055. };
  22056. if (instance.rotationQuaternion) {
  22057. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  22058. }
  22059. else if (instance.rotation) {
  22060. serializationInstance.rotation = instance.rotation.asArray();
  22061. }
  22062. serializationObject.instances.push(serializationInstance);
  22063. // Animations
  22064. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  22065. serializationInstance.ranges = instance.serializeAnimationRanges();
  22066. }
  22067. //
  22068. // Animations
  22069. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22070. serializationObject.ranges = this.serializeAnimationRanges();
  22071. // Layer mask
  22072. serializationObject.layerMask = this.layerMask;
  22073. // Alpha
  22074. serializationObject.alphaIndex = this.alphaIndex;
  22075. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  22076. // Overlay
  22077. serializationObject.overlayAlpha = this.overlayAlpha;
  22078. serializationObject.overlayColor = this.overlayColor.asArray();
  22079. serializationObject.renderOverlay = this.renderOverlay;
  22080. // Fog
  22081. serializationObject.applyFog = this.applyFog;
  22082. // Action Manager
  22083. if (this.actionManager) {
  22084. serializationObject.actions = this.actionManager.serialize(this.name);
  22085. }
  22086. };
  22087. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  22088. if (!this.geometry) {
  22089. return;
  22090. }
  22091. this._markSubMeshesAsAttributesDirty();
  22092. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  22093. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  22094. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  22095. this.morphTargetManager = undefined;
  22096. return;
  22097. }
  22098. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  22099. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  22100. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  22101. if (morphTarget.hasNormals) {
  22102. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  22103. }
  22104. if (morphTarget.hasTangents) {
  22105. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  22106. }
  22107. }
  22108. }
  22109. else {
  22110. var index = 0;
  22111. // Positions
  22112. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  22113. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  22114. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  22115. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  22116. }
  22117. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  22118. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  22119. }
  22120. index++;
  22121. }
  22122. }
  22123. };
  22124. // Statics
  22125. /**
  22126. * Returns a new Mesh object what is a deep copy of the passed mesh.
  22127. * The parameter `parsedMesh` is the mesh to be copied.
  22128. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  22129. */
  22130. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  22131. var mesh;
  22132. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  22133. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  22134. }
  22135. else {
  22136. mesh = new Mesh(parsedMesh.name, scene);
  22137. }
  22138. mesh.id = parsedMesh.id;
  22139. if (BABYLON.Tags) {
  22140. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  22141. }
  22142. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  22143. if (parsedMesh.metadata !== undefined) {
  22144. mesh.metadata = parsedMesh.metadata;
  22145. }
  22146. if (parsedMesh.rotationQuaternion) {
  22147. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  22148. }
  22149. else if (parsedMesh.rotation) {
  22150. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  22151. }
  22152. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  22153. if (parsedMesh.localMatrix) {
  22154. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  22155. }
  22156. else if (parsedMesh.pivotMatrix) {
  22157. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  22158. }
  22159. mesh.setEnabled(parsedMesh.isEnabled);
  22160. mesh.isVisible = parsedMesh.isVisible;
  22161. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  22162. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  22163. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  22164. if (parsedMesh.applyFog !== undefined) {
  22165. mesh.applyFog = parsedMesh.applyFog;
  22166. }
  22167. if (parsedMesh.pickable !== undefined) {
  22168. mesh.isPickable = parsedMesh.pickable;
  22169. }
  22170. if (parsedMesh.alphaIndex !== undefined) {
  22171. mesh.alphaIndex = parsedMesh.alphaIndex;
  22172. }
  22173. mesh.receiveShadows = parsedMesh.receiveShadows;
  22174. mesh.billboardMode = parsedMesh.billboardMode;
  22175. if (parsedMesh.visibility !== undefined) {
  22176. mesh.visibility = parsedMesh.visibility;
  22177. }
  22178. mesh.checkCollisions = parsedMesh.checkCollisions;
  22179. if (parsedMesh.isBlocker !== undefined) {
  22180. mesh.isBlocker = parsedMesh.isBlocker;
  22181. }
  22182. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  22183. // freezeWorldMatrix
  22184. if (parsedMesh.freezeWorldMatrix) {
  22185. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  22186. }
  22187. // Parent
  22188. if (parsedMesh.parentId) {
  22189. mesh._waitingParentId = parsedMesh.parentId;
  22190. }
  22191. // Actions
  22192. if (parsedMesh.actions !== undefined) {
  22193. mesh._waitingActions = parsedMesh.actions;
  22194. }
  22195. // Overlay
  22196. if (parsedMesh.overlayAlpha !== undefined) {
  22197. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  22198. }
  22199. if (parsedMesh.overlayColor !== undefined) {
  22200. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  22201. }
  22202. if (parsedMesh.renderOverlay !== undefined) {
  22203. mesh.renderOverlay = parsedMesh.renderOverlay;
  22204. }
  22205. // Geometry
  22206. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  22207. if (parsedMesh.delayLoadingFile) {
  22208. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22209. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  22210. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  22211. if (parsedMesh._binaryInfo) {
  22212. mesh._binaryInfo = parsedMesh._binaryInfo;
  22213. }
  22214. mesh._delayInfo = [];
  22215. if (parsedMesh.hasUVs) {
  22216. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  22217. }
  22218. if (parsedMesh.hasUVs2) {
  22219. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  22220. }
  22221. if (parsedMesh.hasUVs3) {
  22222. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  22223. }
  22224. if (parsedMesh.hasUVs4) {
  22225. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  22226. }
  22227. if (parsedMesh.hasUVs5) {
  22228. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  22229. }
  22230. if (parsedMesh.hasUVs6) {
  22231. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  22232. }
  22233. if (parsedMesh.hasColors) {
  22234. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  22235. }
  22236. if (parsedMesh.hasMatricesIndices) {
  22237. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  22238. }
  22239. if (parsedMesh.hasMatricesWeights) {
  22240. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  22241. }
  22242. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  22243. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  22244. mesh._checkDelayState();
  22245. }
  22246. }
  22247. else {
  22248. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  22249. }
  22250. // Material
  22251. if (parsedMesh.materialId) {
  22252. mesh.setMaterialByID(parsedMesh.materialId);
  22253. }
  22254. else {
  22255. mesh.material = null;
  22256. }
  22257. // Morph targets
  22258. if (parsedMesh.morphTargetManagerId > -1) {
  22259. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  22260. }
  22261. // Skeleton
  22262. if (parsedMesh.skeletonId > -1) {
  22263. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  22264. if (parsedMesh.numBoneInfluencers) {
  22265. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  22266. }
  22267. }
  22268. // Animations
  22269. if (parsedMesh.animations) {
  22270. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  22271. var parsedAnimation = parsedMesh.animations[animationIndex];
  22272. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22273. }
  22274. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  22275. }
  22276. if (parsedMesh.autoAnimate) {
  22277. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  22278. }
  22279. // Layer Mask
  22280. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  22281. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  22282. }
  22283. else {
  22284. mesh.layerMask = 0x0FFFFFFF;
  22285. }
  22286. // Physics
  22287. if (parsedMesh.physicsImpostor) {
  22288. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  22289. mass: parsedMesh.physicsMass,
  22290. friction: parsedMesh.physicsFriction,
  22291. restitution: parsedMesh.physicsRestitution
  22292. }, scene);
  22293. }
  22294. // Instances
  22295. if (parsedMesh.instances) {
  22296. for (var index = 0; index < parsedMesh.instances.length; index++) {
  22297. var parsedInstance = parsedMesh.instances[index];
  22298. var instance = mesh.createInstance(parsedInstance.name);
  22299. if (BABYLON.Tags) {
  22300. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  22301. }
  22302. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  22303. if (parsedInstance.parentId) {
  22304. instance._waitingParentId = parsedInstance.parentId;
  22305. }
  22306. if (parsedInstance.rotationQuaternion) {
  22307. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  22308. }
  22309. else if (parsedInstance.rotation) {
  22310. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  22311. }
  22312. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  22313. instance.checkCollisions = mesh.checkCollisions;
  22314. if (parsedMesh.animations) {
  22315. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  22316. parsedAnimation = parsedMesh.animations[animationIndex];
  22317. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22318. }
  22319. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  22320. }
  22321. }
  22322. }
  22323. return mesh;
  22324. };
  22325. /**
  22326. * Creates a ribbon mesh.
  22327. * Please consider using the same method from the MeshBuilder class instead.
  22328. * 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.
  22329. *
  22330. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  22331. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  22332. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  22333. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  22334. * 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.
  22335. * 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.
  22336. * 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
  22337. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22338. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22339. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22340. */
  22341. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  22342. return BABYLON.MeshBuilder.CreateRibbon(name, {
  22343. pathArray: pathArray,
  22344. closeArray: closeArray,
  22345. closePath: closePath,
  22346. offset: offset,
  22347. updatable: updatable,
  22348. sideOrientation: sideOrientation,
  22349. instance: instance
  22350. }, scene);
  22351. };
  22352. /**
  22353. * Creates a plane polygonal mesh. By default, this is a disc.
  22354. * Please consider using the same method from the MeshBuilder class instead.
  22355. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  22356. * 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.
  22357. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22358. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22359. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22360. */
  22361. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  22362. var options = {
  22363. radius: radius,
  22364. tessellation: tessellation,
  22365. sideOrientation: sideOrientation,
  22366. updatable: updatable
  22367. };
  22368. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  22369. };
  22370. /**
  22371. * Creates a box mesh.
  22372. * Please consider using the same method from the MeshBuilder class instead.
  22373. * The parameter `size` sets the size (float) of each box side (default 1).
  22374. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22375. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22376. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22377. */
  22378. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  22379. var options = {
  22380. size: size,
  22381. sideOrientation: sideOrientation,
  22382. updatable: updatable
  22383. };
  22384. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  22385. };
  22386. /**
  22387. * Creates a sphere mesh.
  22388. * Please consider using the same method from the MeshBuilder class instead.
  22389. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  22390. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  22391. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22392. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22393. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22394. */
  22395. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  22396. var options = {
  22397. segments: segments,
  22398. diameterX: diameter,
  22399. diameterY: diameter,
  22400. diameterZ: diameter,
  22401. sideOrientation: sideOrientation,
  22402. updatable: updatable
  22403. };
  22404. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  22405. };
  22406. /**
  22407. * Creates a cylinder or a cone mesh.
  22408. * Please consider using the same method from the MeshBuilder class instead.
  22409. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  22410. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  22411. * 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.
  22412. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  22413. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  22414. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22415. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22416. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22417. */
  22418. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  22419. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  22420. if (scene !== undefined) {
  22421. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  22422. updatable = scene;
  22423. }
  22424. scene = subdivisions;
  22425. subdivisions = 1;
  22426. }
  22427. var options = {
  22428. height: height,
  22429. diameterTop: diameterTop,
  22430. diameterBottom: diameterBottom,
  22431. tessellation: tessellation,
  22432. subdivisions: subdivisions,
  22433. sideOrientation: sideOrientation,
  22434. updatable: updatable
  22435. };
  22436. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  22437. };
  22438. // Torus (Code from SharpDX.org)
  22439. /**
  22440. * Creates a torus mesh.
  22441. * Please consider using the same method from the MeshBuilder class instead.
  22442. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  22443. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  22444. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  22445. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22446. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22447. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22448. */
  22449. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  22450. var options = {
  22451. diameter: diameter,
  22452. thickness: thickness,
  22453. tessellation: tessellation,
  22454. sideOrientation: sideOrientation,
  22455. updatable: updatable
  22456. };
  22457. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  22458. };
  22459. /**
  22460. * Creates a torus knot mesh.
  22461. * Please consider using the same method from the MeshBuilder class instead.
  22462. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  22463. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  22464. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  22465. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  22466. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22467. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22468. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22469. */
  22470. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  22471. var options = {
  22472. radius: radius,
  22473. tube: tube,
  22474. radialSegments: radialSegments,
  22475. tubularSegments: tubularSegments,
  22476. p: p,
  22477. q: q,
  22478. sideOrientation: sideOrientation,
  22479. updatable: updatable
  22480. };
  22481. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  22482. };
  22483. /**
  22484. * Creates a line mesh.
  22485. * Please consider using the same method from the MeshBuilder class instead.
  22486. * 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.
  22487. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22488. * The parameter `points` is an array successive Vector3.
  22489. * 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
  22490. * When updating an instance, remember that only point positions can change, not the number of points.
  22491. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22492. */
  22493. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  22494. var options = {
  22495. points: points,
  22496. updatable: updatable,
  22497. instance: instance
  22498. };
  22499. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  22500. };
  22501. /**
  22502. * Creates a dashed line mesh.
  22503. * Please consider using the same method from the MeshBuilder class instead.
  22504. * 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.
  22505. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22506. * The parameter `points` is an array successive Vector3.
  22507. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  22508. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  22509. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  22510. * 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
  22511. * When updating an instance, remember that only point positions can change, not the number of points.
  22512. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22513. */
  22514. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  22515. var options = {
  22516. points: points,
  22517. dashSize: dashSize,
  22518. gapSize: gapSize,
  22519. dashNb: dashNb,
  22520. updatable: updatable,
  22521. instance: instance
  22522. };
  22523. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  22524. };
  22525. /**
  22526. * Creates a polygon mesh.
  22527. * Please consider using the same method from the MeshBuilder class instead.
  22528. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  22529. * 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.
  22530. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22531. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22532. * Remember you can only change the shape positions, not their number when updating a polygon.
  22533. */
  22534. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  22535. var options = {
  22536. shape: shape,
  22537. holes: holes,
  22538. updatable: updatable,
  22539. sideOrientation: sideOrientation
  22540. };
  22541. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  22542. };
  22543. /**
  22544. * Creates an extruded polygon mesh, with depth in the Y direction.
  22545. * Please consider using the same method from the MeshBuilder class instead.
  22546. */
  22547. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  22548. var options = {
  22549. shape: shape,
  22550. holes: holes,
  22551. depth: depth,
  22552. updatable: updatable,
  22553. sideOrientation: sideOrientation
  22554. };
  22555. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  22556. };
  22557. /**
  22558. * Creates an extruded shape mesh.
  22559. * 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.
  22560. * Please consider using the same method from the MeshBuilder class instead.
  22561. *
  22562. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  22563. * 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
  22564. * extruded along the Z axis.
  22565. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  22566. * 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.
  22567. * The parameter `scale` (float, default 1) is the value to scale the shape.
  22568. * 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
  22569. * 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
  22570. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22571. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22572. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22573. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22574. */
  22575. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  22576. var options = {
  22577. shape: shape,
  22578. path: path,
  22579. scale: scale,
  22580. rotation: rotation,
  22581. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  22582. sideOrientation: sideOrientation,
  22583. instance: instance,
  22584. updatable: updatable
  22585. };
  22586. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  22587. };
  22588. /**
  22589. * Creates an custom extruded shape mesh.
  22590. * 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.
  22591. * Please consider using the same method from the MeshBuilder class instead.
  22592. *
  22593. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  22594. * 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
  22595. * extruded along the Z axis.
  22596. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  22597. * 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
  22598. * and the distance of this point from the begining of the path :
  22599. * ```javascript
  22600. * var rotationFunction = function(i, distance) {
  22601. * // do things
  22602. * return rotationValue; }
  22603. * ```
  22604. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  22605. * 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
  22606. * and the distance of this point from the begining of the path :
  22607. * ```javascript
  22608. * var scaleFunction = function(i, distance) {
  22609. * // do things
  22610. * return scaleValue;}
  22611. * ```
  22612. * It must returns a float value that will be the scale value applied to the shape on each path point.
  22613. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  22614. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  22615. * 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
  22616. * 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
  22617. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22618. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22619. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22620. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22621. */
  22622. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  22623. var options = {
  22624. shape: shape,
  22625. path: path,
  22626. scaleFunction: scaleFunction,
  22627. rotationFunction: rotationFunction,
  22628. ribbonCloseArray: ribbonCloseArray,
  22629. ribbonClosePath: ribbonClosePath,
  22630. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  22631. sideOrientation: sideOrientation,
  22632. instance: instance,
  22633. updatable: updatable
  22634. };
  22635. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  22636. };
  22637. /**
  22638. * Creates lathe mesh.
  22639. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  22640. * Please consider using the same method from the MeshBuilder class instead.
  22641. * 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
  22642. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  22643. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  22644. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  22645. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22646. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22647. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22648. */
  22649. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  22650. var options = {
  22651. shape: shape,
  22652. radius: radius,
  22653. tessellation: tessellation,
  22654. sideOrientation: sideOrientation,
  22655. updatable: updatable
  22656. };
  22657. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  22658. };
  22659. /**
  22660. * Creates a plane mesh.
  22661. * Please consider using the same method from the MeshBuilder class instead.
  22662. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  22663. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22664. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22665. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22666. */
  22667. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  22668. var options = {
  22669. size: size,
  22670. width: size,
  22671. height: size,
  22672. sideOrientation: sideOrientation,
  22673. updatable: updatable
  22674. };
  22675. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  22676. };
  22677. /**
  22678. * Creates a ground mesh.
  22679. * Please consider using the same method from the MeshBuilder class instead.
  22680. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  22681. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  22682. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22683. */
  22684. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  22685. var options = {
  22686. width: width,
  22687. height: height,
  22688. subdivisions: subdivisions,
  22689. updatable: updatable
  22690. };
  22691. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  22692. };
  22693. /**
  22694. * Creates a tiled ground mesh.
  22695. * Please consider using the same method from the MeshBuilder class instead.
  22696. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  22697. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  22698. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  22699. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  22700. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  22701. * numbers of subdivisions on the ground width and height of each tile.
  22702. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22703. */
  22704. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  22705. var options = {
  22706. xmin: xmin,
  22707. zmin: zmin,
  22708. xmax: xmax,
  22709. zmax: zmax,
  22710. subdivisions: subdivisions,
  22711. precision: precision,
  22712. updatable: updatable
  22713. };
  22714. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  22715. };
  22716. /**
  22717. * Creates a ground mesh from a height map.
  22718. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  22719. * Please consider using the same method from the MeshBuilder class instead.
  22720. * The parameter `url` sets the URL of the height map image resource.
  22721. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  22722. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  22723. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  22724. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  22725. * 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).
  22726. * This function is passed the newly built mesh :
  22727. * ```javascript
  22728. * function(mesh) { // do things
  22729. * return; }
  22730. * ```
  22731. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22732. */
  22733. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  22734. var options = {
  22735. width: width,
  22736. height: height,
  22737. subdivisions: subdivisions,
  22738. minHeight: minHeight,
  22739. maxHeight: maxHeight,
  22740. updatable: updatable,
  22741. onReady: onReady
  22742. };
  22743. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  22744. };
  22745. /**
  22746. * Creates a tube mesh.
  22747. * 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.
  22748. * Please consider using the same method from the MeshBuilder class instead.
  22749. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  22750. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  22751. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  22752. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  22753. * 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.
  22754. * It must return a radius value (positive float) :
  22755. * ```javascript
  22756. * var radiusFunction = function(i, distance) {
  22757. * // do things
  22758. * return radius; }
  22759. * ```
  22760. * 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
  22761. * 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
  22762. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22763. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22764. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22765. */
  22766. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  22767. var options = {
  22768. path: path,
  22769. radius: radius,
  22770. tessellation: tessellation,
  22771. radiusFunction: radiusFunction,
  22772. arc: 1,
  22773. cap: cap,
  22774. updatable: updatable,
  22775. sideOrientation: sideOrientation,
  22776. instance: instance
  22777. };
  22778. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  22779. };
  22780. /**
  22781. * Creates a polyhedron mesh.
  22782. * Please consider using the same method from the MeshBuilder class instead.
  22783. * 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
  22784. * to choose the wanted type.
  22785. * The parameter `size` (positive float, default 1) sets the polygon size.
  22786. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  22787. * 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`.
  22788. * 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
  22789. * 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)`).
  22790. * 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
  22791. * 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.
  22792. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22793. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22794. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22795. */
  22796. Mesh.CreatePolyhedron = function (name, options, scene) {
  22797. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  22798. };
  22799. /**
  22800. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  22801. * Please consider using the same method from the MeshBuilder class instead.
  22802. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  22803. * 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`).
  22804. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  22805. * 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.
  22806. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22807. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22808. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22809. */
  22810. Mesh.CreateIcoSphere = function (name, options, scene) {
  22811. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  22812. };
  22813. /**
  22814. * Creates a decal mesh.
  22815. * Please consider using the same method from the MeshBuilder class instead.
  22816. * 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.
  22817. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  22818. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  22819. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  22820. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  22821. */
  22822. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  22823. var options = {
  22824. position: position,
  22825. normal: normal,
  22826. size: size,
  22827. angle: angle
  22828. };
  22829. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  22830. };
  22831. // Skeletons
  22832. /**
  22833. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  22834. */
  22835. Mesh.prototype.setPositionsForCPUSkinning = function () {
  22836. var source;
  22837. if (!this._sourcePositions) {
  22838. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22839. this._sourcePositions = new Float32Array(source);
  22840. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  22841. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  22842. }
  22843. }
  22844. return this._sourcePositions;
  22845. };
  22846. /**
  22847. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  22848. */
  22849. Mesh.prototype.setNormalsForCPUSkinning = function () {
  22850. var source;
  22851. if (!this._sourceNormals) {
  22852. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22853. this._sourceNormals = new Float32Array(source);
  22854. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  22855. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  22856. }
  22857. }
  22858. return this._sourceNormals;
  22859. };
  22860. /**
  22861. * Updates the vertex buffer by applying transformation from the bones.
  22862. * Returns the Mesh.
  22863. *
  22864. * @param {skeleton} skeleton to apply
  22865. */
  22866. Mesh.prototype.applySkeleton = function (skeleton) {
  22867. if (!this.geometry) {
  22868. return this;
  22869. }
  22870. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  22871. return this;
  22872. }
  22873. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  22874. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22875. return this;
  22876. }
  22877. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22878. return this;
  22879. }
  22880. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  22881. return this;
  22882. }
  22883. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  22884. return this;
  22885. }
  22886. if (!this._sourcePositions) {
  22887. var submeshes = this.subMeshes.slice();
  22888. this.setPositionsForCPUSkinning();
  22889. this.subMeshes = submeshes;
  22890. }
  22891. if (!this._sourceNormals) {
  22892. this.setNormalsForCPUSkinning();
  22893. }
  22894. // positionsData checks for not being Float32Array will only pass at most once
  22895. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22896. if (!(positionsData instanceof Float32Array)) {
  22897. positionsData = new Float32Array(positionsData);
  22898. }
  22899. // normalsData checks for not being Float32Array will only pass at most once
  22900. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22901. if (!(normalsData instanceof Float32Array)) {
  22902. normalsData = new Float32Array(normalsData);
  22903. }
  22904. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  22905. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  22906. var needExtras = this.numBoneInfluencers > 4;
  22907. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  22908. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  22909. var skeletonMatrices = skeleton.getTransformMatrices(this);
  22910. var tempVector3 = BABYLON.Vector3.Zero();
  22911. var finalMatrix = new BABYLON.Matrix();
  22912. var tempMatrix = new BABYLON.Matrix();
  22913. var matWeightIdx = 0;
  22914. var inf;
  22915. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  22916. var weight;
  22917. for (inf = 0; inf < 4; inf++) {
  22918. weight = matricesWeightsData[matWeightIdx + inf];
  22919. if (weight > 0) {
  22920. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  22921. finalMatrix.addToSelf(tempMatrix);
  22922. }
  22923. else
  22924. break;
  22925. }
  22926. if (needExtras) {
  22927. for (inf = 0; inf < 4; inf++) {
  22928. weight = matricesWeightsExtraData[matWeightIdx + inf];
  22929. if (weight > 0) {
  22930. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  22931. finalMatrix.addToSelf(tempMatrix);
  22932. }
  22933. else
  22934. break;
  22935. }
  22936. }
  22937. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  22938. tempVector3.toArray(positionsData, index);
  22939. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  22940. tempVector3.toArray(normalsData, index);
  22941. finalMatrix.reset();
  22942. }
  22943. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  22944. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  22945. return this;
  22946. };
  22947. // Tools
  22948. /**
  22949. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  22950. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  22951. */
  22952. Mesh.MinMax = function (meshes) {
  22953. var minVector = null;
  22954. var maxVector = null;
  22955. meshes.forEach(function (mesh, index, array) {
  22956. var boundingBox = mesh.getBoundingInfo().boundingBox;
  22957. if (!minVector) {
  22958. minVector = boundingBox.minimumWorld;
  22959. maxVector = boundingBox.maximumWorld;
  22960. }
  22961. else {
  22962. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  22963. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  22964. }
  22965. });
  22966. return {
  22967. min: minVector,
  22968. max: maxVector
  22969. };
  22970. };
  22971. /**
  22972. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  22973. */
  22974. Mesh.Center = function (meshesOrMinMaxVector) {
  22975. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  22976. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  22977. };
  22978. /**
  22979. * Merge the array of meshes into a single mesh for performance reasons.
  22980. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  22981. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  22982. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  22983. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  22984. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  22985. */
  22986. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  22987. if (disposeSource === void 0) { disposeSource = true; }
  22988. var index;
  22989. if (!allow32BitsIndices) {
  22990. var totalVertices = 0;
  22991. // Counting vertices
  22992. for (index = 0; index < meshes.length; index++) {
  22993. if (meshes[index]) {
  22994. totalVertices += meshes[index].getTotalVertices();
  22995. if (totalVertices > 65536) {
  22996. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  22997. return null;
  22998. }
  22999. }
  23000. }
  23001. }
  23002. // Merge
  23003. var vertexData;
  23004. var otherVertexData;
  23005. var indiceArray = new Array();
  23006. var source;
  23007. for (index = 0; index < meshes.length; index++) {
  23008. if (meshes[index]) {
  23009. meshes[index].computeWorldMatrix(true);
  23010. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  23011. otherVertexData.transform(meshes[index].getWorldMatrix());
  23012. if (vertexData) {
  23013. vertexData.merge(otherVertexData);
  23014. }
  23015. else {
  23016. vertexData = otherVertexData;
  23017. source = meshes[index];
  23018. }
  23019. if (subdivideWithSubMeshes) {
  23020. indiceArray.push(meshes[index].getTotalIndices());
  23021. }
  23022. }
  23023. }
  23024. if (!meshSubclass) {
  23025. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  23026. }
  23027. vertexData.applyToMesh(meshSubclass);
  23028. // Setting properties
  23029. meshSubclass.material = source.material;
  23030. meshSubclass.checkCollisions = source.checkCollisions;
  23031. // Cleaning
  23032. if (disposeSource) {
  23033. for (index = 0; index < meshes.length; index++) {
  23034. if (meshes[index]) {
  23035. meshes[index].dispose();
  23036. }
  23037. }
  23038. }
  23039. // Subdivide
  23040. if (subdivideWithSubMeshes) {
  23041. //-- Suppresions du submesh global
  23042. meshSubclass.releaseSubMeshes();
  23043. index = 0;
  23044. var offset = 0;
  23045. //-- aplique la subdivision en fonction du tableau d'indices
  23046. while (index < indiceArray.length) {
  23047. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  23048. offset += indiceArray[index];
  23049. index++;
  23050. }
  23051. }
  23052. return meshSubclass;
  23053. };
  23054. return Mesh;
  23055. }(BABYLON.AbstractMesh));
  23056. // Consts
  23057. Mesh._FRONTSIDE = 0;
  23058. Mesh._BACKSIDE = 1;
  23059. Mesh._DOUBLESIDE = 2;
  23060. Mesh._DEFAULTSIDE = 0;
  23061. Mesh._NO_CAP = 0;
  23062. Mesh._CAP_START = 1;
  23063. Mesh._CAP_END = 2;
  23064. Mesh._CAP_ALL = 3;
  23065. BABYLON.Mesh = Mesh;
  23066. })(BABYLON || (BABYLON = {}));
  23067. //# sourceMappingURL=babylon.mesh.js.map
  23068. var BABYLON;
  23069. (function (BABYLON) {
  23070. var BaseSubMesh = (function () {
  23071. function BaseSubMesh() {
  23072. }
  23073. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  23074. get: function () {
  23075. return this._materialEffect;
  23076. },
  23077. enumerable: true,
  23078. configurable: true
  23079. });
  23080. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  23081. if (this._materialEffect === effect) {
  23082. if (!effect) {
  23083. this._materialDefines = undefined;
  23084. }
  23085. return;
  23086. }
  23087. this._materialDefines = defines;
  23088. this._materialEffect = effect;
  23089. };
  23090. return BaseSubMesh;
  23091. }());
  23092. BABYLON.BaseSubMesh = BaseSubMesh;
  23093. var SubMesh = (function (_super) {
  23094. __extends(SubMesh, _super);
  23095. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  23096. if (createBoundingBox === void 0) { createBoundingBox = true; }
  23097. var _this = _super.call(this) || this;
  23098. _this.materialIndex = materialIndex;
  23099. _this.verticesStart = verticesStart;
  23100. _this.verticesCount = verticesCount;
  23101. _this.indexStart = indexStart;
  23102. _this.indexCount = indexCount;
  23103. _this._renderId = 0;
  23104. _this._mesh = mesh;
  23105. _this._renderingMesh = renderingMesh || mesh;
  23106. mesh.subMeshes.push(_this);
  23107. _this._trianglePlanes = [];
  23108. _this._id = mesh.subMeshes.length - 1;
  23109. if (createBoundingBox) {
  23110. _this.refreshBoundingInfo();
  23111. mesh.computeWorldMatrix(true);
  23112. }
  23113. return _this;
  23114. }
  23115. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  23116. get: function () {
  23117. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  23118. },
  23119. enumerable: true,
  23120. configurable: true
  23121. });
  23122. /**
  23123. * Returns the submesh BoudingInfo object.
  23124. */
  23125. SubMesh.prototype.getBoundingInfo = function () {
  23126. if (this.IsGlobal) {
  23127. return this._mesh.getBoundingInfo();
  23128. }
  23129. return this._boundingInfo;
  23130. };
  23131. /**
  23132. * Sets the submesh BoundingInfo.
  23133. * Return the SubMesh.
  23134. */
  23135. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  23136. this._boundingInfo = boundingInfo;
  23137. return this;
  23138. };
  23139. /**
  23140. * Returns the mesh of the current submesh.
  23141. */
  23142. SubMesh.prototype.getMesh = function () {
  23143. return this._mesh;
  23144. };
  23145. /**
  23146. * Returns the rendering mesh of the submesh.
  23147. */
  23148. SubMesh.prototype.getRenderingMesh = function () {
  23149. return this._renderingMesh;
  23150. };
  23151. /**
  23152. * Returns the submesh material.
  23153. */
  23154. SubMesh.prototype.getMaterial = function () {
  23155. var rootMaterial = this._renderingMesh.material;
  23156. if (rootMaterial && rootMaterial.getSubMaterial) {
  23157. var multiMaterial = rootMaterial;
  23158. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  23159. if (this._currentMaterial !== effectiveMaterial) {
  23160. this._currentMaterial = effectiveMaterial;
  23161. this._materialDefines = undefined;
  23162. }
  23163. return effectiveMaterial;
  23164. }
  23165. if (!rootMaterial) {
  23166. return this._mesh.getScene().defaultMaterial;
  23167. }
  23168. return rootMaterial;
  23169. };
  23170. // Methods
  23171. /**
  23172. * Sets a new updated BoundingInfo object to the submesh.
  23173. * Returns the SubMesh.
  23174. */
  23175. SubMesh.prototype.refreshBoundingInfo = function () {
  23176. this._lastColliderWorldVertices = null;
  23177. if (this.IsGlobal) {
  23178. return;
  23179. }
  23180. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23181. if (!data) {
  23182. this._boundingInfo = this._mesh._boundingInfo;
  23183. return;
  23184. }
  23185. var indices = this._renderingMesh.getIndices();
  23186. var extend;
  23187. //is this the only submesh?
  23188. if (this.indexStart === 0 && this.indexCount === indices.length) {
  23189. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  23190. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  23191. }
  23192. else {
  23193. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  23194. }
  23195. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23196. return this;
  23197. };
  23198. SubMesh.prototype._checkCollision = function (collider) {
  23199. return this.getBoundingInfo()._checkCollision(collider);
  23200. };
  23201. /**
  23202. * Updates the submesh BoundingInfo.
  23203. * Returns the Submesh.
  23204. */
  23205. SubMesh.prototype.updateBoundingInfo = function (world) {
  23206. if (!this.getBoundingInfo()) {
  23207. this.refreshBoundingInfo();
  23208. }
  23209. this.getBoundingInfo().update(world);
  23210. return this;
  23211. };
  23212. /**
  23213. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  23214. * Boolean returned.
  23215. */
  23216. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  23217. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  23218. };
  23219. /**
  23220. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  23221. * Boolean returned.
  23222. */
  23223. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  23224. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  23225. };
  23226. /**
  23227. * Renders the submesh.
  23228. * Returns it.
  23229. */
  23230. SubMesh.prototype.render = function (enableAlphaMode) {
  23231. this._renderingMesh.render(this, enableAlphaMode);
  23232. return this;
  23233. };
  23234. /**
  23235. * Returns a new Index Buffer.
  23236. * Type returned : WebGLBuffer.
  23237. */
  23238. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  23239. if (!this._linesIndexBuffer) {
  23240. var linesIndices = [];
  23241. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  23242. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  23243. }
  23244. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  23245. this.linesIndexCount = linesIndices.length;
  23246. }
  23247. return this._linesIndexBuffer;
  23248. };
  23249. /**
  23250. * True is the passed Ray intersects the submesh bounding box.
  23251. * Boolean returned.
  23252. */
  23253. SubMesh.prototype.canIntersects = function (ray) {
  23254. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  23255. };
  23256. /**
  23257. * Returns an object IntersectionInfo.
  23258. */
  23259. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  23260. var intersectInfo = null;
  23261. // LineMesh first as it's also a Mesh...
  23262. if (this._mesh instanceof BABYLON.LinesMesh) {
  23263. var lineMesh = this._mesh;
  23264. // Line test
  23265. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  23266. var p0 = positions[indices[index]];
  23267. var p1 = positions[indices[index + 1]];
  23268. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  23269. if (length < 0) {
  23270. continue;
  23271. }
  23272. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  23273. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  23274. if (fastCheck) {
  23275. break;
  23276. }
  23277. }
  23278. }
  23279. }
  23280. else {
  23281. // Triangles test
  23282. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  23283. var p0 = positions[indices[index]];
  23284. var p1 = positions[indices[index + 1]];
  23285. var p2 = positions[indices[index + 2]];
  23286. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  23287. if (currentIntersectInfo) {
  23288. if (currentIntersectInfo.distance < 0) {
  23289. continue;
  23290. }
  23291. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  23292. intersectInfo = currentIntersectInfo;
  23293. intersectInfo.faceId = index / 3;
  23294. if (fastCheck) {
  23295. break;
  23296. }
  23297. }
  23298. }
  23299. }
  23300. }
  23301. return intersectInfo;
  23302. };
  23303. // Clone
  23304. /**
  23305. * Creates a new Submesh from the passed Mesh.
  23306. */
  23307. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  23308. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  23309. if (!this.IsGlobal) {
  23310. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  23311. }
  23312. return result;
  23313. };
  23314. // Dispose
  23315. /**
  23316. * Disposes the Submesh.
  23317. * Returns nothing.
  23318. */
  23319. SubMesh.prototype.dispose = function () {
  23320. if (this._linesIndexBuffer) {
  23321. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  23322. this._linesIndexBuffer = null;
  23323. }
  23324. // Remove from mesh
  23325. var index = this._mesh.subMeshes.indexOf(this);
  23326. this._mesh.subMeshes.splice(index, 1);
  23327. };
  23328. // Statics
  23329. /**
  23330. * Creates a new Submesh from the passed parameters :
  23331. * - materialIndex (integer) : the index of the main mesh material.
  23332. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  23333. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  23334. * - mesh (Mesh) : the main mesh to create the submesh from.
  23335. * - renderingMesh (optional Mesh) : rendering mesh.
  23336. */
  23337. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  23338. var minVertexIndex = Number.MAX_VALUE;
  23339. var maxVertexIndex = -Number.MAX_VALUE;
  23340. renderingMesh = renderingMesh || mesh;
  23341. var indices = renderingMesh.getIndices();
  23342. for (var index = startIndex; index < startIndex + indexCount; index++) {
  23343. var vertexIndex = indices[index];
  23344. if (vertexIndex < minVertexIndex)
  23345. minVertexIndex = vertexIndex;
  23346. if (vertexIndex > maxVertexIndex)
  23347. maxVertexIndex = vertexIndex;
  23348. }
  23349. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  23350. };
  23351. return SubMesh;
  23352. }(BaseSubMesh));
  23353. BABYLON.SubMesh = SubMesh;
  23354. })(BABYLON || (BABYLON = {}));
  23355. //# sourceMappingURL=babylon.subMesh.js.map
  23356. var BABYLON;
  23357. (function (BABYLON) {
  23358. var EffectFallbacks = (function () {
  23359. function EffectFallbacks() {
  23360. this._defines = {};
  23361. this._currentRank = 32;
  23362. this._maxRank = -1;
  23363. }
  23364. EffectFallbacks.prototype.addFallback = function (rank, define) {
  23365. if (!this._defines[rank]) {
  23366. if (rank < this._currentRank) {
  23367. this._currentRank = rank;
  23368. }
  23369. if (rank > this._maxRank) {
  23370. this._maxRank = rank;
  23371. }
  23372. this._defines[rank] = new Array();
  23373. }
  23374. this._defines[rank].push(define);
  23375. };
  23376. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  23377. this._meshRank = rank;
  23378. this._mesh = mesh;
  23379. if (rank < this._currentRank) {
  23380. this._currentRank = rank;
  23381. }
  23382. if (rank > this._maxRank) {
  23383. this._maxRank = rank;
  23384. }
  23385. };
  23386. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  23387. get: function () {
  23388. return this._currentRank <= this._maxRank;
  23389. },
  23390. enumerable: true,
  23391. configurable: true
  23392. });
  23393. EffectFallbacks.prototype.reduce = function (currentDefines) {
  23394. // First we try to switch to CPU skinning
  23395. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  23396. this._mesh.computeBonesUsingShaders = false;
  23397. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  23398. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  23399. var scene = this._mesh.getScene();
  23400. for (var index = 0; index < scene.meshes.length; index++) {
  23401. var otherMesh = scene.meshes[index];
  23402. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  23403. otherMesh.computeBonesUsingShaders = false;
  23404. }
  23405. }
  23406. }
  23407. else {
  23408. var currentFallbacks = this._defines[this._currentRank];
  23409. if (currentFallbacks) {
  23410. for (var index = 0; index < currentFallbacks.length; index++) {
  23411. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  23412. }
  23413. }
  23414. this._currentRank++;
  23415. }
  23416. return currentDefines;
  23417. };
  23418. return EffectFallbacks;
  23419. }());
  23420. BABYLON.EffectFallbacks = EffectFallbacks;
  23421. var EffectCreationOptions = (function () {
  23422. function EffectCreationOptions() {
  23423. }
  23424. return EffectCreationOptions;
  23425. }());
  23426. BABYLON.EffectCreationOptions = EffectCreationOptions;
  23427. var Effect = (function () {
  23428. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  23429. var _this = this;
  23430. this.uniqueId = 0;
  23431. this.onCompileObservable = new BABYLON.Observable();
  23432. this.onErrorObservable = new BABYLON.Observable();
  23433. this.onBindObservable = new BABYLON.Observable();
  23434. this._uniformBuffersNames = {};
  23435. this._isReady = false;
  23436. this._compilationError = "";
  23437. this._valueCache = {};
  23438. this.name = baseName;
  23439. if (attributesNamesOrOptions.attributes) {
  23440. var options = attributesNamesOrOptions;
  23441. this._engine = uniformsNamesOrEngine;
  23442. this._attributesNames = options.attributes;
  23443. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  23444. this._samplers = options.samplers;
  23445. this.defines = options.defines;
  23446. this.onError = options.onError;
  23447. this.onCompiled = options.onCompiled;
  23448. this._fallbacks = options.fallbacks;
  23449. this._indexParameters = options.indexParameters;
  23450. if (options.uniformBuffersNames) {
  23451. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  23452. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  23453. }
  23454. }
  23455. }
  23456. else {
  23457. this._engine = engine;
  23458. this.defines = defines;
  23459. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  23460. this._samplers = samplers;
  23461. this._attributesNames = attributesNamesOrOptions;
  23462. this.onError = onError;
  23463. this.onCompiled = onCompiled;
  23464. this._indexParameters = indexParameters;
  23465. this._fallbacks = fallbacks;
  23466. }
  23467. this.uniqueId = Effect._uniqueIdSeed++;
  23468. var vertexSource;
  23469. var fragmentSource;
  23470. if (baseName.vertexElement) {
  23471. vertexSource = document.getElementById(baseName.vertexElement);
  23472. if (!vertexSource) {
  23473. vertexSource = baseName.vertexElement;
  23474. }
  23475. }
  23476. else {
  23477. vertexSource = baseName.vertex || baseName;
  23478. }
  23479. if (baseName.fragmentElement) {
  23480. fragmentSource = document.getElementById(baseName.fragmentElement);
  23481. if (!fragmentSource) {
  23482. fragmentSource = baseName.fragmentElement;
  23483. }
  23484. }
  23485. else {
  23486. fragmentSource = baseName.fragment || baseName;
  23487. }
  23488. this._loadVertexShader(vertexSource, function (vertexCode) {
  23489. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  23490. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  23491. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  23492. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  23493. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  23494. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, _this._attributesNames, _this.defines, _this._fallbacks);
  23495. });
  23496. });
  23497. });
  23498. });
  23499. });
  23500. });
  23501. }
  23502. Object.defineProperty(Effect.prototype, "key", {
  23503. get: function () {
  23504. return this._key;
  23505. },
  23506. enumerable: true,
  23507. configurable: true
  23508. });
  23509. // Properties
  23510. Effect.prototype.isReady = function () {
  23511. return this._isReady;
  23512. };
  23513. Effect.prototype.getEngine = function () {
  23514. return this._engine;
  23515. };
  23516. Effect.prototype.getProgram = function () {
  23517. return this._program;
  23518. };
  23519. Effect.prototype.getAttributesNames = function () {
  23520. return this._attributesNames;
  23521. };
  23522. Effect.prototype.getAttributeLocation = function (index) {
  23523. return this._attributes[index];
  23524. };
  23525. Effect.prototype.getAttributeLocationByName = function (name) {
  23526. var index = this._attributesNames.indexOf(name);
  23527. return this._attributes[index];
  23528. };
  23529. Effect.prototype.getAttributesCount = function () {
  23530. return this._attributes.length;
  23531. };
  23532. Effect.prototype.getUniformIndex = function (uniformName) {
  23533. return this._uniformsNames.indexOf(uniformName);
  23534. };
  23535. Effect.prototype.getUniform = function (uniformName) {
  23536. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  23537. };
  23538. Effect.prototype.getSamplers = function () {
  23539. return this._samplers;
  23540. };
  23541. Effect.prototype.getCompilationError = function () {
  23542. return this._compilationError;
  23543. };
  23544. Effect.prototype.getVertexShaderSource = function () {
  23545. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  23546. };
  23547. Effect.prototype.getFragmentShaderSource = function () {
  23548. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  23549. };
  23550. // Methods
  23551. Effect.prototype.executeWhenCompiled = function (func) {
  23552. if (this.isReady()) {
  23553. func(this);
  23554. return;
  23555. }
  23556. this.onCompileObservable.add(function (effect) {
  23557. func(effect);
  23558. });
  23559. };
  23560. Effect.prototype._loadVertexShader = function (vertex, callback) {
  23561. // DOM element ?
  23562. if (vertex instanceof HTMLElement) {
  23563. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  23564. callback(vertexCode);
  23565. return;
  23566. }
  23567. // Base64 encoded ?
  23568. if (vertex.substr(0, 7) === "base64:") {
  23569. var vertexBinary = window.atob(vertex.substr(7));
  23570. callback(vertexBinary);
  23571. return;
  23572. }
  23573. // Is in local store ?
  23574. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  23575. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  23576. return;
  23577. }
  23578. var vertexShaderUrl;
  23579. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  23580. vertexShaderUrl = vertex;
  23581. }
  23582. else {
  23583. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  23584. }
  23585. // Vertex shader
  23586. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  23587. };
  23588. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  23589. // DOM element ?
  23590. if (fragment instanceof HTMLElement) {
  23591. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  23592. callback(fragmentCode);
  23593. return;
  23594. }
  23595. // Base64 encoded ?
  23596. if (fragment.substr(0, 7) === "base64:") {
  23597. var fragmentBinary = window.atob(fragment.substr(7));
  23598. callback(fragmentBinary);
  23599. return;
  23600. }
  23601. // Is in local store ?
  23602. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  23603. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  23604. return;
  23605. }
  23606. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  23607. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  23608. return;
  23609. }
  23610. var fragmentShaderUrl;
  23611. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  23612. fragmentShaderUrl = fragment;
  23613. }
  23614. else {
  23615. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  23616. }
  23617. // Fragment shader
  23618. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  23619. };
  23620. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  23621. // Rebuild shaders source code
  23622. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  23623. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  23624. vertexCode = prefix + vertexCode;
  23625. fragmentCode = prefix + fragmentCode;
  23626. // Number lines of shaders source code
  23627. var i = 2;
  23628. var regex = /\n/gm;
  23629. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  23630. i = 2;
  23631. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  23632. // Dump shaders name and formatted source code
  23633. if (this.name.vertexElement) {
  23634. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  23635. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  23636. }
  23637. else if (this.name.vertex) {
  23638. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  23639. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  23640. }
  23641. else {
  23642. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  23643. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  23644. }
  23645. };
  23646. ;
  23647. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  23648. var preparedSourceCode = this._processPrecision(sourceCode);
  23649. if (this._engine.webGLVersion == 1) {
  23650. callback(preparedSourceCode);
  23651. return;
  23652. }
  23653. // Already converted
  23654. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  23655. callback(preparedSourceCode.replace("#version 300 es", ""));
  23656. return;
  23657. }
  23658. // Remove extensions
  23659. // #extension GL_OES_standard_derivatives : enable
  23660. // #extension GL_EXT_shader_texture_lod : enable
  23661. // #extension GL_EXT_frag_depth : enable
  23662. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  23663. var result = preparedSourceCode.replace(regex, "");
  23664. // Migrate to GLSL v300
  23665. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  23666. result = result.replace(/attribute[ \t]/g, "in ");
  23667. result = result.replace(/[ \t]attribute/g, " in");
  23668. if (isFragment) {
  23669. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  23670. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  23671. result = result.replace(/texture2D\(/g, "texture(");
  23672. result = result.replace(/textureCube\(/g, "texture(");
  23673. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  23674. result = result.replace(/gl_FragColor/g, "glFragColor");
  23675. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  23676. }
  23677. callback(result);
  23678. };
  23679. Effect.prototype._processIncludes = function (sourceCode, callback) {
  23680. var _this = this;
  23681. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  23682. var match = regex.exec(sourceCode);
  23683. var returnValue = new String(sourceCode);
  23684. while (match != null) {
  23685. var includeFile = match[1];
  23686. // Uniform declaration
  23687. if (includeFile.indexOf("__decl__") !== -1) {
  23688. includeFile = includeFile.replace(/__decl__/, "");
  23689. if (this._engine.webGLVersion != 1) {
  23690. includeFile = includeFile.replace(/Vertex/, "Ubo");
  23691. includeFile = includeFile.replace(/Fragment/, "Ubo");
  23692. }
  23693. includeFile = includeFile + "Declaration";
  23694. }
  23695. if (Effect.IncludesShadersStore[includeFile]) {
  23696. // Substitution
  23697. var includeContent = Effect.IncludesShadersStore[includeFile];
  23698. if (match[2]) {
  23699. var splits = match[3].split(",");
  23700. for (var index = 0; index < splits.length; index += 2) {
  23701. var source = new RegExp(splits[index], "g");
  23702. var dest = splits[index + 1];
  23703. includeContent = includeContent.replace(source, dest);
  23704. }
  23705. }
  23706. if (match[4]) {
  23707. var indexString = match[5];
  23708. if (indexString.indexOf("..") !== -1) {
  23709. var indexSplits = indexString.split("..");
  23710. var minIndex = parseInt(indexSplits[0]);
  23711. var maxIndex = parseInt(indexSplits[1]);
  23712. var sourceIncludeContent = includeContent.slice(0);
  23713. includeContent = "";
  23714. if (isNaN(maxIndex)) {
  23715. maxIndex = this._indexParameters[indexSplits[1]];
  23716. }
  23717. for (var i = minIndex; i < maxIndex; i++) {
  23718. if (this._engine.webGLVersion === 1) {
  23719. // Ubo replacement
  23720. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  23721. return p1 + "{X}";
  23722. });
  23723. }
  23724. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  23725. }
  23726. }
  23727. else {
  23728. if (this._engine.webGLVersion === 1) {
  23729. // Ubo replacement
  23730. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  23731. return p1 + "{X}";
  23732. });
  23733. }
  23734. includeContent = includeContent.replace(/\{X\}/g, indexString);
  23735. }
  23736. }
  23737. // Replace
  23738. returnValue = returnValue.replace(match[0], includeContent);
  23739. }
  23740. else {
  23741. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  23742. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  23743. Effect.IncludesShadersStore[includeFile] = fileContent;
  23744. _this._processIncludes(returnValue, callback);
  23745. });
  23746. return;
  23747. }
  23748. match = regex.exec(sourceCode);
  23749. }
  23750. callback(returnValue);
  23751. };
  23752. Effect.prototype._processPrecision = function (source) {
  23753. if (source.indexOf("precision highp float") === -1) {
  23754. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  23755. source = "precision mediump float;\n" + source;
  23756. }
  23757. else {
  23758. source = "precision highp float;\n" + source;
  23759. }
  23760. }
  23761. else {
  23762. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  23763. source = source.replace("precision highp float", "precision mediump float");
  23764. }
  23765. }
  23766. return source;
  23767. };
  23768. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  23769. try {
  23770. var engine = this._engine;
  23771. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  23772. if (engine.webGLVersion > 1) {
  23773. for (var name in this._uniformBuffersNames) {
  23774. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  23775. }
  23776. }
  23777. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  23778. this._attributes = engine.getAttributes(this._program, attributesNames);
  23779. var index;
  23780. for (index = 0; index < this._samplers.length; index++) {
  23781. var sampler = this.getUniform(this._samplers[index]);
  23782. if (sampler == null) {
  23783. this._samplers.splice(index, 1);
  23784. index--;
  23785. }
  23786. }
  23787. engine.bindSamplers(this);
  23788. this._compilationError = "";
  23789. this._isReady = true;
  23790. if (this.onCompiled) {
  23791. this.onCompiled(this);
  23792. }
  23793. this.onCompileObservable.notifyObservers(this);
  23794. this.onCompileObservable.clear();
  23795. }
  23796. catch (e) {
  23797. this._compilationError = e.message;
  23798. // Let's go through fallbacks then
  23799. BABYLON.Tools.Error("Unable to compile effect:");
  23800. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  23801. return " " + uniform;
  23802. }));
  23803. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  23804. return " " + attribute;
  23805. }));
  23806. this._dumpShadersSource(vertexSourceCode, fragmentSourceCode, defines);
  23807. BABYLON.Tools.Error("Error: " + this._compilationError);
  23808. if (fallbacks && fallbacks.isMoreFallbacks) {
  23809. BABYLON.Tools.Error("Trying next fallback.");
  23810. defines = fallbacks.reduce(defines);
  23811. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  23812. }
  23813. else {
  23814. if (this.onError) {
  23815. this.onError(this, this._compilationError);
  23816. }
  23817. this.onErrorObservable.notifyObservers(this);
  23818. }
  23819. }
  23820. };
  23821. Object.defineProperty(Effect.prototype, "isSupported", {
  23822. get: function () {
  23823. return this._compilationError === "";
  23824. },
  23825. enumerable: true,
  23826. configurable: true
  23827. });
  23828. Effect.prototype._bindTexture = function (channel, texture) {
  23829. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  23830. };
  23831. Effect.prototype.setTexture = function (channel, texture) {
  23832. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  23833. };
  23834. Effect.prototype.setTextureArray = function (channel, textures) {
  23835. if (this._samplers.indexOf(channel + "Ex") === -1) {
  23836. var initialPos = this._samplers.indexOf(channel);
  23837. for (var index = 1; index < textures.length; index++) {
  23838. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  23839. }
  23840. }
  23841. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  23842. };
  23843. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  23844. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  23845. };
  23846. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  23847. var cache = this._valueCache[uniformName];
  23848. var flag = matrix.updateFlag;
  23849. if (cache !== undefined && cache === flag) {
  23850. return false;
  23851. }
  23852. this._valueCache[uniformName] = flag;
  23853. return true;
  23854. };
  23855. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  23856. var cache = this._valueCache[uniformName];
  23857. if (!cache) {
  23858. cache = [x, y];
  23859. this._valueCache[uniformName] = cache;
  23860. return true;
  23861. }
  23862. var changed = false;
  23863. if (cache[0] !== x) {
  23864. cache[0] = x;
  23865. changed = true;
  23866. }
  23867. if (cache[1] !== y) {
  23868. cache[1] = y;
  23869. changed = true;
  23870. }
  23871. return changed;
  23872. };
  23873. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  23874. var cache = this._valueCache[uniformName];
  23875. if (!cache) {
  23876. cache = [x, y, z];
  23877. this._valueCache[uniformName] = cache;
  23878. return true;
  23879. }
  23880. var changed = false;
  23881. if (cache[0] !== x) {
  23882. cache[0] = x;
  23883. changed = true;
  23884. }
  23885. if (cache[1] !== y) {
  23886. cache[1] = y;
  23887. changed = true;
  23888. }
  23889. if (cache[2] !== z) {
  23890. cache[2] = z;
  23891. changed = true;
  23892. }
  23893. return changed;
  23894. };
  23895. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  23896. var cache = this._valueCache[uniformName];
  23897. if (!cache) {
  23898. cache = [x, y, z, w];
  23899. this._valueCache[uniformName] = cache;
  23900. return true;
  23901. }
  23902. var changed = false;
  23903. if (cache[0] !== x) {
  23904. cache[0] = x;
  23905. changed = true;
  23906. }
  23907. if (cache[1] !== y) {
  23908. cache[1] = y;
  23909. changed = true;
  23910. }
  23911. if (cache[2] !== z) {
  23912. cache[2] = z;
  23913. changed = true;
  23914. }
  23915. if (cache[3] !== w) {
  23916. cache[3] = w;
  23917. changed = true;
  23918. }
  23919. return changed;
  23920. };
  23921. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  23922. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  23923. return;
  23924. }
  23925. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  23926. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  23927. };
  23928. Effect.prototype.bindUniformBlock = function (blockName, index) {
  23929. this._engine.bindUniformBlock(this._program, blockName, index);
  23930. };
  23931. Effect.prototype.setIntArray = function (uniformName, array) {
  23932. this._valueCache[uniformName] = null;
  23933. this._engine.setIntArray(this.getUniform(uniformName), array);
  23934. return this;
  23935. };
  23936. Effect.prototype.setIntArray2 = function (uniformName, array) {
  23937. this._valueCache[uniformName] = null;
  23938. this._engine.setIntArray2(this.getUniform(uniformName), array);
  23939. return this;
  23940. };
  23941. Effect.prototype.setIntArray3 = function (uniformName, array) {
  23942. this._valueCache[uniformName] = null;
  23943. this._engine.setIntArray3(this.getUniform(uniformName), array);
  23944. return this;
  23945. };
  23946. Effect.prototype.setIntArray4 = function (uniformName, array) {
  23947. this._valueCache[uniformName] = null;
  23948. this._engine.setIntArray4(this.getUniform(uniformName), array);
  23949. return this;
  23950. };
  23951. Effect.prototype.setFloatArray = function (uniformName, array) {
  23952. this._valueCache[uniformName] = null;
  23953. this._engine.setFloatArray(this.getUniform(uniformName), array);
  23954. return this;
  23955. };
  23956. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  23957. this._valueCache[uniformName] = null;
  23958. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  23959. return this;
  23960. };
  23961. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  23962. this._valueCache[uniformName] = null;
  23963. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  23964. return this;
  23965. };
  23966. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  23967. this._valueCache[uniformName] = null;
  23968. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  23969. return this;
  23970. };
  23971. Effect.prototype.setArray = function (uniformName, array) {
  23972. this._valueCache[uniformName] = null;
  23973. this._engine.setArray(this.getUniform(uniformName), array);
  23974. return this;
  23975. };
  23976. Effect.prototype.setArray2 = function (uniformName, array) {
  23977. this._valueCache[uniformName] = null;
  23978. this._engine.setArray2(this.getUniform(uniformName), array);
  23979. return this;
  23980. };
  23981. Effect.prototype.setArray3 = function (uniformName, array) {
  23982. this._valueCache[uniformName] = null;
  23983. this._engine.setArray3(this.getUniform(uniformName), array);
  23984. return this;
  23985. };
  23986. Effect.prototype.setArray4 = function (uniformName, array) {
  23987. this._valueCache[uniformName] = null;
  23988. this._engine.setArray4(this.getUniform(uniformName), array);
  23989. return this;
  23990. };
  23991. Effect.prototype.setMatrices = function (uniformName, matrices) {
  23992. if (!matrices) {
  23993. return;
  23994. }
  23995. this._valueCache[uniformName] = null;
  23996. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  23997. return this;
  23998. };
  23999. Effect.prototype.setMatrix = function (uniformName, matrix) {
  24000. if (this._cacheMatrix(uniformName, matrix)) {
  24001. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  24002. }
  24003. return this;
  24004. };
  24005. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  24006. this._valueCache[uniformName] = null;
  24007. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  24008. return this;
  24009. };
  24010. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  24011. this._valueCache[uniformName] = null;
  24012. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  24013. return this;
  24014. };
  24015. Effect.prototype.setFloat = function (uniformName, value) {
  24016. var cache = this._valueCache[uniformName];
  24017. if (cache !== undefined && cache === value)
  24018. return this;
  24019. this._valueCache[uniformName] = value;
  24020. this._engine.setFloat(this.getUniform(uniformName), value);
  24021. return this;
  24022. };
  24023. Effect.prototype.setBool = function (uniformName, bool) {
  24024. var cache = this._valueCache[uniformName];
  24025. if (cache !== undefined && cache === bool)
  24026. return this;
  24027. this._valueCache[uniformName] = bool;
  24028. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  24029. return this;
  24030. };
  24031. Effect.prototype.setVector2 = function (uniformName, vector2) {
  24032. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  24033. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  24034. }
  24035. return this;
  24036. };
  24037. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  24038. if (this._cacheFloat2(uniformName, x, y)) {
  24039. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  24040. }
  24041. return this;
  24042. };
  24043. Effect.prototype.setVector3 = function (uniformName, vector3) {
  24044. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  24045. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  24046. }
  24047. return this;
  24048. };
  24049. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  24050. if (this._cacheFloat3(uniformName, x, y, z)) {
  24051. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  24052. }
  24053. return this;
  24054. };
  24055. Effect.prototype.setVector4 = function (uniformName, vector4) {
  24056. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  24057. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  24058. }
  24059. return this;
  24060. };
  24061. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  24062. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  24063. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  24064. }
  24065. return this;
  24066. };
  24067. Effect.prototype.setColor3 = function (uniformName, color3) {
  24068. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  24069. this._engine.setColor3(this.getUniform(uniformName), color3);
  24070. }
  24071. return this;
  24072. };
  24073. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  24074. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  24075. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  24076. }
  24077. return this;
  24078. };
  24079. Effect.prototype._recombineShader = function (node) {
  24080. if (node.define) {
  24081. if (node.condition) {
  24082. var defineIndex = this.defines.indexOf("#define " + node.define);
  24083. if (defineIndex === -1) {
  24084. return null;
  24085. }
  24086. var nextComma = this.defines.indexOf("\n", defineIndex);
  24087. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  24088. var condition = defineValue + node.condition;
  24089. if (!eval(condition)) {
  24090. return null;
  24091. }
  24092. }
  24093. else if (node.ndef) {
  24094. if (this.defines.indexOf("#define " + node.define) !== -1) {
  24095. return null;
  24096. }
  24097. }
  24098. else if (this.defines.indexOf("#define " + node.define) === -1) {
  24099. return null;
  24100. }
  24101. }
  24102. var result = "";
  24103. for (var index = 0; index < node.children.length; index++) {
  24104. var line = node.children[index];
  24105. if (line.children) {
  24106. var combined = this._recombineShader(line);
  24107. if (combined !== null) {
  24108. result += combined + "\r\n";
  24109. }
  24110. continue;
  24111. }
  24112. if (line.length > 0) {
  24113. result += line + "\r\n";
  24114. }
  24115. }
  24116. return result;
  24117. };
  24118. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  24119. var root = {
  24120. children: []
  24121. };
  24122. var currentNode = root;
  24123. var lines = shaderString.split("\n");
  24124. for (var index = 0; index < lines.length; index++) {
  24125. var line = lines[index].trim();
  24126. // #ifdef
  24127. var pos = line.indexOf("#ifdef ");
  24128. if (pos !== -1) {
  24129. var define = line.substr(pos + 7);
  24130. var newNode = {
  24131. condition: null,
  24132. ndef: false,
  24133. define: define,
  24134. children: [],
  24135. parent: currentNode
  24136. };
  24137. currentNode.children.push(newNode);
  24138. currentNode = newNode;
  24139. continue;
  24140. }
  24141. // #ifndef
  24142. var pos = line.indexOf("#ifndef ");
  24143. if (pos !== -1) {
  24144. var define = line.substr(pos + 8);
  24145. newNode = {
  24146. condition: null,
  24147. define: define,
  24148. ndef: true,
  24149. children: [],
  24150. parent: currentNode
  24151. };
  24152. currentNode.children.push(newNode);
  24153. currentNode = newNode;
  24154. continue;
  24155. }
  24156. // #if
  24157. var pos = line.indexOf("#if ");
  24158. if (pos !== -1) {
  24159. var define = line.substr(pos + 4).trim();
  24160. var conditionPos = define.indexOf(" ");
  24161. newNode = {
  24162. condition: define.substr(conditionPos + 1),
  24163. define: define.substr(0, conditionPos),
  24164. ndef: false,
  24165. children: [],
  24166. parent: currentNode
  24167. };
  24168. currentNode.children.push(newNode);
  24169. currentNode = newNode;
  24170. continue;
  24171. }
  24172. // #endif
  24173. pos = line.indexOf("#endif");
  24174. if (pos !== -1) {
  24175. currentNode = currentNode.parent;
  24176. continue;
  24177. }
  24178. currentNode.children.push(line);
  24179. }
  24180. // Recombine
  24181. return this._recombineShader(root);
  24182. };
  24183. Effect.ResetCache = function () {
  24184. Effect._baseCache = {};
  24185. };
  24186. return Effect;
  24187. }());
  24188. Effect._uniqueIdSeed = 0;
  24189. Effect._baseCache = {};
  24190. // Statics
  24191. Effect.ShadersStore = {};
  24192. Effect.IncludesShadersStore = {};
  24193. BABYLON.Effect = Effect;
  24194. })(BABYLON || (BABYLON = {}));
  24195. //# sourceMappingURL=babylon.effect.js.map
  24196. var BABYLON;
  24197. (function (BABYLON) {
  24198. var MaterialHelper = (function () {
  24199. function MaterialHelper() {
  24200. }
  24201. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  24202. defines._needUVs = true;
  24203. defines[key] = true;
  24204. if (texture.getTextureMatrix().isIdentity(true)) {
  24205. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  24206. if (texture.coordinatesIndex === 0) {
  24207. defines["MAINUV1"] = true;
  24208. }
  24209. else {
  24210. defines["MAINUV2"] = true;
  24211. }
  24212. }
  24213. else {
  24214. defines[key + "DIRECTUV"] = 0;
  24215. }
  24216. };
  24217. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  24218. var matrix = texture.getTextureMatrix();
  24219. if (!matrix.isIdentity(true)) {
  24220. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  24221. }
  24222. };
  24223. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  24224. if (defines._areMiscDirty) {
  24225. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  24226. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  24227. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  24228. defines["USERIGHTHANDEDSYSTEM"] = scene.useRightHandedSystem;
  24229. }
  24230. };
  24231. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  24232. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  24233. var changed = false;
  24234. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  24235. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  24236. changed = true;
  24237. }
  24238. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  24239. defines["ALPHATEST"] = !defines["ALPHATEST"];
  24240. changed = true;
  24241. }
  24242. if (defines["INSTANCES"] !== useInstances) {
  24243. defines["INSTANCES"] = useInstances;
  24244. changed = true;
  24245. }
  24246. if (changed) {
  24247. defines.markAsUnprocessed();
  24248. }
  24249. };
  24250. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  24251. if (useMorphTargets === void 0) { useMorphTargets = false; }
  24252. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  24253. return false;
  24254. }
  24255. defines._normals = defines._needNormals;
  24256. defines._uvs = defines._needUVs;
  24257. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  24258. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  24259. defines["TANGENT"] = true;
  24260. }
  24261. if (defines._needUVs) {
  24262. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  24263. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  24264. }
  24265. else {
  24266. defines["UV1"] = false;
  24267. defines["UV2"] = false;
  24268. }
  24269. if (useVertexColor) {
  24270. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  24271. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  24272. }
  24273. if (useBones) {
  24274. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  24275. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  24276. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  24277. }
  24278. else {
  24279. defines["NUM_BONE_INFLUENCERS"] = 0;
  24280. defines["BonesPerMesh"] = 0;
  24281. }
  24282. }
  24283. if (useMorphTargets) {
  24284. if (mesh.morphTargetManager) {
  24285. var manager = mesh.morphTargetManager;
  24286. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  24287. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  24288. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  24289. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  24290. }
  24291. else {
  24292. defines["MORPHTARGETS_TANGENT"] = false;
  24293. defines["MORPHTARGETS_NORMAL"] = false;
  24294. defines["MORPHTARGETS"] = false;
  24295. defines["NUM_MORPH_INFLUENCERS"] = 0;
  24296. }
  24297. }
  24298. return true;
  24299. };
  24300. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  24301. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24302. if (disableLighting === void 0) { disableLighting = false; }
  24303. if (!defines._areLightsDirty) {
  24304. return defines._needNormals;
  24305. }
  24306. var lightIndex = 0;
  24307. var needNormals = false;
  24308. var needRebuild = false;
  24309. var lightmapMode = false;
  24310. var shadowEnabled = false;
  24311. var specularEnabled = false;
  24312. if (scene.lightsEnabled && !disableLighting) {
  24313. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  24314. var light = _a[_i];
  24315. needNormals = true;
  24316. if (defines["LIGHT" + lightIndex] === undefined) {
  24317. needRebuild = true;
  24318. }
  24319. defines["LIGHT" + lightIndex] = true;
  24320. defines["SPOTLIGHT" + lightIndex] = false;
  24321. defines["HEMILIGHT" + lightIndex] = false;
  24322. defines["POINTLIGHT" + lightIndex] = false;
  24323. defines["DIRLIGHT" + lightIndex] = false;
  24324. var type;
  24325. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  24326. type = "SPOTLIGHT" + lightIndex;
  24327. }
  24328. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  24329. type = "HEMILIGHT" + lightIndex;
  24330. }
  24331. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  24332. type = "POINTLIGHT" + lightIndex;
  24333. }
  24334. else {
  24335. type = "DIRLIGHT" + lightIndex;
  24336. }
  24337. defines[type] = true;
  24338. // Specular
  24339. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  24340. specularEnabled = true;
  24341. }
  24342. // Shadows
  24343. defines["SHADOW" + lightIndex] = false;
  24344. defines["SHADOWPCF" + lightIndex] = false;
  24345. defines["SHADOWESM" + lightIndex] = false;
  24346. defines["SHADOWCUBE" + lightIndex] = false;
  24347. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  24348. var shadowGenerator = light.getShadowGenerator();
  24349. if (shadowGenerator) {
  24350. shadowEnabled = true;
  24351. shadowGenerator.prepareDefines(defines, lightIndex);
  24352. }
  24353. }
  24354. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  24355. lightmapMode = true;
  24356. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  24357. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  24358. }
  24359. else {
  24360. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  24361. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  24362. }
  24363. lightIndex++;
  24364. if (lightIndex === maxSimultaneousLights)
  24365. break;
  24366. }
  24367. }
  24368. defines["SPECULARTERM"] = specularEnabled;
  24369. defines["SHADOWS"] = shadowEnabled;
  24370. // Resetting all other lights if any
  24371. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  24372. if (defines["LIGHT" + index] !== undefined) {
  24373. defines["LIGHT" + index] = false;
  24374. defines["HEMILIGHT" + lightIndex] = false;
  24375. defines["POINTLIGHT" + lightIndex] = false;
  24376. defines["DIRLIGHT" + lightIndex] = false;
  24377. defines["SPOTLIGHT" + lightIndex] = false;
  24378. defines["SHADOW" + lightIndex] = false;
  24379. }
  24380. }
  24381. var caps = scene.getEngine().getCaps();
  24382. if (defines["SHADOWFLOAT"] === undefined) {
  24383. needRebuild = true;
  24384. }
  24385. defines["SHADOWFLOAT"] = shadowEnabled &&
  24386. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  24387. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  24388. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  24389. if (needRebuild) {
  24390. defines.rebuild();
  24391. }
  24392. return needNormals;
  24393. };
  24394. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  24395. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24396. var uniformsList, uniformBuffersList, samplersList, defines;
  24397. if (uniformsListOrOptions.uniformsNames) {
  24398. var options = uniformsListOrOptions;
  24399. uniformsList = options.uniformsNames;
  24400. uniformBuffersList = options.uniformBuffersNames;
  24401. samplersList = options.samplers;
  24402. defines = options.defines;
  24403. maxSimultaneousLights = options.maxSimultaneousLights;
  24404. }
  24405. else {
  24406. uniformsList = uniformsListOrOptions;
  24407. }
  24408. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24409. if (!defines["LIGHT" + lightIndex]) {
  24410. break;
  24411. }
  24412. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  24413. if (uniformBuffersList) {
  24414. uniformBuffersList.push("Light" + lightIndex);
  24415. }
  24416. samplersList.push("shadowSampler" + lightIndex);
  24417. }
  24418. if (defines["NUM_MORPH_INFLUENCERS"]) {
  24419. uniformsList.push("morphTargetInfluences");
  24420. }
  24421. };
  24422. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  24423. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24424. if (!defines["SHADOWS"]) {
  24425. return;
  24426. }
  24427. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24428. if (!defines["LIGHT" + lightIndex]) {
  24429. break;
  24430. }
  24431. if (lightIndex > 0) {
  24432. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  24433. }
  24434. if (defines["SHADOW" + lightIndex]) {
  24435. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  24436. }
  24437. if (defines["SHADOWPCF" + lightIndex]) {
  24438. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  24439. }
  24440. if (defines["SHADOWESM" + lightIndex]) {
  24441. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  24442. }
  24443. }
  24444. };
  24445. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  24446. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  24447. if (influencers > 0) {
  24448. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  24449. var manager = mesh.morphTargetManager;
  24450. var normal = manager.supportsNormals && defines["NORMAL"];
  24451. var tangent = manager.supportsTangents && defines["TANGENT"];
  24452. for (var index = 0; index < influencers; index++) {
  24453. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  24454. if (normal) {
  24455. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  24456. }
  24457. if (tangent) {
  24458. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  24459. }
  24460. if (attribs.length > maxAttributesCount) {
  24461. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  24462. }
  24463. }
  24464. }
  24465. };
  24466. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  24467. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  24468. fallbacks.addCPUSkinningFallback(0, mesh);
  24469. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24470. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24471. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  24472. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  24473. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  24474. }
  24475. }
  24476. };
  24477. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  24478. if (defines["INSTANCES"]) {
  24479. attribs.push("world0");
  24480. attribs.push("world1");
  24481. attribs.push("world2");
  24482. attribs.push("world3");
  24483. }
  24484. };
  24485. // Bindings
  24486. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  24487. if (light.shadowEnabled && mesh.receiveShadows) {
  24488. var shadowGenerator = light.getShadowGenerator();
  24489. if (shadowGenerator) {
  24490. shadowGenerator.bindShadowLight(lightIndex, effect);
  24491. }
  24492. }
  24493. };
  24494. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  24495. light.transferToEffect(effect, lightIndex + "");
  24496. };
  24497. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  24498. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24499. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  24500. var lightIndex = 0;
  24501. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  24502. var light = _a[_i];
  24503. var scaledIntensity = light.getScaledIntensity();
  24504. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  24505. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  24506. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  24507. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  24508. if (defines["SPECULARTERM"]) {
  24509. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  24510. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  24511. }
  24512. // Shadows
  24513. if (scene.shadowsEnabled) {
  24514. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  24515. }
  24516. light._uniformBuffer.update();
  24517. lightIndex++;
  24518. if (lightIndex === maxSimultaneousLights)
  24519. break;
  24520. }
  24521. };
  24522. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  24523. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  24524. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  24525. effect.setColor3("vFogColor", scene.fogColor);
  24526. }
  24527. };
  24528. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  24529. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  24530. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  24531. if (matrices) {
  24532. effect.setMatrices("mBones", matrices);
  24533. }
  24534. }
  24535. };
  24536. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  24537. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  24538. return;
  24539. }
  24540. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  24541. };
  24542. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  24543. if (defines["LOGARITHMICDEPTH"]) {
  24544. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  24545. }
  24546. };
  24547. MaterialHelper.BindClipPlane = function (effect, scene) {
  24548. if (scene.clipPlane) {
  24549. var clipPlane = scene.clipPlane;
  24550. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  24551. }
  24552. };
  24553. return MaterialHelper;
  24554. }());
  24555. BABYLON.MaterialHelper = MaterialHelper;
  24556. })(BABYLON || (BABYLON = {}));
  24557. //# sourceMappingURL=babylon.materialHelper.js.map
  24558. var BABYLON;
  24559. (function (BABYLON) {
  24560. var MaterialDefines = (function () {
  24561. function MaterialDefines() {
  24562. this._isDirty = true;
  24563. this._areLightsDirty = true;
  24564. this._areAttributesDirty = true;
  24565. this._areTexturesDirty = true;
  24566. this._areFresnelDirty = true;
  24567. this._areMiscDirty = true;
  24568. this._areImageProcessingDirty = true;
  24569. this._normals = false;
  24570. this._uvs = false;
  24571. this._needNormals = false;
  24572. this._needUVs = false;
  24573. }
  24574. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  24575. get: function () {
  24576. return this._isDirty;
  24577. },
  24578. enumerable: true,
  24579. configurable: true
  24580. });
  24581. MaterialDefines.prototype.markAsProcessed = function () {
  24582. this._isDirty = false;
  24583. this._areAttributesDirty = false;
  24584. this._areTexturesDirty = false;
  24585. this._areFresnelDirty = false;
  24586. this._areLightsDirty = false;
  24587. this._areMiscDirty = false;
  24588. this._areImageProcessingDirty = false;
  24589. };
  24590. MaterialDefines.prototype.markAsUnprocessed = function () {
  24591. this._isDirty = true;
  24592. };
  24593. MaterialDefines.prototype.markAllAsDirty = function () {
  24594. this._areTexturesDirty = true;
  24595. this._areAttributesDirty = true;
  24596. this._areLightsDirty = true;
  24597. this._areFresnelDirty = true;
  24598. this._areMiscDirty = true;
  24599. this._areImageProcessingDirty = true;
  24600. this._isDirty = true;
  24601. };
  24602. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  24603. this._areImageProcessingDirty = true;
  24604. this._isDirty = true;
  24605. };
  24606. MaterialDefines.prototype.markAsLightDirty = function () {
  24607. this._areLightsDirty = true;
  24608. this._isDirty = true;
  24609. };
  24610. MaterialDefines.prototype.markAsAttributesDirty = function () {
  24611. this._areAttributesDirty = true;
  24612. this._isDirty = true;
  24613. };
  24614. MaterialDefines.prototype.markAsTexturesDirty = function () {
  24615. this._areTexturesDirty = true;
  24616. this._isDirty = true;
  24617. };
  24618. MaterialDefines.prototype.markAsFresnelDirty = function () {
  24619. this._areFresnelDirty = true;
  24620. this._isDirty = true;
  24621. };
  24622. MaterialDefines.prototype.markAsMiscDirty = function () {
  24623. this._areMiscDirty = true;
  24624. this._isDirty = true;
  24625. };
  24626. MaterialDefines.prototype.rebuild = function () {
  24627. if (this._keys) {
  24628. delete this._keys;
  24629. }
  24630. this._keys = [];
  24631. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  24632. var key = _a[_i];
  24633. if (key[0] === "_") {
  24634. continue;
  24635. }
  24636. this._keys.push(key);
  24637. }
  24638. };
  24639. MaterialDefines.prototype.isEqual = function (other) {
  24640. if (this._keys.length !== other._keys.length) {
  24641. return false;
  24642. }
  24643. for (var index = 0; index < this._keys.length; index++) {
  24644. var prop = this._keys[index];
  24645. if (this[prop] !== other[prop]) {
  24646. return false;
  24647. }
  24648. }
  24649. return true;
  24650. };
  24651. MaterialDefines.prototype.cloneTo = function (other) {
  24652. if (this._keys.length !== other._keys.length) {
  24653. other._keys = this._keys.slice(0);
  24654. }
  24655. for (var index = 0; index < this._keys.length; index++) {
  24656. var prop = this._keys[index];
  24657. other[prop] = this[prop];
  24658. }
  24659. };
  24660. MaterialDefines.prototype.reset = function () {
  24661. for (var index = 0; index < this._keys.length; index++) {
  24662. var prop = this._keys[index];
  24663. if (typeof (this[prop]) === "number") {
  24664. this[prop] = 0;
  24665. }
  24666. else {
  24667. this[prop] = false;
  24668. }
  24669. }
  24670. };
  24671. MaterialDefines.prototype.toString = function () {
  24672. var result = "";
  24673. for (var index = 0; index < this._keys.length; index++) {
  24674. var prop = this._keys[index];
  24675. var value = this[prop];
  24676. if (typeof (value) === "number") {
  24677. result += "#define " + prop + " " + this[prop] + "\n";
  24678. }
  24679. else if (value) {
  24680. result += "#define " + prop + "\n";
  24681. }
  24682. }
  24683. return result;
  24684. };
  24685. return MaterialDefines;
  24686. }());
  24687. BABYLON.MaterialDefines = MaterialDefines;
  24688. var Material = (function () {
  24689. function Material(name, scene, doNotAdd) {
  24690. this.checkReadyOnEveryCall = false;
  24691. this.checkReadyOnlyOnce = false;
  24692. this.state = "";
  24693. this.alpha = 1.0;
  24694. this._backFaceCulling = true;
  24695. this.doNotSerialize = false;
  24696. this.storeEffectOnSubMeshes = false;
  24697. /**
  24698. * An event triggered when the material is disposed.
  24699. * @type {BABYLON.Observable}
  24700. */
  24701. this.onDisposeObservable = new BABYLON.Observable();
  24702. /**
  24703. * An event triggered when the material is bound.
  24704. * @type {BABYLON.Observable}
  24705. */
  24706. this.onBindObservable = new BABYLON.Observable();
  24707. /**
  24708. * An event triggered when the material is unbound.
  24709. * @type {BABYLON.Observable}
  24710. */
  24711. this.onUnBindObservable = new BABYLON.Observable();
  24712. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  24713. this.disableDepthWrite = false;
  24714. this._fogEnabled = true;
  24715. this.pointSize = 1.0;
  24716. this.zOffset = 0;
  24717. this._wasPreviouslyReady = false;
  24718. this._fillMode = Material.TriangleFillMode;
  24719. this.name = name;
  24720. this.id = name || BABYLON.Tools.RandomId();
  24721. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  24722. if (this._scene.useRightHandedSystem) {
  24723. this.sideOrientation = Material.ClockWiseSideOrientation;
  24724. }
  24725. else {
  24726. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  24727. }
  24728. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  24729. this._useUBO = this.getScene().getEngine().webGLVersion > 1;
  24730. if (!doNotAdd) {
  24731. this._scene.materials.push(this);
  24732. }
  24733. }
  24734. Object.defineProperty(Material, "TriangleFillMode", {
  24735. get: function () {
  24736. return Material._TriangleFillMode;
  24737. },
  24738. enumerable: true,
  24739. configurable: true
  24740. });
  24741. Object.defineProperty(Material, "WireFrameFillMode", {
  24742. get: function () {
  24743. return Material._WireFrameFillMode;
  24744. },
  24745. enumerable: true,
  24746. configurable: true
  24747. });
  24748. Object.defineProperty(Material, "PointFillMode", {
  24749. get: function () {
  24750. return Material._PointFillMode;
  24751. },
  24752. enumerable: true,
  24753. configurable: true
  24754. });
  24755. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  24756. get: function () {
  24757. return Material._ClockWiseSideOrientation;
  24758. },
  24759. enumerable: true,
  24760. configurable: true
  24761. });
  24762. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  24763. get: function () {
  24764. return Material._CounterClockWiseSideOrientation;
  24765. },
  24766. enumerable: true,
  24767. configurable: true
  24768. });
  24769. Object.defineProperty(Material, "TextureDirtyFlag", {
  24770. get: function () {
  24771. return Material._TextureDirtyFlag;
  24772. },
  24773. enumerable: true,
  24774. configurable: true
  24775. });
  24776. Object.defineProperty(Material, "LightDirtyFlag", {
  24777. get: function () {
  24778. return Material._LightDirtyFlag;
  24779. },
  24780. enumerable: true,
  24781. configurable: true
  24782. });
  24783. Object.defineProperty(Material, "FresnelDirtyFlag", {
  24784. get: function () {
  24785. return Material._FresnelDirtyFlag;
  24786. },
  24787. enumerable: true,
  24788. configurable: true
  24789. });
  24790. Object.defineProperty(Material, "AttributesDirtyFlag", {
  24791. get: function () {
  24792. return Material._AttributesDirtyFlag;
  24793. },
  24794. enumerable: true,
  24795. configurable: true
  24796. });
  24797. Object.defineProperty(Material, "MiscDirtyFlag", {
  24798. get: function () {
  24799. return Material._MiscDirtyFlag;
  24800. },
  24801. enumerable: true,
  24802. configurable: true
  24803. });
  24804. Object.defineProperty(Material.prototype, "backFaceCulling", {
  24805. get: function () {
  24806. return this._backFaceCulling;
  24807. },
  24808. set: function (value) {
  24809. if (this._backFaceCulling === value) {
  24810. return;
  24811. }
  24812. this._backFaceCulling = value;
  24813. this.markAsDirty(Material.TextureDirtyFlag);
  24814. },
  24815. enumerable: true,
  24816. configurable: true
  24817. });
  24818. Object.defineProperty(Material.prototype, "onDispose", {
  24819. set: function (callback) {
  24820. if (this._onDisposeObserver) {
  24821. this.onDisposeObservable.remove(this._onDisposeObserver);
  24822. }
  24823. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24824. },
  24825. enumerable: true,
  24826. configurable: true
  24827. });
  24828. Object.defineProperty(Material.prototype, "onBind", {
  24829. set: function (callback) {
  24830. if (this._onBindObserver) {
  24831. this.onBindObservable.remove(this._onBindObserver);
  24832. }
  24833. this._onBindObserver = this.onBindObservable.add(callback);
  24834. },
  24835. enumerable: true,
  24836. configurable: true
  24837. });
  24838. Object.defineProperty(Material.prototype, "fogEnabled", {
  24839. get: function () {
  24840. return this._fogEnabled;
  24841. },
  24842. set: function (value) {
  24843. if (this._fogEnabled === value) {
  24844. return;
  24845. }
  24846. this._fogEnabled = value;
  24847. this.markAsDirty(Material.MiscDirtyFlag);
  24848. },
  24849. enumerable: true,
  24850. configurable: true
  24851. });
  24852. Object.defineProperty(Material.prototype, "wireframe", {
  24853. get: function () {
  24854. return this._fillMode === Material.WireFrameFillMode;
  24855. },
  24856. set: function (value) {
  24857. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  24858. },
  24859. enumerable: true,
  24860. configurable: true
  24861. });
  24862. Object.defineProperty(Material.prototype, "pointsCloud", {
  24863. get: function () {
  24864. return this._fillMode === Material.PointFillMode;
  24865. },
  24866. set: function (value) {
  24867. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  24868. },
  24869. enumerable: true,
  24870. configurable: true
  24871. });
  24872. Object.defineProperty(Material.prototype, "fillMode", {
  24873. get: function () {
  24874. return this._fillMode;
  24875. },
  24876. set: function (value) {
  24877. if (this._fillMode === value) {
  24878. return;
  24879. }
  24880. this._fillMode = value;
  24881. this.markAsDirty(Material.MiscDirtyFlag);
  24882. },
  24883. enumerable: true,
  24884. configurable: true
  24885. });
  24886. /**
  24887. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  24888. * subclasses should override adding information pertainent to themselves
  24889. */
  24890. Material.prototype.toString = function (fullDetails) {
  24891. var ret = "Name: " + this.name;
  24892. if (fullDetails) {
  24893. }
  24894. return ret;
  24895. };
  24896. /**
  24897. * Child classes can use it to update shaders
  24898. */
  24899. Material.prototype.getClassName = function () {
  24900. return "Material";
  24901. };
  24902. Object.defineProperty(Material.prototype, "isFrozen", {
  24903. get: function () {
  24904. return this.checkReadyOnlyOnce;
  24905. },
  24906. enumerable: true,
  24907. configurable: true
  24908. });
  24909. Material.prototype.freeze = function () {
  24910. this.checkReadyOnlyOnce = true;
  24911. };
  24912. Material.prototype.unfreeze = function () {
  24913. this.checkReadyOnlyOnce = false;
  24914. };
  24915. Material.prototype.isReady = function (mesh, useInstances) {
  24916. return true;
  24917. };
  24918. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  24919. return false;
  24920. };
  24921. Material.prototype.getEffect = function () {
  24922. return this._effect;
  24923. };
  24924. Material.prototype.getScene = function () {
  24925. return this._scene;
  24926. };
  24927. Material.prototype.needAlphaBlending = function () {
  24928. return (this.alpha < 1.0);
  24929. };
  24930. Material.prototype.needAlphaTesting = function () {
  24931. return false;
  24932. };
  24933. Material.prototype.getAlphaTestTexture = function () {
  24934. return null;
  24935. };
  24936. Material.prototype.markDirty = function () {
  24937. this._wasPreviouslyReady = false;
  24938. };
  24939. Material.prototype._preBind = function (effect) {
  24940. var engine = this._scene.getEngine();
  24941. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  24942. engine.enableEffect(effect ? effect : this._effect);
  24943. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  24944. };
  24945. Material.prototype.bind = function (world, mesh) {
  24946. };
  24947. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  24948. };
  24949. Material.prototype.bindOnlyWorldMatrix = function (world) {
  24950. };
  24951. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  24952. sceneUbo.bindToEffect(effect, "Scene");
  24953. };
  24954. Material.prototype.bindView = function (effect) {
  24955. if (!this._useUBO) {
  24956. effect.setMatrix("view", this.getScene().getViewMatrix());
  24957. }
  24958. else {
  24959. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  24960. }
  24961. };
  24962. Material.prototype.bindViewProjection = function (effect) {
  24963. if (!this._useUBO) {
  24964. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  24965. }
  24966. else {
  24967. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  24968. }
  24969. };
  24970. Material.prototype._afterBind = function (mesh) {
  24971. this._scene._cachedMaterial = this;
  24972. this.onBindObservable.notifyObservers(mesh);
  24973. if (this.disableDepthWrite) {
  24974. var engine = this._scene.getEngine();
  24975. this._cachedDepthWriteState = engine.getDepthWrite();
  24976. engine.setDepthWrite(false);
  24977. }
  24978. };
  24979. Material.prototype.unbind = function () {
  24980. this.onUnBindObservable.notifyObservers(this);
  24981. if (this.disableDepthWrite) {
  24982. var engine = this._scene.getEngine();
  24983. engine.setDepthWrite(this._cachedDepthWriteState);
  24984. }
  24985. };
  24986. Material.prototype.getActiveTextures = function () {
  24987. return [];
  24988. };
  24989. Material.prototype.hasTexture = function (texture) {
  24990. return false;
  24991. };
  24992. Material.prototype.clone = function (name) {
  24993. return null;
  24994. };
  24995. Material.prototype.getBindedMeshes = function () {
  24996. var result = new Array();
  24997. for (var index = 0; index < this._scene.meshes.length; index++) {
  24998. var mesh = this._scene.meshes[index];
  24999. if (mesh.material === this) {
  25000. result.push(mesh);
  25001. }
  25002. }
  25003. return result;
  25004. };
  25005. /**
  25006. * Force shader compilation including textures ready check
  25007. */
  25008. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  25009. var _this = this;
  25010. var subMesh = new BABYLON.BaseSubMesh();
  25011. var scene = this.getScene();
  25012. var engine = scene.getEngine();
  25013. var checkReady = function () {
  25014. if (!_this._scene || !_this._scene.getEngine()) {
  25015. return;
  25016. }
  25017. if (subMesh._materialDefines) {
  25018. subMesh._materialDefines._renderId = -1;
  25019. }
  25020. var alphaTestState = engine.getAlphaTesting();
  25021. var clipPlaneState = scene.clipPlane;
  25022. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  25023. if (options && options.clipPlane) {
  25024. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  25025. }
  25026. if (_this.storeEffectOnSubMeshes) {
  25027. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  25028. if (onCompiled) {
  25029. onCompiled(_this);
  25030. }
  25031. }
  25032. else {
  25033. setTimeout(checkReady, 16);
  25034. }
  25035. }
  25036. else {
  25037. if (_this.isReady(mesh)) {
  25038. if (onCompiled) {
  25039. onCompiled(_this);
  25040. }
  25041. }
  25042. else {
  25043. setTimeout(checkReady, 16);
  25044. }
  25045. }
  25046. engine.setAlphaTesting(alphaTestState);
  25047. if (options && options.clipPlane) {
  25048. scene.clipPlane = clipPlaneState;
  25049. }
  25050. };
  25051. checkReady();
  25052. };
  25053. Material.prototype.markAsDirty = function (flag) {
  25054. if (flag & Material.TextureDirtyFlag) {
  25055. this._markAllSubMeshesAsTexturesDirty();
  25056. }
  25057. if (flag & Material.LightDirtyFlag) {
  25058. this._markAllSubMeshesAsLightsDirty();
  25059. }
  25060. if (flag & Material.FresnelDirtyFlag) {
  25061. this._markAllSubMeshesAsFresnelDirty();
  25062. }
  25063. if (flag & Material.AttributesDirtyFlag) {
  25064. this._markAllSubMeshesAsAttributesDirty();
  25065. }
  25066. if (flag & Material.MiscDirtyFlag) {
  25067. this._markAllSubMeshesAsMiscDirty();
  25068. }
  25069. this.getScene().resetCachedMaterial();
  25070. };
  25071. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  25072. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  25073. var mesh = _a[_i];
  25074. if (!mesh.subMeshes) {
  25075. continue;
  25076. }
  25077. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25078. var subMesh = _c[_b];
  25079. if (subMesh.getMaterial() !== this) {
  25080. continue;
  25081. }
  25082. if (!subMesh._materialDefines) {
  25083. continue;
  25084. }
  25085. func(subMesh._materialDefines);
  25086. }
  25087. }
  25088. };
  25089. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  25090. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  25091. };
  25092. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  25093. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  25094. };
  25095. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  25096. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  25097. };
  25098. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  25099. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  25100. };
  25101. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  25102. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  25103. };
  25104. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  25105. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  25106. };
  25107. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  25108. // Animations
  25109. this.getScene().stopAnimation(this);
  25110. // Remove from scene
  25111. var index = this._scene.materials.indexOf(this);
  25112. if (index >= 0) {
  25113. this._scene.materials.splice(index, 1);
  25114. }
  25115. // Remove from meshes
  25116. for (index = 0; index < this._scene.meshes.length; index++) {
  25117. var mesh = this._scene.meshes[index];
  25118. if (mesh.material === this) {
  25119. mesh.material = null;
  25120. if (mesh.geometry) {
  25121. var geometry = mesh.geometry;
  25122. if (this.storeEffectOnSubMeshes) {
  25123. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  25124. var subMesh = _a[_i];
  25125. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  25126. }
  25127. }
  25128. else {
  25129. geometry._releaseVertexArrayObject(this._effect);
  25130. }
  25131. }
  25132. }
  25133. }
  25134. this._uniformBuffer.dispose();
  25135. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  25136. if (forceDisposeEffect && this._effect) {
  25137. if (this.storeEffectOnSubMeshes) {
  25138. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25139. var subMesh = _c[_b];
  25140. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  25141. }
  25142. }
  25143. else {
  25144. this._scene.getEngine()._releaseEffect(this._effect);
  25145. }
  25146. this._effect = null;
  25147. }
  25148. // Callback
  25149. this.onDisposeObservable.notifyObservers(this);
  25150. this.onDisposeObservable.clear();
  25151. this.onBindObservable.clear();
  25152. this.onUnBindObservable.clear();
  25153. };
  25154. Material.prototype.serialize = function () {
  25155. return BABYLON.SerializationHelper.Serialize(this);
  25156. };
  25157. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  25158. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  25159. multiMaterial.id = parsedMultiMaterial.id;
  25160. if (BABYLON.Tags) {
  25161. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  25162. }
  25163. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  25164. var subMatId = parsedMultiMaterial.materials[matIndex];
  25165. if (subMatId) {
  25166. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  25167. }
  25168. else {
  25169. multiMaterial.subMaterials.push(null);
  25170. }
  25171. }
  25172. return multiMaterial;
  25173. };
  25174. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  25175. if (!parsedMaterial.customType) {
  25176. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  25177. }
  25178. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  25179. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  25180. if (!BABYLON.LegacyPBRMaterial) {
  25181. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  25182. return;
  25183. }
  25184. }
  25185. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  25186. return materialType.Parse(parsedMaterial, scene, rootUrl);
  25187. ;
  25188. };
  25189. return Material;
  25190. }());
  25191. Material._TriangleFillMode = 0;
  25192. Material._WireFrameFillMode = 1;
  25193. Material._PointFillMode = 2;
  25194. Material._ClockWiseSideOrientation = 0;
  25195. Material._CounterClockWiseSideOrientation = 1;
  25196. Material._TextureDirtyFlag = 1;
  25197. Material._LightDirtyFlag = 2;
  25198. Material._FresnelDirtyFlag = 4;
  25199. Material._AttributesDirtyFlag = 8;
  25200. Material._MiscDirtyFlag = 16;
  25201. __decorate([
  25202. BABYLON.serialize()
  25203. ], Material.prototype, "id", void 0);
  25204. __decorate([
  25205. BABYLON.serialize()
  25206. ], Material.prototype, "name", void 0);
  25207. __decorate([
  25208. BABYLON.serialize()
  25209. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  25210. __decorate([
  25211. BABYLON.serialize()
  25212. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  25213. __decorate([
  25214. BABYLON.serialize()
  25215. ], Material.prototype, "state", void 0);
  25216. __decorate([
  25217. BABYLON.serialize()
  25218. ], Material.prototype, "alpha", void 0);
  25219. __decorate([
  25220. BABYLON.serialize("backFaceCulling")
  25221. ], Material.prototype, "_backFaceCulling", void 0);
  25222. __decorate([
  25223. BABYLON.serialize()
  25224. ], Material.prototype, "sideOrientation", void 0);
  25225. __decorate([
  25226. BABYLON.serialize()
  25227. ], Material.prototype, "alphaMode", void 0);
  25228. __decorate([
  25229. BABYLON.serialize()
  25230. ], Material.prototype, "disableDepthWrite", void 0);
  25231. __decorate([
  25232. BABYLON.serialize("fogEnabled")
  25233. ], Material.prototype, "_fogEnabled", void 0);
  25234. __decorate([
  25235. BABYLON.serialize()
  25236. ], Material.prototype, "pointSize", void 0);
  25237. __decorate([
  25238. BABYLON.serialize()
  25239. ], Material.prototype, "zOffset", void 0);
  25240. __decorate([
  25241. BABYLON.serialize()
  25242. ], Material.prototype, "wireframe", null);
  25243. __decorate([
  25244. BABYLON.serialize()
  25245. ], Material.prototype, "pointsCloud", null);
  25246. __decorate([
  25247. BABYLON.serialize()
  25248. ], Material.prototype, "fillMode", null);
  25249. BABYLON.Material = Material;
  25250. })(BABYLON || (BABYLON = {}));
  25251. //# sourceMappingURL=babylon.material.js.map
  25252. var BABYLON;
  25253. (function (BABYLON) {
  25254. var UniformBuffer = (function () {
  25255. /**
  25256. * Uniform buffer objects.
  25257. *
  25258. * Handles blocks of uniform on the GPU.
  25259. *
  25260. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  25261. *
  25262. * For more information, please refer to :
  25263. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  25264. */
  25265. function UniformBuffer(engine, data, dynamic) {
  25266. this._engine = engine;
  25267. this._noUBO = engine.webGLVersion === 1;
  25268. this._dynamic = dynamic;
  25269. this._data = data || [];
  25270. this._uniformLocations = {};
  25271. this._uniformSizes = {};
  25272. this._uniformLocationPointer = 0;
  25273. this._needSync = false;
  25274. if (this._noUBO) {
  25275. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  25276. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  25277. this.updateFloat = this._updateFloatForEffect;
  25278. this.updateFloat2 = this._updateFloat2ForEffect;
  25279. this.updateFloat3 = this._updateFloat3ForEffect;
  25280. this.updateFloat4 = this._updateFloat4ForEffect;
  25281. this.updateMatrix = this._updateMatrixForEffect;
  25282. this.updateVector3 = this._updateVector3ForEffect;
  25283. this.updateVector4 = this._updateVector4ForEffect;
  25284. this.updateColor3 = this._updateColor3ForEffect;
  25285. this.updateColor4 = this._updateColor4ForEffect;
  25286. }
  25287. else {
  25288. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  25289. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  25290. this.updateFloat = this._updateFloatForUniform;
  25291. this.updateFloat2 = this._updateFloat2ForUniform;
  25292. this.updateFloat3 = this._updateFloat3ForUniform;
  25293. this.updateFloat4 = this._updateFloat4ForUniform;
  25294. this.updateMatrix = this._updateMatrixForUniform;
  25295. this.updateVector3 = this._updateVector3ForUniform;
  25296. this.updateVector4 = this._updateVector4ForUniform;
  25297. this.updateColor3 = this._updateColor3ForUniform;
  25298. this.updateColor4 = this._updateColor4ForUniform;
  25299. }
  25300. }
  25301. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  25302. // Properties
  25303. /**
  25304. * Indicates if the buffer is using the WebGL2 UBO implementation,
  25305. * or just falling back on setUniformXXX calls.
  25306. */
  25307. get: function () {
  25308. return !this._noUBO;
  25309. },
  25310. enumerable: true,
  25311. configurable: true
  25312. });
  25313. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  25314. /**
  25315. * Indicates if the WebGL underlying uniform buffer is in sync
  25316. * with the javascript cache data.
  25317. */
  25318. get: function () {
  25319. return !this._needSync;
  25320. },
  25321. enumerable: true,
  25322. configurable: true
  25323. });
  25324. /**
  25325. * Indicates if the WebGL underlying uniform buffer is dynamic.
  25326. * Also, a dynamic UniformBuffer will disable cache verification and always
  25327. * update the underlying WebGL uniform buffer to the GPU.
  25328. */
  25329. UniformBuffer.prototype.isDynamic = function () {
  25330. return this._dynamic;
  25331. };
  25332. /**
  25333. * The data cache on JS side.
  25334. */
  25335. UniformBuffer.prototype.getData = function () {
  25336. return this._bufferData;
  25337. };
  25338. /**
  25339. * The underlying WebGL Uniform buffer.
  25340. */
  25341. UniformBuffer.prototype.getBuffer = function () {
  25342. return this._buffer;
  25343. };
  25344. /**
  25345. * std140 layout specifies how to align data within an UBO structure.
  25346. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  25347. * for specs.
  25348. */
  25349. UniformBuffer.prototype._fillAlignment = function (size) {
  25350. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  25351. // and 4x4 matrices
  25352. // TODO : change if other types are used
  25353. var alignment;
  25354. if (size <= 2) {
  25355. alignment = size;
  25356. }
  25357. else {
  25358. alignment = 4;
  25359. }
  25360. if ((this._uniformLocationPointer % alignment) !== 0) {
  25361. var oldPointer = this._uniformLocationPointer;
  25362. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  25363. var diff = this._uniformLocationPointer - oldPointer;
  25364. for (var i = 0; i < diff; i++) {
  25365. this._data.push(0);
  25366. }
  25367. }
  25368. };
  25369. /**
  25370. * Adds an uniform in the buffer.
  25371. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  25372. * for the layout to be correct !
  25373. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25374. * @param {number|number[]} size Data size, or data directly.
  25375. */
  25376. UniformBuffer.prototype.addUniform = function (name, size) {
  25377. if (this._noUBO) {
  25378. return;
  25379. }
  25380. if (this._uniformLocations[name] !== undefined) {
  25381. // Already existing uniform
  25382. return;
  25383. }
  25384. // This function must be called in the order of the shader layout !
  25385. // size can be the size of the uniform, or data directly
  25386. var data;
  25387. if (size instanceof Array) {
  25388. data = size;
  25389. size = data.length;
  25390. }
  25391. else {
  25392. size = size;
  25393. data = [];
  25394. // Fill with zeros
  25395. for (var i = 0; i < size; i++) {
  25396. data.push(0);
  25397. }
  25398. }
  25399. this._fillAlignment(size);
  25400. this._uniformSizes[name] = size;
  25401. this._uniformLocations[name] = this._uniformLocationPointer;
  25402. this._uniformLocationPointer += size;
  25403. for (var i = 0; i < size; i++) {
  25404. this._data.push(data[i]);
  25405. }
  25406. this._needSync = true;
  25407. };
  25408. /**
  25409. * Wrapper for addUniform.
  25410. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25411. * @param {Matrix} mat A 4x4 matrix.
  25412. */
  25413. UniformBuffer.prototype.addMatrix = function (name, mat) {
  25414. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  25415. };
  25416. /**
  25417. * Wrapper for addUniform.
  25418. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25419. * @param {number} x
  25420. * @param {number} y
  25421. */
  25422. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  25423. var temp = [x, y];
  25424. this.addUniform(name, temp);
  25425. };
  25426. /**
  25427. * Wrapper for addUniform.
  25428. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25429. * @param {number} x
  25430. * @param {number} y
  25431. * @param {number} z
  25432. */
  25433. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  25434. var temp = [x, y, z];
  25435. this.addUniform(name, temp);
  25436. };
  25437. /**
  25438. * Wrapper for addUniform.
  25439. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25440. * @param {Color3} color
  25441. */
  25442. UniformBuffer.prototype.addColor3 = function (name, color) {
  25443. var temp = [];
  25444. color.toArray(temp);
  25445. this.addUniform(name, temp);
  25446. };
  25447. /**
  25448. * Wrapper for addUniform.
  25449. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25450. * @param {Color3} color
  25451. * @param {number} alpha
  25452. */
  25453. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  25454. var temp = [];
  25455. color.toArray(temp);
  25456. temp.push(alpha);
  25457. this.addUniform(name, temp);
  25458. };
  25459. /**
  25460. * Wrapper for addUniform.
  25461. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25462. * @param {Vector3} vector
  25463. */
  25464. UniformBuffer.prototype.addVector3 = function (name, vector) {
  25465. var temp = [];
  25466. vector.toArray(temp);
  25467. this.addUniform(name, temp);
  25468. };
  25469. /**
  25470. * Wrapper for addUniform.
  25471. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25472. */
  25473. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  25474. this.addUniform(name, 12);
  25475. };
  25476. /**
  25477. * Wrapper for addUniform.
  25478. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25479. */
  25480. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  25481. this.addUniform(name, 8);
  25482. };
  25483. /**
  25484. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  25485. */
  25486. UniformBuffer.prototype.create = function () {
  25487. if (this._noUBO) {
  25488. return;
  25489. }
  25490. if (this._buffer) {
  25491. return; // nothing to do
  25492. }
  25493. // See spec, alignment must be filled as a vec4
  25494. this._fillAlignment(4);
  25495. this._bufferData = new Float32Array(this._data);
  25496. if (this._dynamic) {
  25497. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  25498. }
  25499. else {
  25500. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  25501. }
  25502. this._needSync = true;
  25503. };
  25504. /**
  25505. * Updates the WebGL Uniform Buffer on the GPU.
  25506. * If the `dynamic` flag is set to true, no cache comparison is done.
  25507. * Otherwise, the buffer will be updated only if the cache differs.
  25508. */
  25509. UniformBuffer.prototype.update = function () {
  25510. if (!this._buffer) {
  25511. this.create();
  25512. return;
  25513. }
  25514. if (!this._dynamic && !this._needSync) {
  25515. return;
  25516. }
  25517. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  25518. this._needSync = false;
  25519. };
  25520. /**
  25521. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  25522. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  25523. * @param {number[]|Float32Array} data Flattened data
  25524. * @param {number} size Size of the data.
  25525. */
  25526. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  25527. var location = this._uniformLocations[uniformName];
  25528. if (location === undefined) {
  25529. if (this._buffer) {
  25530. // Cannot add an uniform if the buffer is already created
  25531. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  25532. return;
  25533. }
  25534. this.addUniform(uniformName, size);
  25535. location = this._uniformLocations[uniformName];
  25536. }
  25537. if (!this._buffer) {
  25538. this.create();
  25539. }
  25540. if (!this._dynamic) {
  25541. // Cache for static uniform buffers
  25542. var changed = false;
  25543. for (var i = 0; i < size; i++) {
  25544. if (this._bufferData[location + i] !== data[i]) {
  25545. changed = true;
  25546. this._bufferData[location + i] = data[i];
  25547. }
  25548. }
  25549. this._needSync = this._needSync || changed;
  25550. }
  25551. else {
  25552. // No cache for dynamic
  25553. for (var i = 0; i < size; i++) {
  25554. this._bufferData[location + i] = data[i];
  25555. }
  25556. }
  25557. };
  25558. // Update methods
  25559. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  25560. // To match std140, matrix must be realigned
  25561. for (var i = 0; i < 3; i++) {
  25562. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  25563. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  25564. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  25565. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  25566. }
  25567. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  25568. };
  25569. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  25570. this._currentEffect.setMatrix3x3(name, matrix);
  25571. };
  25572. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  25573. this._currentEffect.setMatrix2x2(name, matrix);
  25574. };
  25575. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  25576. // To match std140, matrix must be realigned
  25577. for (var i = 0; i < 2; i++) {
  25578. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  25579. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  25580. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  25581. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  25582. }
  25583. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  25584. };
  25585. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  25586. this._currentEffect.setFloat(name, x);
  25587. };
  25588. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  25589. UniformBuffer._tempBuffer[0] = x;
  25590. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  25591. };
  25592. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  25593. if (suffix === void 0) { suffix = ""; }
  25594. this._currentEffect.setFloat2(name + suffix, x, y);
  25595. };
  25596. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  25597. if (suffix === void 0) { suffix = ""; }
  25598. UniformBuffer._tempBuffer[0] = x;
  25599. UniformBuffer._tempBuffer[1] = y;
  25600. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  25601. };
  25602. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  25603. if (suffix === void 0) { suffix = ""; }
  25604. this._currentEffect.setFloat3(name + suffix, x, y, z);
  25605. };
  25606. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  25607. if (suffix === void 0) { suffix = ""; }
  25608. UniformBuffer._tempBuffer[0] = x;
  25609. UniformBuffer._tempBuffer[1] = y;
  25610. UniformBuffer._tempBuffer[2] = z;
  25611. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  25612. };
  25613. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  25614. if (suffix === void 0) { suffix = ""; }
  25615. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  25616. };
  25617. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  25618. if (suffix === void 0) { suffix = ""; }
  25619. UniformBuffer._tempBuffer[0] = x;
  25620. UniformBuffer._tempBuffer[1] = y;
  25621. UniformBuffer._tempBuffer[2] = z;
  25622. UniformBuffer._tempBuffer[3] = w;
  25623. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  25624. };
  25625. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  25626. this._currentEffect.setMatrix(name, mat);
  25627. };
  25628. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  25629. this.updateUniform(name, mat.toArray(), 16);
  25630. };
  25631. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  25632. this._currentEffect.setVector3(name, vector);
  25633. };
  25634. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  25635. vector.toArray(UniformBuffer._tempBuffer);
  25636. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  25637. };
  25638. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  25639. this._currentEffect.setVector4(name, vector);
  25640. };
  25641. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  25642. vector.toArray(UniformBuffer._tempBuffer);
  25643. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  25644. };
  25645. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  25646. if (suffix === void 0) { suffix = ""; }
  25647. this._currentEffect.setColor3(name + suffix, color);
  25648. };
  25649. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  25650. if (suffix === void 0) { suffix = ""; }
  25651. color.toArray(UniformBuffer._tempBuffer);
  25652. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  25653. };
  25654. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  25655. if (suffix === void 0) { suffix = ""; }
  25656. this._currentEffect.setColor4(name + suffix, color, alpha);
  25657. };
  25658. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  25659. if (suffix === void 0) { suffix = ""; }
  25660. color.toArray(UniformBuffer._tempBuffer);
  25661. UniformBuffer._tempBuffer[3] = alpha;
  25662. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  25663. };
  25664. /**
  25665. * Sets a sampler uniform on the effect.
  25666. * @param {string} name Name of the sampler.
  25667. * @param {Texture} texture
  25668. */
  25669. UniformBuffer.prototype.setTexture = function (name, texture) {
  25670. this._currentEffect.setTexture(name, texture);
  25671. };
  25672. /**
  25673. * Directly updates the value of the uniform in the cache AND on the GPU.
  25674. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  25675. * @param {number[]|Float32Array} data Flattened data
  25676. */
  25677. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  25678. this.updateUniform(uniformName, data, data.length);
  25679. this.update();
  25680. };
  25681. /**
  25682. * Binds this uniform buffer to an effect.
  25683. * @param {Effect} effect
  25684. * @param {string} name Name of the uniform block in the shader.
  25685. */
  25686. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  25687. this._currentEffect = effect;
  25688. if (this._noUBO) {
  25689. return;
  25690. }
  25691. effect.bindUniformBuffer(this._buffer, name);
  25692. };
  25693. /**
  25694. * Disposes the uniform buffer.
  25695. */
  25696. UniformBuffer.prototype.dispose = function () {
  25697. if (!this._buffer) {
  25698. return;
  25699. }
  25700. if (this._engine._releaseBuffer(this._buffer)) {
  25701. this._buffer = null;
  25702. }
  25703. };
  25704. return UniformBuffer;
  25705. }());
  25706. // Pool for avoiding memory leaks
  25707. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  25708. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  25709. BABYLON.UniformBuffer = UniformBuffer;
  25710. })(BABYLON || (BABYLON = {}));
  25711. //# sourceMappingURL=babylon.uniformBuffer.js.map
  25712. var BABYLON;
  25713. (function (BABYLON) {
  25714. var PushMaterial = (function (_super) {
  25715. __extends(PushMaterial, _super);
  25716. function PushMaterial(name, scene) {
  25717. var _this = _super.call(this, name, scene) || this;
  25718. _this.storeEffectOnSubMeshes = true;
  25719. return _this;
  25720. }
  25721. PushMaterial.prototype.getEffect = function () {
  25722. return this._activeEffect;
  25723. };
  25724. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  25725. if (!mesh) {
  25726. return false;
  25727. }
  25728. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25729. return true;
  25730. }
  25731. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  25732. };
  25733. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  25734. this._activeEffect.setMatrix("world", world);
  25735. };
  25736. PushMaterial.prototype.bind = function (world, mesh) {
  25737. if (!mesh) {
  25738. return;
  25739. }
  25740. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  25741. };
  25742. PushMaterial.prototype._afterBind = function (mesh, effect) {
  25743. _super.prototype._afterBind.call(this, mesh);
  25744. this.getScene()._cachedEffect = effect;
  25745. };
  25746. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  25747. if (visibility === void 0) { visibility = 0; }
  25748. return scene.isCachedMaterialValid(this, effect, visibility);
  25749. };
  25750. return PushMaterial;
  25751. }(BABYLON.Material));
  25752. BABYLON.PushMaterial = PushMaterial;
  25753. })(BABYLON || (BABYLON = {}));
  25754. //# sourceMappingURL=babylon.pushMaterial.js.map
  25755. var BABYLON;
  25756. (function (BABYLON) {
  25757. var VertexData = (function () {
  25758. function VertexData() {
  25759. }
  25760. VertexData.prototype.set = function (data, kind) {
  25761. switch (kind) {
  25762. case BABYLON.VertexBuffer.PositionKind:
  25763. this.positions = data;
  25764. break;
  25765. case BABYLON.VertexBuffer.NormalKind:
  25766. this.normals = data;
  25767. break;
  25768. case BABYLON.VertexBuffer.TangentKind:
  25769. this.tangents = data;
  25770. break;
  25771. case BABYLON.VertexBuffer.UVKind:
  25772. this.uvs = data;
  25773. break;
  25774. case BABYLON.VertexBuffer.UV2Kind:
  25775. this.uvs2 = data;
  25776. break;
  25777. case BABYLON.VertexBuffer.UV3Kind:
  25778. this.uvs3 = data;
  25779. break;
  25780. case BABYLON.VertexBuffer.UV4Kind:
  25781. this.uvs4 = data;
  25782. break;
  25783. case BABYLON.VertexBuffer.UV5Kind:
  25784. this.uvs5 = data;
  25785. break;
  25786. case BABYLON.VertexBuffer.UV6Kind:
  25787. this.uvs6 = data;
  25788. break;
  25789. case BABYLON.VertexBuffer.ColorKind:
  25790. this.colors = data;
  25791. break;
  25792. case BABYLON.VertexBuffer.MatricesIndicesKind:
  25793. this.matricesIndices = data;
  25794. break;
  25795. case BABYLON.VertexBuffer.MatricesWeightsKind:
  25796. this.matricesWeights = data;
  25797. break;
  25798. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  25799. this.matricesIndicesExtra = data;
  25800. break;
  25801. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  25802. this.matricesWeightsExtra = data;
  25803. break;
  25804. }
  25805. };
  25806. /**
  25807. * Associates the vertexData to the passed Mesh.
  25808. * Sets it as updatable or not (default `false`).
  25809. * Returns the VertexData.
  25810. */
  25811. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  25812. this._applyTo(mesh, updatable);
  25813. return this;
  25814. };
  25815. /**
  25816. * Associates the vertexData to the passed Geometry.
  25817. * Sets it as updatable or not (default `false`).
  25818. * Returns the VertexData.
  25819. */
  25820. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  25821. this._applyTo(geometry, updatable);
  25822. return this;
  25823. };
  25824. /**
  25825. * Updates the associated mesh.
  25826. * Returns the VertexData.
  25827. */
  25828. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  25829. this._update(mesh);
  25830. return this;
  25831. };
  25832. /**
  25833. * Updates the associated geometry.
  25834. * Returns the VertexData.
  25835. */
  25836. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  25837. this._update(geometry);
  25838. return this;
  25839. };
  25840. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  25841. if (this.positions) {
  25842. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  25843. }
  25844. if (this.normals) {
  25845. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  25846. }
  25847. if (this.tangents) {
  25848. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  25849. }
  25850. if (this.uvs) {
  25851. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  25852. }
  25853. if (this.uvs2) {
  25854. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  25855. }
  25856. if (this.uvs3) {
  25857. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  25858. }
  25859. if (this.uvs4) {
  25860. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  25861. }
  25862. if (this.uvs5) {
  25863. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  25864. }
  25865. if (this.uvs6) {
  25866. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  25867. }
  25868. if (this.colors) {
  25869. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  25870. }
  25871. if (this.matricesIndices) {
  25872. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  25873. }
  25874. if (this.matricesWeights) {
  25875. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  25876. }
  25877. if (this.matricesIndicesExtra) {
  25878. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  25879. }
  25880. if (this.matricesWeightsExtra) {
  25881. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  25882. }
  25883. if (this.indices) {
  25884. meshOrGeometry.setIndices(this.indices);
  25885. }
  25886. return this;
  25887. };
  25888. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  25889. if (this.positions) {
  25890. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  25891. }
  25892. if (this.normals) {
  25893. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  25894. }
  25895. if (this.tangents) {
  25896. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  25897. }
  25898. if (this.uvs) {
  25899. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  25900. }
  25901. if (this.uvs2) {
  25902. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  25903. }
  25904. if (this.uvs3) {
  25905. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  25906. }
  25907. if (this.uvs4) {
  25908. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  25909. }
  25910. if (this.uvs5) {
  25911. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  25912. }
  25913. if (this.uvs6) {
  25914. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  25915. }
  25916. if (this.colors) {
  25917. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  25918. }
  25919. if (this.matricesIndices) {
  25920. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  25921. }
  25922. if (this.matricesWeights) {
  25923. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  25924. }
  25925. if (this.matricesIndicesExtra) {
  25926. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  25927. }
  25928. if (this.matricesWeightsExtra) {
  25929. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  25930. }
  25931. if (this.indices) {
  25932. meshOrGeometry.setIndices(this.indices);
  25933. }
  25934. return this;
  25935. };
  25936. /**
  25937. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  25938. * Returns the VertexData.
  25939. */
  25940. VertexData.prototype.transform = function (matrix) {
  25941. var transformed = BABYLON.Vector3.Zero();
  25942. var index;
  25943. if (this.positions) {
  25944. var position = BABYLON.Vector3.Zero();
  25945. for (index = 0; index < this.positions.length; index += 3) {
  25946. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  25947. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  25948. this.positions[index] = transformed.x;
  25949. this.positions[index + 1] = transformed.y;
  25950. this.positions[index + 2] = transformed.z;
  25951. }
  25952. }
  25953. if (this.normals) {
  25954. var normal = BABYLON.Vector3.Zero();
  25955. for (index = 0; index < this.normals.length; index += 3) {
  25956. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  25957. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  25958. this.normals[index] = transformed.x;
  25959. this.normals[index + 1] = transformed.y;
  25960. this.normals[index + 2] = transformed.z;
  25961. }
  25962. }
  25963. if (this.tangents) {
  25964. var tangent = BABYLON.Vector4.Zero();
  25965. var tangentTransformed = BABYLON.Vector4.Zero();
  25966. for (index = 0; index < this.tangents.length; index += 4) {
  25967. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  25968. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  25969. this.tangents[index] = tangentTransformed.x;
  25970. this.tangents[index + 1] = tangentTransformed.y;
  25971. this.tangents[index + 2] = tangentTransformed.z;
  25972. this.tangents[index + 3] = tangentTransformed.w;
  25973. }
  25974. }
  25975. return this;
  25976. };
  25977. /**
  25978. * Merges the passed VertexData into the current one.
  25979. * Returns the modified VertexData.
  25980. */
  25981. VertexData.prototype.merge = function (other) {
  25982. if (other.indices) {
  25983. if (!this.indices) {
  25984. this.indices = [];
  25985. }
  25986. var offset = this.positions ? this.positions.length / 3 : 0;
  25987. for (var index = 0; index < other.indices.length; index++) {
  25988. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  25989. this.indices.push(other.indices[index] + offset);
  25990. }
  25991. }
  25992. this.positions = this._mergeElement(this.positions, other.positions);
  25993. this.normals = this._mergeElement(this.normals, other.normals);
  25994. this.tangents = this._mergeElement(this.tangents, other.tangents);
  25995. this.uvs = this._mergeElement(this.uvs, other.uvs);
  25996. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  25997. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  25998. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  25999. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  26000. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  26001. this.colors = this._mergeElement(this.colors, other.colors);
  26002. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  26003. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  26004. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  26005. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  26006. return this;
  26007. };
  26008. VertexData.prototype._mergeElement = function (source, other) {
  26009. if (!other)
  26010. return source;
  26011. if (!source)
  26012. return other;
  26013. var len = other.length + source.length;
  26014. var isSrcTypedArray = source instanceof Float32Array;
  26015. var isOthTypedArray = other instanceof Float32Array;
  26016. // use non-loop method when the source is Float32Array
  26017. if (isSrcTypedArray) {
  26018. var ret32 = new Float32Array(len);
  26019. ret32.set(source);
  26020. ret32.set(other, source.length);
  26021. return ret32;
  26022. // source is number[], when other is also use concat
  26023. }
  26024. else if (!isOthTypedArray) {
  26025. return source.concat(other);
  26026. // source is a number[], but other is a Float32Array, loop required
  26027. }
  26028. else {
  26029. var ret = source.slice(0); // copy source to a separate array
  26030. for (var i = 0, len = other.length; i < len; i++) {
  26031. ret.push(other[i]);
  26032. }
  26033. return ret;
  26034. }
  26035. };
  26036. /**
  26037. * Serializes the VertexData.
  26038. * Returns a serialized object.
  26039. */
  26040. VertexData.prototype.serialize = function () {
  26041. var serializationObject = this.serialize();
  26042. if (this.positions) {
  26043. serializationObject.positions = this.positions;
  26044. }
  26045. if (this.normals) {
  26046. serializationObject.normals = this.normals;
  26047. }
  26048. if (this.tangents) {
  26049. serializationObject.tangents = this.tangents;
  26050. }
  26051. if (this.uvs) {
  26052. serializationObject.uvs = this.uvs;
  26053. }
  26054. if (this.uvs2) {
  26055. serializationObject.uvs2 = this.uvs2;
  26056. }
  26057. if (this.uvs3) {
  26058. serializationObject.uvs3 = this.uvs3;
  26059. }
  26060. if (this.uvs4) {
  26061. serializationObject.uvs4 = this.uvs4;
  26062. }
  26063. if (this.uvs5) {
  26064. serializationObject.uvs5 = this.uvs5;
  26065. }
  26066. if (this.uvs6) {
  26067. serializationObject.uvs6 = this.uvs6;
  26068. }
  26069. if (this.colors) {
  26070. serializationObject.colors = this.colors;
  26071. }
  26072. if (this.matricesIndices) {
  26073. serializationObject.matricesIndices = this.matricesIndices;
  26074. serializationObject.matricesIndices._isExpanded = true;
  26075. }
  26076. if (this.matricesWeights) {
  26077. serializationObject.matricesWeights = this.matricesWeights;
  26078. }
  26079. if (this.matricesIndicesExtra) {
  26080. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  26081. serializationObject.matricesIndicesExtra._isExpanded = true;
  26082. }
  26083. if (this.matricesWeightsExtra) {
  26084. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  26085. }
  26086. serializationObject.indices = this.indices;
  26087. return serializationObject;
  26088. };
  26089. // Statics
  26090. /**
  26091. * Returns the object VertexData associated to the passed mesh.
  26092. */
  26093. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  26094. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  26095. };
  26096. /**
  26097. * Returns the object VertexData associated to the passed geometry.
  26098. */
  26099. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  26100. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  26101. };
  26102. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  26103. var result = new VertexData();
  26104. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26105. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  26106. }
  26107. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26108. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  26109. }
  26110. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  26111. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  26112. }
  26113. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26114. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  26115. }
  26116. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26117. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  26118. }
  26119. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26120. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  26121. }
  26122. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26123. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  26124. }
  26125. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26126. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  26127. }
  26128. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26129. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  26130. }
  26131. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26132. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  26133. }
  26134. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26135. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  26136. }
  26137. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26138. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  26139. }
  26140. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  26141. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  26142. }
  26143. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  26144. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  26145. }
  26146. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  26147. return result;
  26148. };
  26149. /**
  26150. * Creates the vertexData of the Ribbon.
  26151. */
  26152. VertexData.CreateRibbon = function (options) {
  26153. var pathArray = options.pathArray;
  26154. var closeArray = options.closeArray || false;
  26155. var closePath = options.closePath || false;
  26156. var invertUV = options.invertUV || false;
  26157. var defaultOffset = Math.floor(pathArray[0].length / 2);
  26158. var offset = options.offset || defaultOffset;
  26159. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  26160. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26161. var customUV = options.uvs;
  26162. var customColors = options.colors;
  26163. var positions = [];
  26164. var indices = [];
  26165. var normals = [];
  26166. var uvs = [];
  26167. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  26168. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  26169. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  26170. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  26171. var minlg; // minimal length among all paths from pathArray
  26172. var lg = []; // array of path lengths : nb of vertex per path
  26173. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  26174. var p; // path iterator
  26175. var i; // point iterator
  26176. var j; // point iterator
  26177. // if single path in pathArray
  26178. if (pathArray.length < 2) {
  26179. var ar1 = [];
  26180. var ar2 = [];
  26181. for (i = 0; i < pathArray[0].length - offset; i++) {
  26182. ar1.push(pathArray[0][i]);
  26183. ar2.push(pathArray[0][i + offset]);
  26184. }
  26185. pathArray = [ar1, ar2];
  26186. }
  26187. // positions and horizontal distances (u)
  26188. var idc = 0;
  26189. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  26190. var path;
  26191. var l;
  26192. minlg = pathArray[0].length;
  26193. var vectlg;
  26194. var dist;
  26195. for (p = 0; p < pathArray.length; p++) {
  26196. uTotalDistance[p] = 0;
  26197. us[p] = [0];
  26198. path = pathArray[p];
  26199. l = path.length;
  26200. minlg = (minlg < l) ? minlg : l;
  26201. j = 0;
  26202. while (j < l) {
  26203. positions.push(path[j].x, path[j].y, path[j].z);
  26204. if (j > 0) {
  26205. vectlg = path[j].subtract(path[j - 1]).length();
  26206. dist = vectlg + uTotalDistance[p];
  26207. us[p].push(dist);
  26208. uTotalDistance[p] = dist;
  26209. }
  26210. j++;
  26211. }
  26212. if (closePath) {
  26213. j--;
  26214. positions.push(path[0].x, path[0].y, path[0].z);
  26215. vectlg = path[j].subtract(path[0]).length();
  26216. dist = vectlg + uTotalDistance[p];
  26217. us[p].push(dist);
  26218. uTotalDistance[p] = dist;
  26219. }
  26220. lg[p] = l + closePathCorr;
  26221. idx[p] = idc;
  26222. idc += (l + closePathCorr);
  26223. }
  26224. // vertical distances (v)
  26225. var path1;
  26226. var path2;
  26227. var vertex1;
  26228. var vertex2;
  26229. for (i = 0; i < minlg + closePathCorr; i++) {
  26230. vTotalDistance[i] = 0;
  26231. vs[i] = [0];
  26232. for (p = 0; p < pathArray.length - 1; p++) {
  26233. path1 = pathArray[p];
  26234. path2 = pathArray[p + 1];
  26235. if (i === minlg) {
  26236. vertex1 = path1[0];
  26237. vertex2 = path2[0];
  26238. }
  26239. else {
  26240. vertex1 = path1[i];
  26241. vertex2 = path2[i];
  26242. }
  26243. vectlg = vertex2.subtract(vertex1).length();
  26244. dist = vectlg + vTotalDistance[i];
  26245. vs[i].push(dist);
  26246. vTotalDistance[i] = dist;
  26247. }
  26248. if (closeArray) {
  26249. path1 = pathArray[p];
  26250. path2 = pathArray[0];
  26251. if (i === minlg) {
  26252. vertex2 = path2[0];
  26253. }
  26254. vectlg = vertex2.subtract(vertex1).length();
  26255. dist = vectlg + vTotalDistance[i];
  26256. vTotalDistance[i] = dist;
  26257. }
  26258. }
  26259. // uvs
  26260. var u;
  26261. var v;
  26262. if (customUV) {
  26263. for (p = 0; p < customUV.length; p++) {
  26264. uvs.push(customUV[p].x, customUV[p].y);
  26265. }
  26266. }
  26267. else {
  26268. for (p = 0; p < pathArray.length; p++) {
  26269. for (i = 0; i < minlg + closePathCorr; i++) {
  26270. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  26271. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  26272. if (invertUV) {
  26273. uvs.push(v, u);
  26274. }
  26275. else {
  26276. uvs.push(u, v);
  26277. }
  26278. }
  26279. }
  26280. }
  26281. // indices
  26282. p = 0; // path index
  26283. var pi = 0; // positions array index
  26284. var l1 = lg[p] - 1; // path1 length
  26285. var l2 = lg[p + 1] - 1; // path2 length
  26286. var min = (l1 < l2) ? l1 : l2; // current path stop index
  26287. var shft = idx[1] - idx[0]; // shift
  26288. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  26289. while (pi <= min && p < path1nb) {
  26290. // 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
  26291. indices.push(pi, pi + shft, pi + 1);
  26292. indices.push(pi + shft + 1, pi + 1, pi + shft);
  26293. pi += 1;
  26294. if (pi === min) {
  26295. p++;
  26296. if (p === lg.length - 1) {
  26297. shft = idx[0] - idx[p];
  26298. l1 = lg[p] - 1;
  26299. l2 = lg[0] - 1;
  26300. }
  26301. else {
  26302. shft = idx[p + 1] - idx[p];
  26303. l1 = lg[p] - 1;
  26304. l2 = lg[p + 1] - 1;
  26305. }
  26306. pi = idx[p];
  26307. min = (l1 < l2) ? l1 + pi : l2 + pi;
  26308. }
  26309. }
  26310. // normals
  26311. VertexData.ComputeNormals(positions, indices, normals);
  26312. if (closePath) {
  26313. var indexFirst = 0;
  26314. var indexLast = 0;
  26315. for (p = 0; p < pathArray.length; p++) {
  26316. indexFirst = idx[p] * 3;
  26317. if (p + 1 < pathArray.length) {
  26318. indexLast = (idx[p + 1] - 1) * 3;
  26319. }
  26320. else {
  26321. indexLast = normals.length - 3;
  26322. }
  26323. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  26324. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  26325. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  26326. normals[indexLast] = normals[indexFirst];
  26327. normals[indexLast + 1] = normals[indexFirst + 1];
  26328. normals[indexLast + 2] = normals[indexFirst + 2];
  26329. }
  26330. }
  26331. // sides
  26332. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26333. // Colors
  26334. if (customColors) {
  26335. var colors = new Float32Array(customColors.length * 4);
  26336. for (var c = 0; c < customColors.length; c++) {
  26337. colors[c * 4] = customColors[c].r;
  26338. colors[c * 4 + 1] = customColors[c].g;
  26339. colors[c * 4 + 2] = customColors[c].b;
  26340. colors[c * 4 + 3] = customColors[c].a;
  26341. }
  26342. }
  26343. // Result
  26344. var vertexData = new VertexData();
  26345. var positions32 = new Float32Array(positions);
  26346. var normals32 = new Float32Array(normals);
  26347. var uvs32 = new Float32Array(uvs);
  26348. vertexData.indices = indices;
  26349. vertexData.positions = positions32;
  26350. vertexData.normals = normals32;
  26351. vertexData.uvs = uvs32;
  26352. if (customColors) {
  26353. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  26354. }
  26355. if (closePath) {
  26356. vertexData._idx = idx;
  26357. }
  26358. return vertexData;
  26359. };
  26360. /**
  26361. * Creates the VertexData of the Box.
  26362. */
  26363. VertexData.CreateBox = function (options) {
  26364. var normalsSource = [
  26365. new BABYLON.Vector3(0, 0, 1),
  26366. new BABYLON.Vector3(0, 0, -1),
  26367. new BABYLON.Vector3(1, 0, 0),
  26368. new BABYLON.Vector3(-1, 0, 0),
  26369. new BABYLON.Vector3(0, 1, 0),
  26370. new BABYLON.Vector3(0, -1, 0)
  26371. ];
  26372. var indices = [];
  26373. var positions = [];
  26374. var normals = [];
  26375. var uvs = [];
  26376. var width = options.width || options.size || 1;
  26377. var height = options.height || options.size || 1;
  26378. var depth = options.depth || options.size || 1;
  26379. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26380. var faceUV = options.faceUV || new Array(6);
  26381. var faceColors = options.faceColors;
  26382. var colors = [];
  26383. // default face colors and UV if undefined
  26384. for (var f = 0; f < 6; f++) {
  26385. if (faceUV[f] === undefined) {
  26386. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26387. }
  26388. if (faceColors && faceColors[f] === undefined) {
  26389. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26390. }
  26391. }
  26392. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  26393. // Create each face in turn.
  26394. for (var index = 0; index < normalsSource.length; index++) {
  26395. var normal = normalsSource[index];
  26396. // Get two vectors perpendicular to the face normal and to each other.
  26397. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  26398. var side2 = BABYLON.Vector3.Cross(normal, side1);
  26399. // Six indices (two triangles) per face.
  26400. var verticesLength = positions.length / 3;
  26401. indices.push(verticesLength);
  26402. indices.push(verticesLength + 1);
  26403. indices.push(verticesLength + 2);
  26404. indices.push(verticesLength);
  26405. indices.push(verticesLength + 2);
  26406. indices.push(verticesLength + 3);
  26407. // Four vertices per face.
  26408. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  26409. positions.push(vertex.x, vertex.y, vertex.z);
  26410. normals.push(normal.x, normal.y, normal.z);
  26411. uvs.push(faceUV[index].z, faceUV[index].w);
  26412. if (faceColors) {
  26413. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26414. }
  26415. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  26416. positions.push(vertex.x, vertex.y, vertex.z);
  26417. normals.push(normal.x, normal.y, normal.z);
  26418. uvs.push(faceUV[index].x, faceUV[index].w);
  26419. if (faceColors) {
  26420. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26421. }
  26422. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  26423. positions.push(vertex.x, vertex.y, vertex.z);
  26424. normals.push(normal.x, normal.y, normal.z);
  26425. uvs.push(faceUV[index].x, faceUV[index].y);
  26426. if (faceColors) {
  26427. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26428. }
  26429. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  26430. positions.push(vertex.x, vertex.y, vertex.z);
  26431. normals.push(normal.x, normal.y, normal.z);
  26432. uvs.push(faceUV[index].z, faceUV[index].y);
  26433. if (faceColors) {
  26434. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26435. }
  26436. }
  26437. // sides
  26438. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26439. // Result
  26440. var vertexData = new VertexData();
  26441. vertexData.indices = indices;
  26442. vertexData.positions = positions;
  26443. vertexData.normals = normals;
  26444. vertexData.uvs = uvs;
  26445. if (faceColors) {
  26446. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  26447. vertexData.colors = totalColors;
  26448. }
  26449. return vertexData;
  26450. };
  26451. /**
  26452. * Creates the VertexData of the Sphere.
  26453. */
  26454. VertexData.CreateSphere = function (options) {
  26455. var segments = options.segments || 32;
  26456. var diameterX = options.diameterX || options.diameter || 1;
  26457. var diameterY = options.diameterY || options.diameter || 1;
  26458. var diameterZ = options.diameterZ || options.diameter || 1;
  26459. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  26460. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  26461. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26462. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  26463. var totalZRotationSteps = 2 + segments;
  26464. var totalYRotationSteps = 2 * totalZRotationSteps;
  26465. var indices = [];
  26466. var positions = [];
  26467. var normals = [];
  26468. var uvs = [];
  26469. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  26470. var normalizedZ = zRotationStep / totalZRotationSteps;
  26471. var angleZ = normalizedZ * Math.PI * slice;
  26472. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  26473. var normalizedY = yRotationStep / totalYRotationSteps;
  26474. var angleY = normalizedY * Math.PI * 2 * arc;
  26475. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  26476. var rotationY = BABYLON.Matrix.RotationY(angleY);
  26477. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  26478. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  26479. var vertex = complete.multiply(radius);
  26480. var normal = complete.divide(radius).normalize();
  26481. positions.push(vertex.x, vertex.y, vertex.z);
  26482. normals.push(normal.x, normal.y, normal.z);
  26483. uvs.push(normalizedY, normalizedZ);
  26484. }
  26485. if (zRotationStep > 0) {
  26486. var verticesCount = positions.length / 3;
  26487. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  26488. indices.push((firstIndex));
  26489. indices.push((firstIndex + 1));
  26490. indices.push(firstIndex + totalYRotationSteps + 1);
  26491. indices.push((firstIndex + totalYRotationSteps + 1));
  26492. indices.push((firstIndex + 1));
  26493. indices.push((firstIndex + totalYRotationSteps + 2));
  26494. }
  26495. }
  26496. }
  26497. // Sides
  26498. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26499. // Result
  26500. var vertexData = new VertexData();
  26501. vertexData.indices = indices;
  26502. vertexData.positions = positions;
  26503. vertexData.normals = normals;
  26504. vertexData.uvs = uvs;
  26505. return vertexData;
  26506. };
  26507. /**
  26508. * Creates the VertexData of the Cylinder or Cone.
  26509. */
  26510. VertexData.CreateCylinder = function (options) {
  26511. var height = options.height || 2;
  26512. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  26513. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  26514. var tessellation = options.tessellation || 24;
  26515. var subdivisions = options.subdivisions || 1;
  26516. var hasRings = options.hasRings;
  26517. var enclose = options.enclose;
  26518. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  26519. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26520. var faceUV = options.faceUV || new Array(3);
  26521. var faceColors = options.faceColors;
  26522. // default face colors and UV if undefined
  26523. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  26524. var ringNb = (hasRings) ? subdivisions : 1;
  26525. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  26526. var f;
  26527. for (f = 0; f < surfaceNb; f++) {
  26528. if (faceColors && faceColors[f] === undefined) {
  26529. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26530. }
  26531. }
  26532. for (f = 0; f < surfaceNb; f++) {
  26533. if (faceUV && faceUV[f] === undefined) {
  26534. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26535. }
  26536. }
  26537. var indices = [];
  26538. var positions = [];
  26539. var normals = [];
  26540. var uvs = [];
  26541. var colors = [];
  26542. var angle_step = Math.PI * 2 * arc / tessellation;
  26543. var angle;
  26544. var h;
  26545. var radius;
  26546. var tan = (diameterBottom - diameterTop) / 2 / height;
  26547. var ringVertex = BABYLON.Vector3.Zero();
  26548. var ringNormal = BABYLON.Vector3.Zero();
  26549. var ringFirstVertex = BABYLON.Vector3.Zero();
  26550. var ringFirstNormal = BABYLON.Vector3.Zero();
  26551. var quadNormal = BABYLON.Vector3.Zero();
  26552. var Y = BABYLON.Axis.Y;
  26553. // positions, normals, uvs
  26554. var i;
  26555. var j;
  26556. var r;
  26557. var ringIdx = 1;
  26558. var s = 1; // surface index
  26559. var cs = 0;
  26560. var v = 0;
  26561. for (i = 0; i <= subdivisions; i++) {
  26562. h = i / subdivisions;
  26563. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  26564. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  26565. for (r = 0; r < ringIdx; r++) {
  26566. if (hasRings) {
  26567. s += r;
  26568. }
  26569. if (enclose) {
  26570. s += 2 * r;
  26571. }
  26572. for (j = 0; j <= tessellation; j++) {
  26573. angle = j * angle_step;
  26574. // position
  26575. ringVertex.x = Math.cos(-angle) * radius;
  26576. ringVertex.y = -height / 2 + h * height;
  26577. ringVertex.z = Math.sin(-angle) * radius;
  26578. // normal
  26579. if (diameterTop === 0 && i === subdivisions) {
  26580. // if no top cap, reuse former normals
  26581. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  26582. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  26583. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  26584. }
  26585. else {
  26586. ringNormal.x = ringVertex.x;
  26587. ringNormal.z = ringVertex.z;
  26588. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  26589. ringNormal.normalize();
  26590. }
  26591. // keep first ring vertex values for enclose
  26592. if (j === 0) {
  26593. ringFirstVertex.copyFrom(ringVertex);
  26594. ringFirstNormal.copyFrom(ringNormal);
  26595. }
  26596. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  26597. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  26598. if (hasRings) {
  26599. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  26600. }
  26601. else {
  26602. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  26603. }
  26604. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  26605. if (faceColors) {
  26606. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  26607. }
  26608. }
  26609. // if enclose, add four vertices and their dedicated normals
  26610. if (arc !== 1 && enclose) {
  26611. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  26612. positions.push(0, ringVertex.y, 0);
  26613. positions.push(0, ringVertex.y, 0);
  26614. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  26615. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  26616. quadNormal.normalize();
  26617. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  26618. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  26619. quadNormal.normalize();
  26620. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  26621. if (hasRings) {
  26622. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  26623. }
  26624. else {
  26625. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  26626. }
  26627. uvs.push(faceUV[s + 1].x, v);
  26628. uvs.push(faceUV[s + 1].z, v);
  26629. if (hasRings) {
  26630. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  26631. }
  26632. else {
  26633. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  26634. }
  26635. uvs.push(faceUV[s + 2].x, v);
  26636. uvs.push(faceUV[s + 2].z, v);
  26637. if (faceColors) {
  26638. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  26639. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  26640. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  26641. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  26642. }
  26643. }
  26644. if (cs !== s) {
  26645. cs = s;
  26646. }
  26647. }
  26648. }
  26649. // indices
  26650. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  26651. var s;
  26652. i = 0;
  26653. for (s = 0; s < subdivisions; s++) {
  26654. for (j = 0; j < tessellation; j++) {
  26655. var i0 = i * (e + 1) + j;
  26656. var i1 = (i + 1) * (e + 1) + j;
  26657. var i2 = i * (e + 1) + (j + 1);
  26658. var i3 = (i + 1) * (e + 1) + (j + 1);
  26659. indices.push(i0, i1, i2);
  26660. indices.push(i3, i2, i1);
  26661. }
  26662. if (arc !== 1 && enclose) {
  26663. indices.push(i0 + 2, i1 + 2, i2 + 2);
  26664. indices.push(i3 + 2, i2 + 2, i1 + 2);
  26665. indices.push(i0 + 4, i1 + 4, i2 + 4);
  26666. indices.push(i3 + 4, i2 + 4, i1 + 4);
  26667. }
  26668. i = (hasRings) ? (i + 2) : (i + 1);
  26669. }
  26670. // Caps
  26671. var createCylinderCap = function (isTop) {
  26672. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  26673. if (radius === 0) {
  26674. return;
  26675. }
  26676. // Cap positions, normals & uvs
  26677. var angle;
  26678. var circleVector;
  26679. var i;
  26680. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  26681. var c;
  26682. if (faceColors) {
  26683. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  26684. }
  26685. // cap center
  26686. var vbase = positions.length / 3;
  26687. var offset = isTop ? height / 2 : -height / 2;
  26688. var center = new BABYLON.Vector3(0, offset, 0);
  26689. positions.push(center.x, center.y, center.z);
  26690. normals.push(0, isTop ? 1 : -1, 0);
  26691. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  26692. if (faceColors) {
  26693. colors.push(c.r, c.g, c.b, c.a);
  26694. }
  26695. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  26696. for (i = 0; i <= tessellation; i++) {
  26697. angle = Math.PI * 2 * i * arc / tessellation;
  26698. var cos = Math.cos(-angle);
  26699. var sin = Math.sin(-angle);
  26700. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  26701. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  26702. positions.push(circleVector.x, circleVector.y, circleVector.z);
  26703. normals.push(0, isTop ? 1 : -1, 0);
  26704. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  26705. if (faceColors) {
  26706. colors.push(c.r, c.g, c.b, c.a);
  26707. }
  26708. }
  26709. // Cap indices
  26710. for (i = 0; i < tessellation; i++) {
  26711. if (!isTop) {
  26712. indices.push(vbase);
  26713. indices.push(vbase + (i + 1));
  26714. indices.push(vbase + (i + 2));
  26715. }
  26716. else {
  26717. indices.push(vbase);
  26718. indices.push(vbase + (i + 2));
  26719. indices.push(vbase + (i + 1));
  26720. }
  26721. }
  26722. };
  26723. // add caps to geometry
  26724. createCylinderCap(false);
  26725. createCylinderCap(true);
  26726. // Sides
  26727. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26728. var vertexData = new VertexData();
  26729. vertexData.indices = indices;
  26730. vertexData.positions = positions;
  26731. vertexData.normals = normals;
  26732. vertexData.uvs = uvs;
  26733. if (faceColors) {
  26734. vertexData.colors = colors;
  26735. }
  26736. return vertexData;
  26737. };
  26738. /**
  26739. * Creates the VertexData of the Torus.
  26740. */
  26741. VertexData.CreateTorus = function (options) {
  26742. var indices = [];
  26743. var positions = [];
  26744. var normals = [];
  26745. var uvs = [];
  26746. var diameter = options.diameter || 1;
  26747. var thickness = options.thickness || 0.5;
  26748. var tessellation = options.tessellation || 16;
  26749. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26750. var stride = tessellation + 1;
  26751. for (var i = 0; i <= tessellation; i++) {
  26752. var u = i / tessellation;
  26753. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  26754. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  26755. for (var j = 0; j <= tessellation; j++) {
  26756. var v = 1 - j / tessellation;
  26757. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  26758. var dx = Math.cos(innerAngle);
  26759. var dy = Math.sin(innerAngle);
  26760. // Create a vertex.
  26761. var normal = new BABYLON.Vector3(dx, dy, 0);
  26762. var position = normal.scale(thickness / 2);
  26763. var textureCoordinate = new BABYLON.Vector2(u, v);
  26764. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  26765. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  26766. positions.push(position.x, position.y, position.z);
  26767. normals.push(normal.x, normal.y, normal.z);
  26768. uvs.push(textureCoordinate.x, textureCoordinate.y);
  26769. // And create indices for two triangles.
  26770. var nextI = (i + 1) % stride;
  26771. var nextJ = (j + 1) % stride;
  26772. indices.push(i * stride + j);
  26773. indices.push(i * stride + nextJ);
  26774. indices.push(nextI * stride + j);
  26775. indices.push(i * stride + nextJ);
  26776. indices.push(nextI * stride + nextJ);
  26777. indices.push(nextI * stride + j);
  26778. }
  26779. }
  26780. // Sides
  26781. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26782. // Result
  26783. var vertexData = new VertexData();
  26784. vertexData.indices = indices;
  26785. vertexData.positions = positions;
  26786. vertexData.normals = normals;
  26787. vertexData.uvs = uvs;
  26788. return vertexData;
  26789. };
  26790. /**
  26791. * Creates the VertexData of the LineSystem.
  26792. */
  26793. VertexData.CreateLineSystem = function (options) {
  26794. var indices = [];
  26795. var positions = [];
  26796. var lines = options.lines;
  26797. var idx = 0;
  26798. for (var l = 0; l < lines.length; l++) {
  26799. var points = lines[l];
  26800. for (var index = 0; index < points.length; index++) {
  26801. positions.push(points[index].x, points[index].y, points[index].z);
  26802. if (index > 0) {
  26803. indices.push(idx - 1);
  26804. indices.push(idx);
  26805. }
  26806. idx++;
  26807. }
  26808. }
  26809. var vertexData = new VertexData();
  26810. vertexData.indices = indices;
  26811. vertexData.positions = positions;
  26812. return vertexData;
  26813. };
  26814. /**
  26815. * Create the VertexData of the DashedLines.
  26816. */
  26817. VertexData.CreateDashedLines = function (options) {
  26818. var dashSize = options.dashSize || 3;
  26819. var gapSize = options.gapSize || 1;
  26820. var dashNb = options.dashNb || 200;
  26821. var points = options.points;
  26822. var positions = new Array();
  26823. var indices = new Array();
  26824. var curvect = BABYLON.Vector3.Zero();
  26825. var lg = 0;
  26826. var nb = 0;
  26827. var shft = 0;
  26828. var dashshft = 0;
  26829. var curshft = 0;
  26830. var idx = 0;
  26831. var i = 0;
  26832. for (i = 0; i < points.length - 1; i++) {
  26833. points[i + 1].subtractToRef(points[i], curvect);
  26834. lg += curvect.length();
  26835. }
  26836. shft = lg / dashNb;
  26837. dashshft = dashSize * shft / (dashSize + gapSize);
  26838. for (i = 0; i < points.length - 1; i++) {
  26839. points[i + 1].subtractToRef(points[i], curvect);
  26840. nb = Math.floor(curvect.length() / shft);
  26841. curvect.normalize();
  26842. for (var j = 0; j < nb; j++) {
  26843. curshft = shft * j;
  26844. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  26845. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  26846. indices.push(idx, idx + 1);
  26847. idx += 2;
  26848. }
  26849. }
  26850. // Result
  26851. var vertexData = new VertexData();
  26852. vertexData.positions = positions;
  26853. vertexData.indices = indices;
  26854. return vertexData;
  26855. };
  26856. /**
  26857. * Creates the VertexData of the Ground.
  26858. */
  26859. VertexData.CreateGround = function (options) {
  26860. var indices = [];
  26861. var positions = [];
  26862. var normals = [];
  26863. var uvs = [];
  26864. var row, col;
  26865. var width = options.width || 1;
  26866. var height = options.height || 1;
  26867. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  26868. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  26869. for (row = 0; row <= subdivisionsY; row++) {
  26870. for (col = 0; col <= subdivisionsX; col++) {
  26871. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  26872. var normal = new BABYLON.Vector3(0, 1.0, 0);
  26873. positions.push(position.x, position.y, position.z);
  26874. normals.push(normal.x, normal.y, normal.z);
  26875. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  26876. }
  26877. }
  26878. for (row = 0; row < subdivisionsY; row++) {
  26879. for (col = 0; col < subdivisionsX; col++) {
  26880. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  26881. indices.push(col + 1 + row * (subdivisionsX + 1));
  26882. indices.push(col + row * (subdivisionsX + 1));
  26883. indices.push(col + (row + 1) * (subdivisionsX + 1));
  26884. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  26885. indices.push(col + row * (subdivisionsX + 1));
  26886. }
  26887. }
  26888. // Result
  26889. var vertexData = new VertexData();
  26890. vertexData.indices = indices;
  26891. vertexData.positions = positions;
  26892. vertexData.normals = normals;
  26893. vertexData.uvs = uvs;
  26894. return vertexData;
  26895. };
  26896. /**
  26897. * Creates the VertexData of the TiledGround.
  26898. */
  26899. VertexData.CreateTiledGround = function (options) {
  26900. var xmin = options.xmin || -1.0;
  26901. var zmin = options.zmin || -1.0;
  26902. var xmax = options.xmax || 1.0;
  26903. var zmax = options.zmax || 1.0;
  26904. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  26905. var precision = options.precision || { w: 1, h: 1 };
  26906. var indices = [];
  26907. var positions = [];
  26908. var normals = [];
  26909. var uvs = [];
  26910. var row, col, tileRow, tileCol;
  26911. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  26912. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  26913. precision.w = (precision.w < 1) ? 1 : precision.w;
  26914. precision.h = (precision.h < 1) ? 1 : precision.h;
  26915. var tileSize = {
  26916. 'w': (xmax - xmin) / subdivisions.w,
  26917. 'h': (zmax - zmin) / subdivisions.h
  26918. };
  26919. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  26920. // Indices
  26921. var base = positions.length / 3;
  26922. var rowLength = precision.w + 1;
  26923. for (row = 0; row < precision.h; row++) {
  26924. for (col = 0; col < precision.w; col++) {
  26925. var square = [
  26926. base + col + row * rowLength,
  26927. base + (col + 1) + row * rowLength,
  26928. base + (col + 1) + (row + 1) * rowLength,
  26929. base + col + (row + 1) * rowLength
  26930. ];
  26931. indices.push(square[1]);
  26932. indices.push(square[2]);
  26933. indices.push(square[3]);
  26934. indices.push(square[0]);
  26935. indices.push(square[1]);
  26936. indices.push(square[3]);
  26937. }
  26938. }
  26939. // Position, normals and uvs
  26940. var position = BABYLON.Vector3.Zero();
  26941. var normal = new BABYLON.Vector3(0, 1.0, 0);
  26942. for (row = 0; row <= precision.h; row++) {
  26943. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  26944. for (col = 0; col <= precision.w; col++) {
  26945. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  26946. position.y = 0;
  26947. positions.push(position.x, position.y, position.z);
  26948. normals.push(normal.x, normal.y, normal.z);
  26949. uvs.push(col / precision.w, row / precision.h);
  26950. }
  26951. }
  26952. }
  26953. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  26954. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  26955. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  26956. }
  26957. }
  26958. // Result
  26959. var vertexData = new VertexData();
  26960. vertexData.indices = indices;
  26961. vertexData.positions = positions;
  26962. vertexData.normals = normals;
  26963. vertexData.uvs = uvs;
  26964. return vertexData;
  26965. };
  26966. /**
  26967. * Creates the VertexData of the Ground designed from a heightmap.
  26968. */
  26969. VertexData.CreateGroundFromHeightMap = function (options) {
  26970. var indices = [];
  26971. var positions = [];
  26972. var normals = [];
  26973. var uvs = [];
  26974. var row, col;
  26975. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  26976. // Vertices
  26977. for (row = 0; row <= options.subdivisions; row++) {
  26978. for (col = 0; col <= options.subdivisions; col++) {
  26979. 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));
  26980. // Compute height
  26981. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  26982. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  26983. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  26984. var r = options.buffer[pos] / 255.0;
  26985. var g = options.buffer[pos + 1] / 255.0;
  26986. var b = options.buffer[pos + 2] / 255.0;
  26987. var gradient = r * filter.r + g * filter.g + b * filter.b;
  26988. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  26989. // Add vertex
  26990. positions.push(position.x, position.y, position.z);
  26991. normals.push(0, 0, 0);
  26992. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  26993. }
  26994. }
  26995. // Indices
  26996. for (row = 0; row < options.subdivisions; row++) {
  26997. for (col = 0; col < options.subdivisions; col++) {
  26998. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  26999. indices.push(col + 1 + row * (options.subdivisions + 1));
  27000. indices.push(col + row * (options.subdivisions + 1));
  27001. indices.push(col + (row + 1) * (options.subdivisions + 1));
  27002. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27003. indices.push(col + row * (options.subdivisions + 1));
  27004. }
  27005. }
  27006. // Normals
  27007. VertexData.ComputeNormals(positions, indices, normals);
  27008. // Result
  27009. var vertexData = new VertexData();
  27010. vertexData.indices = indices;
  27011. vertexData.positions = positions;
  27012. vertexData.normals = normals;
  27013. vertexData.uvs = uvs;
  27014. return vertexData;
  27015. };
  27016. /**
  27017. * Creates the VertexData of the Plane.
  27018. */
  27019. VertexData.CreatePlane = function (options) {
  27020. var indices = [];
  27021. var positions = [];
  27022. var normals = [];
  27023. var uvs = [];
  27024. var width = options.width || options.size || 1;
  27025. var height = options.height || options.size || 1;
  27026. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27027. // Vertices
  27028. var halfWidth = width / 2.0;
  27029. var halfHeight = height / 2.0;
  27030. positions.push(-halfWidth, -halfHeight, 0);
  27031. normals.push(0, 0, -1.0);
  27032. uvs.push(0.0, 0.0);
  27033. positions.push(halfWidth, -halfHeight, 0);
  27034. normals.push(0, 0, -1.0);
  27035. uvs.push(1.0, 0.0);
  27036. positions.push(halfWidth, halfHeight, 0);
  27037. normals.push(0, 0, -1.0);
  27038. uvs.push(1.0, 1.0);
  27039. positions.push(-halfWidth, halfHeight, 0);
  27040. normals.push(0, 0, -1.0);
  27041. uvs.push(0.0, 1.0);
  27042. // Indices
  27043. indices.push(0);
  27044. indices.push(1);
  27045. indices.push(2);
  27046. indices.push(0);
  27047. indices.push(2);
  27048. indices.push(3);
  27049. // Sides
  27050. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27051. // Result
  27052. var vertexData = new VertexData();
  27053. vertexData.indices = indices;
  27054. vertexData.positions = positions;
  27055. vertexData.normals = normals;
  27056. vertexData.uvs = uvs;
  27057. return vertexData;
  27058. };
  27059. /**
  27060. * Creates the VertexData of the Disc or regular Polygon.
  27061. */
  27062. VertexData.CreateDisc = function (options) {
  27063. var positions = [];
  27064. var indices = [];
  27065. var normals = [];
  27066. var uvs = [];
  27067. var radius = options.radius || 0.5;
  27068. var tessellation = options.tessellation || 64;
  27069. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27070. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27071. // positions and uvs
  27072. positions.push(0, 0, 0); // disc center first
  27073. uvs.push(0.5, 0.5);
  27074. var theta = Math.PI * 2 * arc;
  27075. var step = theta / tessellation;
  27076. for (var a = 0; a < theta; a += step) {
  27077. var x = Math.cos(a);
  27078. var y = Math.sin(a);
  27079. var u = (x + 1) / 2;
  27080. var v = (1 - y) / 2;
  27081. positions.push(radius * x, radius * y, 0);
  27082. uvs.push(u, v);
  27083. }
  27084. if (arc === 1) {
  27085. positions.push(positions[3], positions[4], positions[5]); // close the circle
  27086. uvs.push(uvs[2], uvs[3]);
  27087. }
  27088. //indices
  27089. var vertexNb = positions.length / 3;
  27090. for (var i = 1; i < vertexNb - 1; i++) {
  27091. indices.push(i + 1, 0, i);
  27092. }
  27093. // result
  27094. VertexData.ComputeNormals(positions, indices, normals);
  27095. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27096. var vertexData = new VertexData();
  27097. vertexData.indices = indices;
  27098. vertexData.positions = positions;
  27099. vertexData.normals = normals;
  27100. vertexData.uvs = uvs;
  27101. return vertexData;
  27102. };
  27103. /**
  27104. * Re-creates the VertexData of the Polygon for sideOrientation.
  27105. */
  27106. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  27107. var faceUV = fUV || new Array(3);
  27108. var faceColors = fColors;
  27109. var colors = [];
  27110. // default face colors and UV if undefined
  27111. for (var f = 0; f < 3; f++) {
  27112. if (faceUV[f] === undefined) {
  27113. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27114. }
  27115. if (faceColors && faceColors[f] === undefined) {
  27116. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27117. }
  27118. }
  27119. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27120. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27121. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  27122. var indices = polygon.getIndices();
  27123. // set face colours and textures
  27124. var idx = 0;
  27125. var face = 0;
  27126. for (var index = 0; index < normals.length; index += 3) {
  27127. //Edge Face no. 1
  27128. if (Math.abs(normals[index + 1]) < 0.001) {
  27129. face = 1;
  27130. }
  27131. //Top Face no. 0
  27132. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  27133. face = 0;
  27134. }
  27135. //Bottom Face no. 2
  27136. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  27137. face = 2;
  27138. }
  27139. idx = index / 3;
  27140. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  27141. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  27142. if (faceColors) {
  27143. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  27144. }
  27145. }
  27146. // sides
  27147. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  27148. // Result
  27149. var vertexData = new VertexData();
  27150. vertexData.indices = indices;
  27151. vertexData.positions = positions;
  27152. vertexData.normals = normals;
  27153. vertexData.uvs = uvs;
  27154. if (faceColors) {
  27155. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  27156. vertexData.colors = totalColors;
  27157. }
  27158. return vertexData;
  27159. };
  27160. /**
  27161. * Creates the VertexData of the IcoSphere.
  27162. */
  27163. VertexData.CreateIcoSphere = function (options) {
  27164. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27165. var radius = options.radius || 1;
  27166. var flat = (options.flat === undefined) ? true : options.flat;
  27167. var subdivisions = options.subdivisions || 4;
  27168. var radiusX = options.radiusX || radius;
  27169. var radiusY = options.radiusY || radius;
  27170. var radiusZ = options.radiusZ || radius;
  27171. var t = (1 + Math.sqrt(5)) / 2;
  27172. // 12 vertex x,y,z
  27173. var ico_vertices = [
  27174. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  27175. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  27176. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  27177. ];
  27178. // index of 3 vertex makes a face of icopshere
  27179. var ico_indices = [
  27180. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  27181. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  27182. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  27183. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  27184. ];
  27185. // vertex for uv have aliased position, not for UV
  27186. var vertices_unalias_id = [
  27187. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  27188. // vertex alias
  27189. 0,
  27190. 2,
  27191. 3,
  27192. 3,
  27193. 3,
  27194. 4,
  27195. 7,
  27196. 8,
  27197. 9,
  27198. 9,
  27199. 10,
  27200. 11 // 23: B + 12
  27201. ];
  27202. // uv as integer step (not pixels !)
  27203. var ico_vertexuv = [
  27204. 5, 1, 3, 1, 6, 4, 0, 0,
  27205. 5, 3, 4, 2, 2, 2, 4, 0,
  27206. 2, 0, 1, 1, 6, 0, 6, 2,
  27207. // vertex alias (for same vertex on different faces)
  27208. 0, 4,
  27209. 3, 3,
  27210. 4, 4,
  27211. 3, 1,
  27212. 4, 2,
  27213. 4, 4,
  27214. 0, 2,
  27215. 1, 1,
  27216. 2, 2,
  27217. 3, 3,
  27218. 1, 3,
  27219. 2, 4 // 23: B + 12
  27220. ];
  27221. // Vertices[0, 1, ...9, A, B] : position on UV plane
  27222. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  27223. // First island of uv mapping
  27224. // v = 4h 3+ 2
  27225. // v = 3h 9+ 4
  27226. // v = 2h 9+ 5 B
  27227. // v = 1h 9 1 0
  27228. // v = 0h 3 8 7 A
  27229. // u = 0 1 2 3 4 5 6 *a
  27230. // Second island of uv mapping
  27231. // v = 4h 0+ B+ 4+
  27232. // v = 3h A+ 2+
  27233. // v = 2h 7+ 6 3+
  27234. // v = 1h 8+ 3+
  27235. // v = 0h
  27236. // u = 0 1 2 3 4 5 6 *a
  27237. // Face layout on texture UV mapping
  27238. // ============
  27239. // \ 4 /\ 16 / ======
  27240. // \ / \ / /\ 11 /
  27241. // \/ 7 \/ / \ /
  27242. // ======= / 10 \/
  27243. // /\ 17 /\ =======
  27244. // / \ / \ \ 15 /\
  27245. // / 8 \/ 12 \ \ / \
  27246. // ============ \/ 6 \
  27247. // \ 18 /\ ============
  27248. // \ / \ \ 5 /\ 0 /
  27249. // \/ 13 \ \ / \ /
  27250. // ======= \/ 1 \/
  27251. // =============
  27252. // /\ 19 /\ 2 /\
  27253. // / \ / \ / \
  27254. // / 14 \/ 9 \/ 3 \
  27255. // ===================
  27256. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  27257. var ustep = 138 / 1024;
  27258. var vstep = 239 / 1024;
  27259. var uoffset = 60 / 1024;
  27260. var voffset = 26 / 1024;
  27261. // Second island should have margin, not to touch the first island
  27262. // avoid any borderline artefact in pixel rounding
  27263. var island_u_offset = -40 / 1024;
  27264. var island_v_offset = +20 / 1024;
  27265. // face is either island 0 or 1 :
  27266. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  27267. var island = [
  27268. 0, 0, 0, 0, 1,
  27269. 0, 0, 1, 1, 0,
  27270. 0, 0, 1, 1, 0,
  27271. 0, 1, 1, 1, 0 // 15 - 19
  27272. ];
  27273. var indices = [];
  27274. var positions = [];
  27275. var normals = [];
  27276. var uvs = [];
  27277. var current_indice = 0;
  27278. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  27279. var face_vertex_pos = new Array(3);
  27280. var face_vertex_uv = new Array(3);
  27281. var v012;
  27282. for (v012 = 0; v012 < 3; v012++) {
  27283. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  27284. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  27285. }
  27286. // create all with normals
  27287. for (var face = 0; face < 20; face++) {
  27288. // 3 vertex per face
  27289. for (v012 = 0; v012 < 3; v012++) {
  27290. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  27291. var v_id = ico_indices[3 * face + v012];
  27292. // vertex have 3D position (x,y,z)
  27293. 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]);
  27294. // Normalize to get normal, then scale to radius
  27295. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  27296. // uv Coordinates from vertex ID
  27297. 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);
  27298. }
  27299. // Subdivide the face (interpolate pos, norm, uv)
  27300. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  27301. // - norm is linear interpolation of vertex corner normal
  27302. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  27303. // - uv is linear interpolation
  27304. //
  27305. // Topology is as below for sub-divide by 2
  27306. // vertex shown as v0,v1,v2
  27307. // interp index is i1 to progress in range [v0,v1[
  27308. // interp index is i2 to progress in range [v0,v2[
  27309. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  27310. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  27311. //
  27312. //
  27313. // i2 v2
  27314. // ^ ^
  27315. // / / \
  27316. // / / \
  27317. // / / \
  27318. // / / (0,1) \
  27319. // / #---------\
  27320. // / / \ (0,0)'/ \
  27321. // / / \ / \
  27322. // / / \ / \
  27323. // / / (0,0) \ / (1,0) \
  27324. // / #---------#---------\
  27325. // v0 v1
  27326. //
  27327. // --------------------> i1
  27328. //
  27329. // interp of (i1,i2):
  27330. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  27331. // along i1 : lerp(x0,x1, i1/(S-i2))
  27332. //
  27333. // centroid of triangle is needed to get help normal computation
  27334. // (c1,c2) are used for centroid location
  27335. var interp_vertex = function (i1, i2, c1, c2) {
  27336. // vertex is interpolated from
  27337. // - face_vertex_pos[0..2]
  27338. // - face_vertex_uv[0..2]
  27339. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  27340. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  27341. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  27342. pos_interp.normalize();
  27343. var vertex_normal;
  27344. if (flat) {
  27345. // in flat mode, recalculate normal as face centroid normal
  27346. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  27347. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  27348. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  27349. }
  27350. else {
  27351. // in smooth mode, recalculate normal from each single vertex position
  27352. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  27353. }
  27354. // Vertex normal need correction due to X,Y,Z radius scaling
  27355. vertex_normal.x /= radiusX;
  27356. vertex_normal.y /= radiusY;
  27357. vertex_normal.z /= radiusZ;
  27358. vertex_normal.normalize();
  27359. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  27360. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  27361. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  27362. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  27363. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  27364. uvs.push(uv_interp.x, uv_interp.y);
  27365. // push each vertex has member of a face
  27366. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  27367. indices.push(current_indice);
  27368. current_indice++;
  27369. };
  27370. for (var i2 = 0; i2 < subdivisions; i2++) {
  27371. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  27372. // face : (i1,i2) for /\ :
  27373. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  27374. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27375. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27376. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27377. if (i1 + i2 + 1 < subdivisions) {
  27378. // face : (i1,i2)' for \/ :
  27379. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  27380. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27381. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27382. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27383. }
  27384. }
  27385. }
  27386. }
  27387. // Sides
  27388. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27389. // Result
  27390. var vertexData = new VertexData();
  27391. vertexData.indices = indices;
  27392. vertexData.positions = positions;
  27393. vertexData.normals = normals;
  27394. vertexData.uvs = uvs;
  27395. return vertexData;
  27396. };
  27397. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  27398. /**
  27399. * Creates the VertexData of the Polyhedron.
  27400. */
  27401. VertexData.CreatePolyhedron = function (options) {
  27402. // provided polyhedron types :
  27403. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  27404. // 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)
  27405. var polyhedra = [];
  27406. 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]] };
  27407. 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]] };
  27408. polyhedra[2] = {
  27409. 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]],
  27410. 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]]
  27411. };
  27412. polyhedra[3] = {
  27413. 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]],
  27414. 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]]
  27415. };
  27416. polyhedra[4] = {
  27417. 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]],
  27418. 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]]
  27419. };
  27420. 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]] };
  27421. 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]] };
  27422. 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]] };
  27423. 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]] };
  27424. 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]] };
  27425. 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]] };
  27426. 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]] };
  27427. 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]] };
  27428. 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]] };
  27429. polyhedra[14] = {
  27430. 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]],
  27431. 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]]
  27432. };
  27433. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  27434. var size = options.size;
  27435. var sizeX = options.sizeX || size || 1;
  27436. var sizeY = options.sizeY || size || 1;
  27437. var sizeZ = options.sizeZ || size || 1;
  27438. var data = options.custom || polyhedra[type];
  27439. var nbfaces = data.face.length;
  27440. var faceUV = options.faceUV || new Array(nbfaces);
  27441. var faceColors = options.faceColors;
  27442. var flat = (options.flat === undefined) ? true : options.flat;
  27443. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27444. var positions = [];
  27445. var indices = [];
  27446. var normals = [];
  27447. var uvs = [];
  27448. var colors = [];
  27449. var index = 0;
  27450. var faceIdx = 0; // face cursor in the array "indexes"
  27451. var indexes = [];
  27452. var i = 0;
  27453. var f = 0;
  27454. var u, v, ang, x, y, tmp;
  27455. // default face colors and UV if undefined
  27456. if (flat) {
  27457. for (f = 0; f < nbfaces; f++) {
  27458. if (faceColors && faceColors[f] === undefined) {
  27459. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27460. }
  27461. if (faceUV && faceUV[f] === undefined) {
  27462. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27463. }
  27464. }
  27465. }
  27466. if (!flat) {
  27467. for (i = 0; i < data.vertex.length; i++) {
  27468. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  27469. uvs.push(0, 0);
  27470. }
  27471. for (f = 0; f < nbfaces; f++) {
  27472. for (i = 0; i < data.face[f].length - 2; i++) {
  27473. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  27474. }
  27475. }
  27476. }
  27477. else {
  27478. for (f = 0; f < nbfaces; f++) {
  27479. var fl = data.face[f].length; // number of vertices of the current face
  27480. ang = 2 * Math.PI / fl;
  27481. x = 0.5 * Math.tan(ang / 2);
  27482. y = 0.5;
  27483. // positions, uvs, colors
  27484. for (i = 0; i < fl; i++) {
  27485. // positions
  27486. 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);
  27487. indexes.push(index);
  27488. index++;
  27489. // uvs
  27490. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  27491. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  27492. uvs.push(u, v);
  27493. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  27494. y = x * Math.sin(ang) + y * Math.cos(ang);
  27495. x = tmp;
  27496. // colors
  27497. if (faceColors) {
  27498. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  27499. }
  27500. }
  27501. // indices from indexes
  27502. for (i = 0; i < fl - 2; i++) {
  27503. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  27504. }
  27505. faceIdx += fl;
  27506. }
  27507. }
  27508. VertexData.ComputeNormals(positions, indices, normals);
  27509. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27510. var vertexData = new VertexData();
  27511. vertexData.positions = positions;
  27512. vertexData.indices = indices;
  27513. vertexData.normals = normals;
  27514. vertexData.uvs = uvs;
  27515. if (faceColors && flat) {
  27516. vertexData.colors = colors;
  27517. }
  27518. return vertexData;
  27519. };
  27520. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  27521. /**
  27522. * Creates the VertexData of the Torus Knot.
  27523. */
  27524. VertexData.CreateTorusKnot = function (options) {
  27525. var indices = [];
  27526. var positions = [];
  27527. var normals = [];
  27528. var uvs = [];
  27529. var radius = options.radius || 2;
  27530. var tube = options.tube || 0.5;
  27531. var radialSegments = options.radialSegments || 32;
  27532. var tubularSegments = options.tubularSegments || 32;
  27533. var p = options.p || 2;
  27534. var q = options.q || 3;
  27535. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27536. // Helper
  27537. var getPos = function (angle) {
  27538. var cu = Math.cos(angle);
  27539. var su = Math.sin(angle);
  27540. var quOverP = q / p * angle;
  27541. var cs = Math.cos(quOverP);
  27542. var tx = radius * (2 + cs) * 0.5 * cu;
  27543. var ty = radius * (2 + cs) * su * 0.5;
  27544. var tz = radius * Math.sin(quOverP) * 0.5;
  27545. return new BABYLON.Vector3(tx, ty, tz);
  27546. };
  27547. // Vertices
  27548. var i;
  27549. var j;
  27550. for (i = 0; i <= radialSegments; i++) {
  27551. var modI = i % radialSegments;
  27552. var u = modI / radialSegments * 2 * p * Math.PI;
  27553. var p1 = getPos(u);
  27554. var p2 = getPos(u + 0.01);
  27555. var tang = p2.subtract(p1);
  27556. var n = p2.add(p1);
  27557. var bitan = BABYLON.Vector3.Cross(tang, n);
  27558. n = BABYLON.Vector3.Cross(bitan, tang);
  27559. bitan.normalize();
  27560. n.normalize();
  27561. for (j = 0; j < tubularSegments; j++) {
  27562. var modJ = j % tubularSegments;
  27563. var v = modJ / tubularSegments * 2 * Math.PI;
  27564. var cx = -tube * Math.cos(v);
  27565. var cy = tube * Math.sin(v);
  27566. positions.push(p1.x + cx * n.x + cy * bitan.x);
  27567. positions.push(p1.y + cx * n.y + cy * bitan.y);
  27568. positions.push(p1.z + cx * n.z + cy * bitan.z);
  27569. uvs.push(i / radialSegments);
  27570. uvs.push(j / tubularSegments);
  27571. }
  27572. }
  27573. for (i = 0; i < radialSegments; i++) {
  27574. for (j = 0; j < tubularSegments; j++) {
  27575. var jNext = (j + 1) % tubularSegments;
  27576. var a = i * tubularSegments + j;
  27577. var b = (i + 1) * tubularSegments + j;
  27578. var c = (i + 1) * tubularSegments + jNext;
  27579. var d = i * tubularSegments + jNext;
  27580. indices.push(d);
  27581. indices.push(b);
  27582. indices.push(a);
  27583. indices.push(d);
  27584. indices.push(c);
  27585. indices.push(b);
  27586. }
  27587. }
  27588. // Normals
  27589. VertexData.ComputeNormals(positions, indices, normals);
  27590. // Sides
  27591. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27592. // Result
  27593. var vertexData = new VertexData();
  27594. vertexData.indices = indices;
  27595. vertexData.positions = positions;
  27596. vertexData.normals = normals;
  27597. vertexData.uvs = uvs;
  27598. return vertexData;
  27599. };
  27600. // Tools
  27601. /**
  27602. * @param {any} - positions (number[] or Float32Array)
  27603. * @param {any} - indices (number[] or Uint16Array)
  27604. * @param {any} - normals (number[] or Float32Array)
  27605. * options (optional) :
  27606. * facetPositions : optional array of facet positions (vector3)
  27607. * facetNormals : optional array of facet normals (vector3)
  27608. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  27609. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  27610. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  27611. * bbSize : optional bounding box size data, required for facetPartitioning computation
  27612. * bInfo : optional bounding info, required for facetPartitioning computation
  27613. */
  27614. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  27615. // temporary scalar variables
  27616. var index = 0; // facet index
  27617. var p1p2x = 0.0; // p1p2 vector x coordinate
  27618. var p1p2y = 0.0; // p1p2 vector y coordinate
  27619. var p1p2z = 0.0; // p1p2 vector z coordinate
  27620. var p3p2x = 0.0; // p3p2 vector x coordinate
  27621. var p3p2y = 0.0; // p3p2 vector y coordinate
  27622. var p3p2z = 0.0; // p3p2 vector z coordinate
  27623. var faceNormalx = 0.0; // facet normal x coordinate
  27624. var faceNormaly = 0.0; // facet normal y coordinate
  27625. var faceNormalz = 0.0; // facet normal z coordinate
  27626. var length = 0.0; // facet normal length before normalization
  27627. var v1x = 0; // vector1 x index in the positions array
  27628. var v1y = 0; // vector1 y index in the positions array
  27629. var v1z = 0; // vector1 z index in the positions array
  27630. var v2x = 0; // vector2 x index in the positions array
  27631. var v2y = 0; // vector2 y index in the positions array
  27632. var v2z = 0; // vector2 z index in the positions array
  27633. var v3x = 0; // vector3 x index in the positions array
  27634. var v3y = 0; // vector3 y index in the positions array
  27635. var v3z = 0; // vector3 z index in the positions array
  27636. var computeFacetNormals = false;
  27637. var computeFacetPositions = false;
  27638. var computeFacetPartitioning = false;
  27639. var faceNormalSign = 1;
  27640. if (options) {
  27641. computeFacetNormals = (options.facetNormals) ? true : false;
  27642. computeFacetPositions = (options.facetPositions) ? true : false;
  27643. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  27644. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  27645. }
  27646. // facetPartitioning reinit if needed
  27647. if (computeFacetPartitioning) {
  27648. var ox = 0; // X partitioning index for facet position
  27649. var oy = 0; // Y partinioning index for facet position
  27650. var oz = 0; // Z partinioning index for facet position
  27651. var b1x = 0; // X partitioning index for facet v1 vertex
  27652. var b1y = 0; // Y partitioning index for facet v1 vertex
  27653. var b1z = 0; // z partitioning index for facet v1 vertex
  27654. var b2x = 0; // X partitioning index for facet v2 vertex
  27655. var b2y = 0; // Y partitioning index for facet v2 vertex
  27656. var b2z = 0; // Z partitioning index for facet v2 vertex
  27657. var b3x = 0; // X partitioning index for facet v3 vertex
  27658. var b3y = 0; // Y partitioning index for facet v3 vertex
  27659. var b3z = 0; // Z partitioning index for facet v3 vertex
  27660. var block_idx_o = 0; // facet barycenter block index
  27661. var block_idx_v1 = 0; // v1 vertex block index
  27662. var block_idx_v2 = 0; // v2 vertex block index
  27663. var block_idx_v3 = 0; // v3 vertex block index
  27664. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  27665. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  27666. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  27667. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  27668. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  27669. var subSq = options.subDiv.max * options.subDiv.max;
  27670. options.facetPartitioning.length = 0;
  27671. }
  27672. // reset the normals
  27673. for (index = 0; index < positions.length; index++) {
  27674. normals[index] = 0.0;
  27675. }
  27676. // Loop : 1 indice triplet = 1 facet
  27677. var nbFaces = indices.length / 3;
  27678. for (index = 0; index < nbFaces; index++) {
  27679. // get the indexes of the coordinates of each vertex of the facet
  27680. v1x = indices[index * 3] * 3;
  27681. v1y = v1x + 1;
  27682. v1z = v1x + 2;
  27683. v2x = indices[index * 3 + 1] * 3;
  27684. v2y = v2x + 1;
  27685. v2z = v2x + 2;
  27686. v3x = indices[index * 3 + 2] * 3;
  27687. v3y = v3x + 1;
  27688. v3z = v3x + 2;
  27689. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  27690. p1p2y = positions[v1y] - positions[v2y];
  27691. p1p2z = positions[v1z] - positions[v2z];
  27692. p3p2x = positions[v3x] - positions[v2x];
  27693. p3p2y = positions[v3y] - positions[v2y];
  27694. p3p2z = positions[v3z] - positions[v2z];
  27695. // compute the face normal with the cross product
  27696. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  27697. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  27698. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  27699. // normalize this normal and store it in the array facetData
  27700. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  27701. length = (length === 0) ? 1.0 : length;
  27702. faceNormalx /= length;
  27703. faceNormaly /= length;
  27704. faceNormalz /= length;
  27705. if (computeFacetNormals) {
  27706. options.facetNormals[index].x = faceNormalx;
  27707. options.facetNormals[index].y = faceNormaly;
  27708. options.facetNormals[index].z = faceNormalz;
  27709. }
  27710. if (computeFacetPositions) {
  27711. // compute and the facet barycenter coordinates in the array facetPositions
  27712. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  27713. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  27714. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  27715. }
  27716. if (computeFacetPartitioning) {
  27717. // store the facet indexes in arrays in the main facetPartitioning array :
  27718. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  27719. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  27720. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  27721. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  27722. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  27723. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  27724. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  27725. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  27726. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  27727. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  27728. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  27729. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  27730. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  27731. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  27732. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  27733. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  27734. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  27735. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  27736. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  27737. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  27738. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  27739. // push each facet index in each block containing the vertex
  27740. options.facetPartitioning[block_idx_v1].push(index);
  27741. if (block_idx_v2 != block_idx_v1) {
  27742. options.facetPartitioning[block_idx_v2].push(index);
  27743. }
  27744. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  27745. options.facetPartitioning[block_idx_v3].push(index);
  27746. }
  27747. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  27748. options.facetPartitioning[block_idx_o].push(index);
  27749. }
  27750. }
  27751. // compute the normals anyway
  27752. normals[v1x] += faceNormalx; // accumulate all the normals per face
  27753. normals[v1y] += faceNormaly;
  27754. normals[v1z] += faceNormalz;
  27755. normals[v2x] += faceNormalx;
  27756. normals[v2y] += faceNormaly;
  27757. normals[v2z] += faceNormalz;
  27758. normals[v3x] += faceNormalx;
  27759. normals[v3y] += faceNormaly;
  27760. normals[v3z] += faceNormalz;
  27761. }
  27762. // last normalization of each normal
  27763. for (index = 0; index < normals.length / 3; index++) {
  27764. faceNormalx = normals[index * 3];
  27765. faceNormaly = normals[index * 3 + 1];
  27766. faceNormalz = normals[index * 3 + 2];
  27767. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  27768. length = (length === 0) ? 1.0 : length;
  27769. faceNormalx /= length;
  27770. faceNormaly /= length;
  27771. faceNormalz /= length;
  27772. normals[index * 3] = faceNormalx;
  27773. normals[index * 3 + 1] = faceNormaly;
  27774. normals[index * 3 + 2] = faceNormalz;
  27775. }
  27776. };
  27777. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  27778. var li = indices.length;
  27779. var ln = normals.length;
  27780. var i;
  27781. var n;
  27782. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27783. switch (sideOrientation) {
  27784. case BABYLON.Mesh.FRONTSIDE:
  27785. // nothing changed
  27786. break;
  27787. case BABYLON.Mesh.BACKSIDE:
  27788. var tmp;
  27789. // indices
  27790. for (i = 0; i < li; i += 3) {
  27791. tmp = indices[i];
  27792. indices[i] = indices[i + 2];
  27793. indices[i + 2] = tmp;
  27794. }
  27795. // normals
  27796. for (n = 0; n < ln; n++) {
  27797. normals[n] = -normals[n];
  27798. }
  27799. break;
  27800. case BABYLON.Mesh.DOUBLESIDE:
  27801. // positions
  27802. var lp = positions.length;
  27803. var l = lp / 3;
  27804. for (var p = 0; p < lp; p++) {
  27805. positions[lp + p] = positions[p];
  27806. }
  27807. // indices
  27808. for (i = 0; i < li; i += 3) {
  27809. indices[i + li] = indices[i + 2] + l;
  27810. indices[i + 1 + li] = indices[i + 1] + l;
  27811. indices[i + 2 + li] = indices[i] + l;
  27812. }
  27813. // normals
  27814. for (n = 0; n < ln; n++) {
  27815. normals[ln + n] = -normals[n];
  27816. }
  27817. // uvs
  27818. var lu = uvs.length;
  27819. var u = 0;
  27820. for (u = 0; u < lu; u++) {
  27821. uvs[u + lu] = uvs[u];
  27822. }
  27823. var frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  27824. var backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  27825. u = 0;
  27826. for (i = 0; i < lu / 2; i++) {
  27827. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  27828. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  27829. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  27830. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  27831. u += 2;
  27832. }
  27833. break;
  27834. }
  27835. };
  27836. /**
  27837. * Creates a new VertexData from the imported parameters.
  27838. */
  27839. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  27840. var vertexData = new VertexData();
  27841. // positions
  27842. var positions = parsedVertexData.positions;
  27843. if (positions) {
  27844. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  27845. }
  27846. // normals
  27847. var normals = parsedVertexData.normals;
  27848. if (normals) {
  27849. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  27850. }
  27851. // tangents
  27852. var tangents = parsedVertexData.tangents;
  27853. if (tangents) {
  27854. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  27855. }
  27856. // uvs
  27857. var uvs = parsedVertexData.uvs;
  27858. if (uvs) {
  27859. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  27860. }
  27861. // uv2s
  27862. var uv2s = parsedVertexData.uv2s;
  27863. if (uv2s) {
  27864. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  27865. }
  27866. // uv3s
  27867. var uv3s = parsedVertexData.uv3s;
  27868. if (uv3s) {
  27869. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  27870. }
  27871. // uv4s
  27872. var uv4s = parsedVertexData.uv4s;
  27873. if (uv4s) {
  27874. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  27875. }
  27876. // uv5s
  27877. var uv5s = parsedVertexData.uv5s;
  27878. if (uv5s) {
  27879. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  27880. }
  27881. // uv6s
  27882. var uv6s = parsedVertexData.uv6s;
  27883. if (uv6s) {
  27884. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  27885. }
  27886. // colors
  27887. var colors = parsedVertexData.colors;
  27888. if (colors) {
  27889. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  27890. }
  27891. // matricesIndices
  27892. var matricesIndices = parsedVertexData.matricesIndices;
  27893. if (matricesIndices) {
  27894. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  27895. }
  27896. // matricesWeights
  27897. var matricesWeights = parsedVertexData.matricesWeights;
  27898. if (matricesWeights) {
  27899. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  27900. }
  27901. // indices
  27902. var indices = parsedVertexData.indices;
  27903. if (indices) {
  27904. vertexData.indices = indices;
  27905. }
  27906. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  27907. };
  27908. return VertexData;
  27909. }());
  27910. BABYLON.VertexData = VertexData;
  27911. })(BABYLON || (BABYLON = {}));
  27912. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  27913. var BABYLON;
  27914. (function (BABYLON) {
  27915. var Geometry = (function () {
  27916. function Geometry(id, scene, vertexData, updatable, mesh) {
  27917. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27918. this._totalVertices = 0;
  27919. this._isDisposed = false;
  27920. this.id = id;
  27921. this._engine = scene.getEngine();
  27922. this._meshes = [];
  27923. this._scene = scene;
  27924. //Init vertex buffer cache
  27925. this._vertexBuffers = {};
  27926. this._indices = [];
  27927. this._updatable = updatable;
  27928. // vertexData
  27929. if (vertexData) {
  27930. this.setAllVerticesData(vertexData, updatable);
  27931. }
  27932. else {
  27933. this._totalVertices = 0;
  27934. this._indices = [];
  27935. }
  27936. if (this._engine.getCaps().vertexArrayObject) {
  27937. this._vertexArrayObjects = {};
  27938. }
  27939. // applyToMesh
  27940. if (mesh) {
  27941. if (mesh.getClassName() === "LinesMesh") {
  27942. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  27943. this.updateExtend();
  27944. }
  27945. this.applyToMesh(mesh);
  27946. mesh.computeWorldMatrix(true);
  27947. }
  27948. }
  27949. Object.defineProperty(Geometry.prototype, "boundingBias", {
  27950. /**
  27951. * 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
  27952. * @returns The Bias Vector
  27953. */
  27954. get: function () {
  27955. return this._boundingBias;
  27956. },
  27957. set: function (value) {
  27958. if (this._boundingBias && this._boundingBias.equals(value)) {
  27959. return;
  27960. }
  27961. this._boundingBias = value.clone();
  27962. this.updateBoundingInfo(true, null);
  27963. },
  27964. enumerable: true,
  27965. configurable: true
  27966. });
  27967. Object.defineProperty(Geometry.prototype, "extend", {
  27968. get: function () {
  27969. return this._extend;
  27970. },
  27971. enumerable: true,
  27972. configurable: true
  27973. });
  27974. Geometry.prototype.getScene = function () {
  27975. return this._scene;
  27976. };
  27977. Geometry.prototype.getEngine = function () {
  27978. return this._engine;
  27979. };
  27980. Geometry.prototype.isReady = function () {
  27981. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  27982. };
  27983. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  27984. get: function () {
  27985. for (var index = 0; index < this._meshes.length; index++) {
  27986. if (!this._meshes[index].doNotSerialize) {
  27987. return false;
  27988. }
  27989. }
  27990. return true;
  27991. },
  27992. enumerable: true,
  27993. configurable: true
  27994. });
  27995. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  27996. vertexData.applyToGeometry(this, updatable);
  27997. this.notifyUpdate();
  27998. };
  27999. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28000. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  28001. this.setVerticesBuffer(buffer);
  28002. };
  28003. Geometry.prototype.removeVerticesData = function (kind) {
  28004. if (this._vertexBuffers[kind]) {
  28005. this._vertexBuffers[kind].dispose();
  28006. delete this._vertexBuffers[kind];
  28007. }
  28008. };
  28009. Geometry.prototype.setVerticesBuffer = function (buffer) {
  28010. var kind = buffer.getKind();
  28011. if (this._vertexBuffers[kind]) {
  28012. this._vertexBuffers[kind].dispose();
  28013. }
  28014. this._vertexBuffers[kind] = buffer;
  28015. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28016. var data = buffer.getData();
  28017. var stride = buffer.getStrideSize();
  28018. this._totalVertices = data.length / stride;
  28019. this.updateExtend(data, stride);
  28020. this._resetPointsArrayCache();
  28021. var meshes = this._meshes;
  28022. var numOfMeshes = meshes.length;
  28023. for (var index = 0; index < numOfMeshes; index++) {
  28024. var mesh = meshes[index];
  28025. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28026. mesh._createGlobalSubMesh(false);
  28027. mesh.computeWorldMatrix(true);
  28028. }
  28029. }
  28030. this.notifyUpdate(kind);
  28031. if (this._vertexArrayObjects) {
  28032. this._disposeVertexArrayObjects();
  28033. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  28034. }
  28035. };
  28036. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  28037. var vertexBuffer = this.getVertexBuffer(kind);
  28038. if (!vertexBuffer) {
  28039. return;
  28040. }
  28041. vertexBuffer.updateDirectly(data, offset);
  28042. this.notifyUpdate(kind);
  28043. };
  28044. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  28045. var vertexBuffer = this.getVertexBuffer(kind);
  28046. if (!vertexBuffer) {
  28047. return;
  28048. }
  28049. vertexBuffer.update(data);
  28050. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28051. var stride = vertexBuffer.getStrideSize();
  28052. this._totalVertices = data.length / stride;
  28053. this.updateBoundingInfo(updateExtends, data);
  28054. }
  28055. this.notifyUpdate(kind);
  28056. };
  28057. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  28058. if (updateExtends) {
  28059. this.updateExtend(data);
  28060. }
  28061. var meshes = this._meshes;
  28062. var numOfMeshes = meshes.length;
  28063. this._resetPointsArrayCache();
  28064. for (var index = 0; index < numOfMeshes; index++) {
  28065. var mesh = meshes[index];
  28066. if (updateExtends) {
  28067. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28068. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  28069. var subMesh = mesh.subMeshes[subIndex];
  28070. subMesh.refreshBoundingInfo();
  28071. }
  28072. }
  28073. }
  28074. };
  28075. Geometry.prototype._bind = function (effect, indexToBind) {
  28076. if (indexToBind === void 0) { indexToBind = undefined; }
  28077. if (indexToBind === undefined) {
  28078. indexToBind = this._indexBuffer;
  28079. }
  28080. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  28081. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  28082. return;
  28083. }
  28084. // Using VAO
  28085. if (!this._vertexArrayObjects[effect.key]) {
  28086. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  28087. }
  28088. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  28089. };
  28090. Geometry.prototype.getTotalVertices = function () {
  28091. if (!this.isReady()) {
  28092. return 0;
  28093. }
  28094. return this._totalVertices;
  28095. };
  28096. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  28097. var vertexBuffer = this.getVertexBuffer(kind);
  28098. if (!vertexBuffer) {
  28099. return null;
  28100. }
  28101. var orig = vertexBuffer.getData();
  28102. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  28103. return orig;
  28104. }
  28105. else {
  28106. var len = orig.length;
  28107. var copy = [];
  28108. for (var i = 0; i < len; i++) {
  28109. copy.push(orig[i]);
  28110. }
  28111. return copy;
  28112. }
  28113. };
  28114. Geometry.prototype.getVertexBuffer = function (kind) {
  28115. if (!this.isReady()) {
  28116. return null;
  28117. }
  28118. return this._vertexBuffers[kind];
  28119. };
  28120. Geometry.prototype.getVertexBuffers = function () {
  28121. if (!this.isReady()) {
  28122. return null;
  28123. }
  28124. return this._vertexBuffers;
  28125. };
  28126. Geometry.prototype.isVerticesDataPresent = function (kind) {
  28127. if (!this._vertexBuffers) {
  28128. if (this._delayInfo) {
  28129. return this._delayInfo.indexOf(kind) !== -1;
  28130. }
  28131. return false;
  28132. }
  28133. return this._vertexBuffers[kind] !== undefined;
  28134. };
  28135. Geometry.prototype.getVerticesDataKinds = function () {
  28136. var result = [];
  28137. var kind;
  28138. if (!this._vertexBuffers && this._delayInfo) {
  28139. for (kind in this._delayInfo) {
  28140. result.push(kind);
  28141. }
  28142. }
  28143. else {
  28144. for (kind in this._vertexBuffers) {
  28145. result.push(kind);
  28146. }
  28147. }
  28148. return result;
  28149. };
  28150. Geometry.prototype.setIndices = function (indices, totalVertices) {
  28151. if (this._indexBuffer) {
  28152. this._engine._releaseBuffer(this._indexBuffer);
  28153. }
  28154. this._disposeVertexArrayObjects();
  28155. this._indices = indices;
  28156. if (this._meshes.length !== 0 && this._indices) {
  28157. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28158. }
  28159. if (totalVertices !== undefined) {
  28160. this._totalVertices = totalVertices;
  28161. }
  28162. var meshes = this._meshes;
  28163. var numOfMeshes = meshes.length;
  28164. for (var index = 0; index < numOfMeshes; index++) {
  28165. meshes[index]._createGlobalSubMesh(true);
  28166. }
  28167. this.notifyUpdate();
  28168. };
  28169. Geometry.prototype.getTotalIndices = function () {
  28170. if (!this.isReady()) {
  28171. return 0;
  28172. }
  28173. return this._indices.length;
  28174. };
  28175. Geometry.prototype.getIndices = function (copyWhenShared) {
  28176. if (!this.isReady()) {
  28177. return null;
  28178. }
  28179. var orig = this._indices;
  28180. if (!copyWhenShared || this._meshes.length === 1) {
  28181. return orig;
  28182. }
  28183. else {
  28184. var len = orig.length;
  28185. var copy = [];
  28186. for (var i = 0; i < len; i++) {
  28187. copy.push(orig[i]);
  28188. }
  28189. return copy;
  28190. }
  28191. };
  28192. Geometry.prototype.getIndexBuffer = function () {
  28193. if (!this.isReady()) {
  28194. return null;
  28195. }
  28196. return this._indexBuffer;
  28197. };
  28198. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  28199. if (!effect || !this._vertexArrayObjects) {
  28200. return;
  28201. }
  28202. if (this._vertexArrayObjects[effect.key]) {
  28203. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  28204. delete this._vertexArrayObjects[effect.key];
  28205. }
  28206. };
  28207. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  28208. var meshes = this._meshes;
  28209. var index = meshes.indexOf(mesh);
  28210. if (index === -1) {
  28211. return;
  28212. }
  28213. meshes.splice(index, 1);
  28214. mesh._geometry = null;
  28215. if (meshes.length === 0 && shouldDispose) {
  28216. this.dispose();
  28217. }
  28218. };
  28219. Geometry.prototype.applyToMesh = function (mesh) {
  28220. if (mesh._geometry === this) {
  28221. return;
  28222. }
  28223. var previousGeometry = mesh._geometry;
  28224. if (previousGeometry) {
  28225. previousGeometry.releaseForMesh(mesh);
  28226. }
  28227. var meshes = this._meshes;
  28228. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  28229. mesh._geometry = this;
  28230. this._scene.pushGeometry(this);
  28231. meshes.push(mesh);
  28232. if (this.isReady()) {
  28233. this._applyToMesh(mesh);
  28234. }
  28235. else {
  28236. mesh._boundingInfo = this._boundingInfo;
  28237. }
  28238. };
  28239. Geometry.prototype.updateExtend = function (data, stride) {
  28240. if (data === void 0) { data = null; }
  28241. if (!data) {
  28242. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  28243. }
  28244. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  28245. };
  28246. Geometry.prototype._applyToMesh = function (mesh) {
  28247. var numOfMeshes = this._meshes.length;
  28248. // vertexBuffers
  28249. for (var kind in this._vertexBuffers) {
  28250. if (numOfMeshes === 1) {
  28251. this._vertexBuffers[kind].create();
  28252. }
  28253. var buffer = this._vertexBuffers[kind].getBuffer();
  28254. if (buffer)
  28255. buffer.references = numOfMeshes;
  28256. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28257. if (!this._extend) {
  28258. this.updateExtend(this._vertexBuffers[kind].getData());
  28259. }
  28260. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28261. mesh._createGlobalSubMesh(false);
  28262. //bounding info was just created again, world matrix should be applied again.
  28263. mesh._updateBoundingInfo();
  28264. }
  28265. }
  28266. // indexBuffer
  28267. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  28268. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28269. }
  28270. if (this._indexBuffer) {
  28271. this._indexBuffer.references = numOfMeshes;
  28272. }
  28273. };
  28274. Geometry.prototype.notifyUpdate = function (kind) {
  28275. if (this.onGeometryUpdated) {
  28276. this.onGeometryUpdated(this, kind);
  28277. }
  28278. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  28279. var mesh = _a[_i];
  28280. mesh._markSubMeshesAsAttributesDirty();
  28281. }
  28282. };
  28283. Geometry.prototype.load = function (scene, onLoaded) {
  28284. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28285. return;
  28286. }
  28287. if (this.isReady()) {
  28288. if (onLoaded) {
  28289. onLoaded();
  28290. }
  28291. return;
  28292. }
  28293. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28294. this._queueLoad(scene, onLoaded);
  28295. };
  28296. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  28297. var _this = this;
  28298. scene._addPendingData(this);
  28299. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28300. _this._delayLoadingFunction(JSON.parse(data), _this);
  28301. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28302. _this._delayInfo = [];
  28303. scene._removePendingData(_this);
  28304. var meshes = _this._meshes;
  28305. var numOfMeshes = meshes.length;
  28306. for (var index = 0; index < numOfMeshes; index++) {
  28307. _this._applyToMesh(meshes[index]);
  28308. }
  28309. if (onLoaded) {
  28310. onLoaded();
  28311. }
  28312. }, function () { }, scene.database);
  28313. };
  28314. /**
  28315. * Invert the geometry to move from a right handed system to a left handed one.
  28316. */
  28317. Geometry.prototype.toLeftHanded = function () {
  28318. // Flip faces
  28319. var tIndices = this.getIndices(false);
  28320. if (tIndices != null && tIndices.length > 0) {
  28321. for (var i = 0; i < tIndices.length; i += 3) {
  28322. var tTemp = tIndices[i + 0];
  28323. tIndices[i + 0] = tIndices[i + 2];
  28324. tIndices[i + 2] = tTemp;
  28325. }
  28326. this.setIndices(tIndices);
  28327. }
  28328. // Negate position.z
  28329. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  28330. if (tPositions != null && tPositions.length > 0) {
  28331. for (var i = 0; i < tPositions.length; i += 3) {
  28332. tPositions[i + 2] = -tPositions[i + 2];
  28333. }
  28334. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  28335. }
  28336. // Negate normal.z
  28337. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  28338. if (tNormals != null && tNormals.length > 0) {
  28339. for (var i = 0; i < tNormals.length; i += 3) {
  28340. tNormals[i + 2] = -tNormals[i + 2];
  28341. }
  28342. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  28343. }
  28344. };
  28345. // Cache
  28346. Geometry.prototype._resetPointsArrayCache = function () {
  28347. this._positions = null;
  28348. };
  28349. Geometry.prototype._generatePointsArray = function () {
  28350. if (this._positions)
  28351. return true;
  28352. this._positions = [];
  28353. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28354. if (!data) {
  28355. return false;
  28356. }
  28357. for (var index = 0; index < data.length; index += 3) {
  28358. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  28359. }
  28360. return true;
  28361. };
  28362. Geometry.prototype.isDisposed = function () {
  28363. return this._isDisposed;
  28364. };
  28365. Geometry.prototype._disposeVertexArrayObjects = function () {
  28366. if (this._vertexArrayObjects) {
  28367. for (var kind in this._vertexArrayObjects) {
  28368. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  28369. }
  28370. this._vertexArrayObjects = {};
  28371. }
  28372. };
  28373. Geometry.prototype.dispose = function () {
  28374. var meshes = this._meshes;
  28375. var numOfMeshes = meshes.length;
  28376. var index;
  28377. for (index = 0; index < numOfMeshes; index++) {
  28378. this.releaseForMesh(meshes[index]);
  28379. }
  28380. this._meshes = [];
  28381. this._disposeVertexArrayObjects();
  28382. for (var kind in this._vertexBuffers) {
  28383. this._vertexBuffers[kind].dispose();
  28384. }
  28385. this._vertexBuffers = {};
  28386. this._totalVertices = 0;
  28387. if (this._indexBuffer) {
  28388. this._engine._releaseBuffer(this._indexBuffer);
  28389. }
  28390. this._indexBuffer = null;
  28391. this._indices = [];
  28392. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28393. this.delayLoadingFile = null;
  28394. this._delayLoadingFunction = null;
  28395. this._delayInfo = [];
  28396. this._boundingInfo = null;
  28397. this._scene.removeGeometry(this);
  28398. this._isDisposed = true;
  28399. };
  28400. Geometry.prototype.copy = function (id) {
  28401. var vertexData = new BABYLON.VertexData();
  28402. vertexData.indices = [];
  28403. var indices = this.getIndices();
  28404. for (var index = 0; index < indices.length; index++) {
  28405. vertexData.indices.push(indices[index]);
  28406. }
  28407. var updatable = false;
  28408. var stopChecking = false;
  28409. var kind;
  28410. for (kind in this._vertexBuffers) {
  28411. // using slice() to make a copy of the array and not just reference it
  28412. var data = this.getVerticesData(kind);
  28413. if (data instanceof Float32Array) {
  28414. vertexData.set(new Float32Array(data), kind);
  28415. }
  28416. else {
  28417. vertexData.set(data.slice(0), kind);
  28418. }
  28419. if (!stopChecking) {
  28420. updatable = this.getVertexBuffer(kind).isUpdatable();
  28421. stopChecking = !updatable;
  28422. }
  28423. }
  28424. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  28425. geometry.delayLoadState = this.delayLoadState;
  28426. geometry.delayLoadingFile = this.delayLoadingFile;
  28427. geometry._delayLoadingFunction = this._delayLoadingFunction;
  28428. for (kind in this._delayInfo) {
  28429. geometry._delayInfo = geometry._delayInfo || [];
  28430. geometry._delayInfo.push(kind);
  28431. }
  28432. // Bounding info
  28433. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28434. return geometry;
  28435. };
  28436. Geometry.prototype.serialize = function () {
  28437. var serializationObject = {};
  28438. serializationObject.id = this.id;
  28439. serializationObject.updatable = this._updatable;
  28440. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  28441. serializationObject.tags = BABYLON.Tags.GetTags(this);
  28442. }
  28443. return serializationObject;
  28444. };
  28445. Geometry.prototype.toNumberArray = function (origin) {
  28446. if (Array.isArray(origin)) {
  28447. return origin;
  28448. }
  28449. else {
  28450. return Array.prototype.slice.call(origin);
  28451. }
  28452. };
  28453. Geometry.prototype.serializeVerticeData = function () {
  28454. var serializationObject = this.serialize();
  28455. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28456. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  28457. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  28458. serializationObject.positions._updatable = true;
  28459. }
  28460. }
  28461. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28462. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  28463. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  28464. serializationObject.normals._updatable = true;
  28465. }
  28466. }
  28467. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28468. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  28469. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  28470. serializationObject.uvs._updatable = true;
  28471. }
  28472. }
  28473. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28474. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  28475. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  28476. serializationObject.uv2s._updatable = true;
  28477. }
  28478. }
  28479. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  28480. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  28481. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  28482. serializationObject.uv3s._updatable = true;
  28483. }
  28484. }
  28485. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  28486. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  28487. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  28488. serializationObject.uv4s._updatable = true;
  28489. }
  28490. }
  28491. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  28492. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  28493. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  28494. serializationObject.uv5s._updatable = true;
  28495. }
  28496. }
  28497. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  28498. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  28499. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  28500. serializationObject.uv6s._updatable = true;
  28501. }
  28502. }
  28503. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28504. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  28505. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  28506. serializationObject.colors._updatable = true;
  28507. }
  28508. }
  28509. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28510. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  28511. serializationObject.matricesIndices._isExpanded = true;
  28512. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  28513. serializationObject.matricesIndices._updatable = true;
  28514. }
  28515. }
  28516. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28517. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  28518. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  28519. serializationObject.matricesWeights._updatable = true;
  28520. }
  28521. }
  28522. serializationObject.indices = this.toNumberArray(this.getIndices());
  28523. return serializationObject;
  28524. };
  28525. // Statics
  28526. Geometry.ExtractFromMesh = function (mesh, id) {
  28527. var geometry = mesh._geometry;
  28528. if (!geometry) {
  28529. return null;
  28530. }
  28531. return geometry.copy(id);
  28532. };
  28533. /**
  28534. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  28535. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  28536. * Be aware Math.random() could cause collisions, but:
  28537. * "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"
  28538. */
  28539. Geometry.RandomId = function () {
  28540. return BABYLON.Tools.RandomId();
  28541. };
  28542. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  28543. var scene = mesh.getScene();
  28544. // Geometry
  28545. var geometryId = parsedGeometry.geometryId;
  28546. if (geometryId) {
  28547. var geometry = scene.getGeometryByID(geometryId);
  28548. if (geometry) {
  28549. geometry.applyToMesh(mesh);
  28550. }
  28551. }
  28552. else if (parsedGeometry instanceof ArrayBuffer) {
  28553. var binaryInfo = mesh._binaryInfo;
  28554. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  28555. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  28556. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  28557. }
  28558. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  28559. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  28560. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  28561. }
  28562. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  28563. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  28564. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  28565. }
  28566. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  28567. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  28568. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  28569. }
  28570. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  28571. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  28572. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  28573. }
  28574. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  28575. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  28576. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  28577. }
  28578. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  28579. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  28580. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  28581. }
  28582. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  28583. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  28584. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  28585. }
  28586. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  28587. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  28588. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  28589. }
  28590. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  28591. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  28592. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  28593. }
  28594. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  28595. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  28596. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  28597. }
  28598. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  28599. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  28600. mesh.setIndices(indicesData);
  28601. }
  28602. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  28603. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  28604. mesh.subMeshes = [];
  28605. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  28606. var materialIndex = subMeshesData[(i * 5) + 0];
  28607. var verticesStart = subMeshesData[(i * 5) + 1];
  28608. var verticesCount = subMeshesData[(i * 5) + 2];
  28609. var indexStart = subMeshesData[(i * 5) + 3];
  28610. var indexCount = subMeshesData[(i * 5) + 4];
  28611. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  28612. }
  28613. }
  28614. }
  28615. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  28616. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  28617. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  28618. if (parsedGeometry.uvs) {
  28619. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  28620. }
  28621. if (parsedGeometry.uvs2) {
  28622. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  28623. }
  28624. if (parsedGeometry.uvs3) {
  28625. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  28626. }
  28627. if (parsedGeometry.uvs4) {
  28628. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  28629. }
  28630. if (parsedGeometry.uvs5) {
  28631. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  28632. }
  28633. if (parsedGeometry.uvs6) {
  28634. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  28635. }
  28636. if (parsedGeometry.colors) {
  28637. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  28638. }
  28639. if (parsedGeometry.matricesIndices) {
  28640. if (!parsedGeometry.matricesIndices._isExpanded) {
  28641. var floatIndices = [];
  28642. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  28643. var matricesIndex = parsedGeometry.matricesIndices[i];
  28644. floatIndices.push(matricesIndex & 0x000000FF);
  28645. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  28646. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  28647. floatIndices.push(matricesIndex >> 24);
  28648. }
  28649. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  28650. }
  28651. else {
  28652. delete parsedGeometry.matricesIndices._isExpanded;
  28653. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  28654. }
  28655. }
  28656. if (parsedGeometry.matricesIndicesExtra) {
  28657. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  28658. var floatIndices = [];
  28659. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  28660. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  28661. floatIndices.push(matricesIndex & 0x000000FF);
  28662. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  28663. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  28664. floatIndices.push(matricesIndex >> 24);
  28665. }
  28666. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  28667. }
  28668. else {
  28669. delete parsedGeometry.matricesIndices._isExpanded;
  28670. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  28671. }
  28672. }
  28673. if (parsedGeometry.matricesWeights) {
  28674. Geometry._CleanMatricesWeights(parsedGeometry.matricesWeights, parsedGeometry.numBoneInfluencers);
  28675. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  28676. }
  28677. if (parsedGeometry.matricesWeightsExtra) {
  28678. Geometry._CleanMatricesWeights(parsedGeometry.matricesWeightsExtra, parsedGeometry.numBoneInfluencers);
  28679. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  28680. }
  28681. mesh.setIndices(parsedGeometry.indices);
  28682. }
  28683. // SubMeshes
  28684. if (parsedGeometry.subMeshes) {
  28685. mesh.subMeshes = [];
  28686. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  28687. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  28688. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  28689. }
  28690. }
  28691. // Flat shading
  28692. if (mesh._shouldGenerateFlatShading) {
  28693. mesh.convertToFlatShadedMesh();
  28694. delete mesh._shouldGenerateFlatShading;
  28695. }
  28696. // Update
  28697. mesh.computeWorldMatrix(true);
  28698. // Octree
  28699. if (scene['_selectionOctree']) {
  28700. scene['_selectionOctree'].addMesh(mesh);
  28701. }
  28702. };
  28703. Geometry._CleanMatricesWeights = function (matricesWeights, influencers) {
  28704. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  28705. return;
  28706. }
  28707. var size = matricesWeights.length;
  28708. for (var i = 0; i < size; i += influencers) {
  28709. var weight = 0;
  28710. var biggerIndex = i;
  28711. var biggerWeight = 0;
  28712. for (var j = 0; j < influencers - 1; j++) {
  28713. weight += matricesWeights[i + j];
  28714. if (matricesWeights[i + j] > biggerWeight) {
  28715. biggerWeight = matricesWeights[i + j];
  28716. biggerIndex = i + j;
  28717. }
  28718. }
  28719. matricesWeights[biggerIndex] += Math.max(0, 1.0 - weight);
  28720. }
  28721. };
  28722. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  28723. if (scene.getGeometryByID(parsedVertexData.id)) {
  28724. return null; // null since geometry could be something else than a box...
  28725. }
  28726. var geometry = new Geometry(parsedVertexData.id, scene, null, parsedVertexData.updatable);
  28727. if (BABYLON.Tags) {
  28728. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  28729. }
  28730. if (parsedVertexData.delayLoadingFile) {
  28731. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  28732. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  28733. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  28734. geometry._delayInfo = [];
  28735. if (parsedVertexData.hasUVs) {
  28736. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  28737. }
  28738. if (parsedVertexData.hasUVs2) {
  28739. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  28740. }
  28741. if (parsedVertexData.hasUVs3) {
  28742. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  28743. }
  28744. if (parsedVertexData.hasUVs4) {
  28745. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  28746. }
  28747. if (parsedVertexData.hasUVs5) {
  28748. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  28749. }
  28750. if (parsedVertexData.hasUVs6) {
  28751. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  28752. }
  28753. if (parsedVertexData.hasColors) {
  28754. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  28755. }
  28756. if (parsedVertexData.hasMatricesIndices) {
  28757. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28758. }
  28759. if (parsedVertexData.hasMatricesWeights) {
  28760. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28761. }
  28762. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  28763. }
  28764. else {
  28765. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  28766. }
  28767. scene.pushGeometry(geometry, true);
  28768. return geometry;
  28769. };
  28770. return Geometry;
  28771. }());
  28772. BABYLON.Geometry = Geometry;
  28773. /////// Primitives //////////////////////////////////////////////
  28774. (function (Geometry) {
  28775. var Primitives;
  28776. (function (Primitives) {
  28777. /// Abstract class
  28778. var _Primitive = (function (_super) {
  28779. __extends(_Primitive, _super);
  28780. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  28781. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  28782. _this._canBeRegenerated = _canBeRegenerated;
  28783. _this._beingRegenerated = true;
  28784. _this.regenerate();
  28785. _this._beingRegenerated = false;
  28786. return _this;
  28787. }
  28788. _Primitive.prototype.canBeRegenerated = function () {
  28789. return this._canBeRegenerated;
  28790. };
  28791. _Primitive.prototype.regenerate = function () {
  28792. if (!this._canBeRegenerated) {
  28793. return;
  28794. }
  28795. this._beingRegenerated = true;
  28796. this.setAllVerticesData(this._regenerateVertexData(), false);
  28797. this._beingRegenerated = false;
  28798. };
  28799. _Primitive.prototype.asNewGeometry = function (id) {
  28800. return _super.prototype.copy.call(this, id);
  28801. };
  28802. // overrides
  28803. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  28804. if (!this._beingRegenerated) {
  28805. return;
  28806. }
  28807. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  28808. };
  28809. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  28810. if (!this._beingRegenerated) {
  28811. return;
  28812. }
  28813. _super.prototype.setVerticesData.call(this, kind, data, false);
  28814. };
  28815. // to override
  28816. // protected
  28817. _Primitive.prototype._regenerateVertexData = function () {
  28818. throw new Error("Abstract method");
  28819. };
  28820. _Primitive.prototype.copy = function (id) {
  28821. throw new Error("Must be overriden in sub-classes.");
  28822. };
  28823. _Primitive.prototype.serialize = function () {
  28824. var serializationObject = _super.prototype.serialize.call(this);
  28825. serializationObject.canBeRegenerated = this.canBeRegenerated();
  28826. return serializationObject;
  28827. };
  28828. return _Primitive;
  28829. }(Geometry));
  28830. Primitives._Primitive = _Primitive;
  28831. var Ribbon = (function (_super) {
  28832. __extends(Ribbon, _super);
  28833. // Members
  28834. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  28835. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28836. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28837. _this.pathArray = pathArray;
  28838. _this.closeArray = closeArray;
  28839. _this.closePath = closePath;
  28840. _this.offset = offset;
  28841. _this.side = side;
  28842. return _this;
  28843. }
  28844. Ribbon.prototype._regenerateVertexData = function () {
  28845. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  28846. };
  28847. Ribbon.prototype.copy = function (id) {
  28848. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  28849. };
  28850. return Ribbon;
  28851. }(_Primitive));
  28852. Primitives.Ribbon = Ribbon;
  28853. var Box = (function (_super) {
  28854. __extends(Box, _super);
  28855. // Members
  28856. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  28857. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28858. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28859. _this.size = size;
  28860. _this.side = side;
  28861. return _this;
  28862. }
  28863. Box.prototype._regenerateVertexData = function () {
  28864. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  28865. };
  28866. Box.prototype.copy = function (id) {
  28867. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28868. };
  28869. Box.prototype.serialize = function () {
  28870. var serializationObject = _super.prototype.serialize.call(this);
  28871. serializationObject.size = this.size;
  28872. return serializationObject;
  28873. };
  28874. Box.Parse = function (parsedBox, scene) {
  28875. if (scene.getGeometryByID(parsedBox.id)) {
  28876. return null; // null since geometry could be something else than a box...
  28877. }
  28878. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  28879. if (BABYLON.Tags) {
  28880. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  28881. }
  28882. scene.pushGeometry(box, true);
  28883. return box;
  28884. };
  28885. return Box;
  28886. }(_Primitive));
  28887. Primitives.Box = Box;
  28888. var Sphere = (function (_super) {
  28889. __extends(Sphere, _super);
  28890. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  28891. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28892. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28893. _this.segments = segments;
  28894. _this.diameter = diameter;
  28895. _this.side = side;
  28896. return _this;
  28897. }
  28898. Sphere.prototype._regenerateVertexData = function () {
  28899. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  28900. };
  28901. Sphere.prototype.copy = function (id) {
  28902. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  28903. };
  28904. Sphere.prototype.serialize = function () {
  28905. var serializationObject = _super.prototype.serialize.call(this);
  28906. serializationObject.segments = this.segments;
  28907. serializationObject.diameter = this.diameter;
  28908. return serializationObject;
  28909. };
  28910. Sphere.Parse = function (parsedSphere, scene) {
  28911. if (scene.getGeometryByID(parsedSphere.id)) {
  28912. return null; // null since geometry could be something else than a sphere...
  28913. }
  28914. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  28915. if (BABYLON.Tags) {
  28916. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  28917. }
  28918. scene.pushGeometry(sphere, true);
  28919. return sphere;
  28920. };
  28921. return Sphere;
  28922. }(_Primitive));
  28923. Primitives.Sphere = Sphere;
  28924. var Disc = (function (_super) {
  28925. __extends(Disc, _super);
  28926. // Members
  28927. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  28928. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28929. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28930. _this.radius = radius;
  28931. _this.tessellation = tessellation;
  28932. _this.side = side;
  28933. return _this;
  28934. }
  28935. Disc.prototype._regenerateVertexData = function () {
  28936. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  28937. };
  28938. Disc.prototype.copy = function (id) {
  28939. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  28940. };
  28941. return Disc;
  28942. }(_Primitive));
  28943. Primitives.Disc = Disc;
  28944. var Cylinder = (function (_super) {
  28945. __extends(Cylinder, _super);
  28946. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  28947. if (subdivisions === void 0) { subdivisions = 1; }
  28948. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28949. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28950. _this.height = height;
  28951. _this.diameterTop = diameterTop;
  28952. _this.diameterBottom = diameterBottom;
  28953. _this.tessellation = tessellation;
  28954. _this.subdivisions = subdivisions;
  28955. _this.side = side;
  28956. return _this;
  28957. }
  28958. Cylinder.prototype._regenerateVertexData = function () {
  28959. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  28960. };
  28961. Cylinder.prototype.copy = function (id) {
  28962. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  28963. };
  28964. Cylinder.prototype.serialize = function () {
  28965. var serializationObject = _super.prototype.serialize.call(this);
  28966. serializationObject.height = this.height;
  28967. serializationObject.diameterTop = this.diameterTop;
  28968. serializationObject.diameterBottom = this.diameterBottom;
  28969. serializationObject.tessellation = this.tessellation;
  28970. return serializationObject;
  28971. };
  28972. Cylinder.Parse = function (parsedCylinder, scene) {
  28973. if (scene.getGeometryByID(parsedCylinder.id)) {
  28974. return null; // null since geometry could be something else than a cylinder...
  28975. }
  28976. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  28977. if (BABYLON.Tags) {
  28978. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  28979. }
  28980. scene.pushGeometry(cylinder, true);
  28981. return cylinder;
  28982. };
  28983. return Cylinder;
  28984. }(_Primitive));
  28985. Primitives.Cylinder = Cylinder;
  28986. var Torus = (function (_super) {
  28987. __extends(Torus, _super);
  28988. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  28989. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28990. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28991. _this.diameter = diameter;
  28992. _this.thickness = thickness;
  28993. _this.tessellation = tessellation;
  28994. _this.side = side;
  28995. return _this;
  28996. }
  28997. Torus.prototype._regenerateVertexData = function () {
  28998. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  28999. };
  29000. Torus.prototype.copy = function (id) {
  29001. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  29002. };
  29003. Torus.prototype.serialize = function () {
  29004. var serializationObject = _super.prototype.serialize.call(this);
  29005. serializationObject.diameter = this.diameter;
  29006. serializationObject.thickness = this.thickness;
  29007. serializationObject.tessellation = this.tessellation;
  29008. return serializationObject;
  29009. };
  29010. Torus.Parse = function (parsedTorus, scene) {
  29011. if (scene.getGeometryByID(parsedTorus.id)) {
  29012. return null; // null since geometry could be something else than a torus...
  29013. }
  29014. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  29015. if (BABYLON.Tags) {
  29016. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  29017. }
  29018. scene.pushGeometry(torus, true);
  29019. return torus;
  29020. };
  29021. return Torus;
  29022. }(_Primitive));
  29023. Primitives.Torus = Torus;
  29024. var Ground = (function (_super) {
  29025. __extends(Ground, _super);
  29026. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  29027. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29028. _this.width = width;
  29029. _this.height = height;
  29030. _this.subdivisions = subdivisions;
  29031. return _this;
  29032. }
  29033. Ground.prototype._regenerateVertexData = function () {
  29034. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  29035. };
  29036. Ground.prototype.copy = function (id) {
  29037. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  29038. };
  29039. Ground.prototype.serialize = function () {
  29040. var serializationObject = _super.prototype.serialize.call(this);
  29041. serializationObject.width = this.width;
  29042. serializationObject.height = this.height;
  29043. serializationObject.subdivisions = this.subdivisions;
  29044. return serializationObject;
  29045. };
  29046. Ground.Parse = function (parsedGround, scene) {
  29047. if (scene.getGeometryByID(parsedGround.id)) {
  29048. return null; // null since geometry could be something else than a ground...
  29049. }
  29050. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  29051. if (BABYLON.Tags) {
  29052. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  29053. }
  29054. scene.pushGeometry(ground, true);
  29055. return ground;
  29056. };
  29057. return Ground;
  29058. }(_Primitive));
  29059. Primitives.Ground = Ground;
  29060. var TiledGround = (function (_super) {
  29061. __extends(TiledGround, _super);
  29062. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  29063. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29064. _this.xmin = xmin;
  29065. _this.zmin = zmin;
  29066. _this.xmax = xmax;
  29067. _this.zmax = zmax;
  29068. _this.subdivisions = subdivisions;
  29069. _this.precision = precision;
  29070. return _this;
  29071. }
  29072. TiledGround.prototype._regenerateVertexData = function () {
  29073. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  29074. };
  29075. TiledGround.prototype.copy = function (id) {
  29076. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  29077. };
  29078. return TiledGround;
  29079. }(_Primitive));
  29080. Primitives.TiledGround = TiledGround;
  29081. var Plane = (function (_super) {
  29082. __extends(Plane, _super);
  29083. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  29084. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29085. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29086. _this.size = size;
  29087. _this.side = side;
  29088. return _this;
  29089. }
  29090. Plane.prototype._regenerateVertexData = function () {
  29091. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  29092. };
  29093. Plane.prototype.copy = function (id) {
  29094. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29095. };
  29096. Plane.prototype.serialize = function () {
  29097. var serializationObject = _super.prototype.serialize.call(this);
  29098. serializationObject.size = this.size;
  29099. return serializationObject;
  29100. };
  29101. Plane.Parse = function (parsedPlane, scene) {
  29102. if (scene.getGeometryByID(parsedPlane.id)) {
  29103. return null; // null since geometry could be something else than a ground...
  29104. }
  29105. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  29106. if (BABYLON.Tags) {
  29107. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  29108. }
  29109. scene.pushGeometry(plane, true);
  29110. return plane;
  29111. };
  29112. return Plane;
  29113. }(_Primitive));
  29114. Primitives.Plane = Plane;
  29115. var TorusKnot = (function (_super) {
  29116. __extends(TorusKnot, _super);
  29117. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  29118. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29119. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29120. _this.radius = radius;
  29121. _this.tube = tube;
  29122. _this.radialSegments = radialSegments;
  29123. _this.tubularSegments = tubularSegments;
  29124. _this.p = p;
  29125. _this.q = q;
  29126. _this.side = side;
  29127. return _this;
  29128. }
  29129. TorusKnot.prototype._regenerateVertexData = function () {
  29130. 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 });
  29131. };
  29132. TorusKnot.prototype.copy = function (id) {
  29133. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  29134. };
  29135. TorusKnot.prototype.serialize = function () {
  29136. var serializationObject = _super.prototype.serialize.call(this);
  29137. serializationObject.radius = this.radius;
  29138. serializationObject.tube = this.tube;
  29139. serializationObject.radialSegments = this.radialSegments;
  29140. serializationObject.tubularSegments = this.tubularSegments;
  29141. serializationObject.p = this.p;
  29142. serializationObject.q = this.q;
  29143. return serializationObject;
  29144. };
  29145. ;
  29146. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  29147. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  29148. return null; // null since geometry could be something else than a ground...
  29149. }
  29150. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  29151. if (BABYLON.Tags) {
  29152. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  29153. }
  29154. scene.pushGeometry(torusKnot, true);
  29155. return torusKnot;
  29156. };
  29157. return TorusKnot;
  29158. }(_Primitive));
  29159. Primitives.TorusKnot = TorusKnot;
  29160. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  29161. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  29162. })(BABYLON || (BABYLON = {}));
  29163. //# sourceMappingURL=babylon.geometry.js.map
  29164. var BABYLON;
  29165. (function (BABYLON) {
  29166. var PostProcessManager = (function () {
  29167. function PostProcessManager(scene) {
  29168. this._vertexBuffers = {};
  29169. this._scene = scene;
  29170. }
  29171. PostProcessManager.prototype._prepareBuffers = function () {
  29172. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  29173. return;
  29174. }
  29175. // VBO
  29176. var vertices = [];
  29177. vertices.push(1, 1);
  29178. vertices.push(-1, 1);
  29179. vertices.push(-1, -1);
  29180. vertices.push(1, -1);
  29181. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  29182. // Indices
  29183. var indices = [];
  29184. indices.push(0);
  29185. indices.push(1);
  29186. indices.push(2);
  29187. indices.push(0);
  29188. indices.push(2);
  29189. indices.push(3);
  29190. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  29191. };
  29192. // Methods
  29193. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  29194. var postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  29195. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29196. return false;
  29197. }
  29198. postProcesses[0].activate(this._scene.activeCamera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  29199. return true;
  29200. };
  29201. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  29202. var engine = this._scene.getEngine();
  29203. for (var index = 0; index < postProcesses.length; index++) {
  29204. if (index < postProcesses.length - 1) {
  29205. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29206. }
  29207. else {
  29208. if (targetTexture) {
  29209. engine.bindFramebuffer(targetTexture);
  29210. }
  29211. else {
  29212. engine.restoreDefaultFramebuffer();
  29213. }
  29214. }
  29215. var pp = postProcesses[index];
  29216. var effect = pp.apply();
  29217. if (effect) {
  29218. pp.onBeforeRenderObservable.notifyObservers(effect);
  29219. // VBOs
  29220. this._prepareBuffers();
  29221. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29222. // Draw order
  29223. engine.draw(true, 0, 6);
  29224. pp.onAfterRenderObservable.notifyObservers(effect);
  29225. }
  29226. }
  29227. // Restore depth buffer
  29228. engine.setDepthBuffer(true);
  29229. engine.setDepthWrite(true);
  29230. };
  29231. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  29232. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  29233. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29234. return;
  29235. }
  29236. var engine = this._scene.getEngine();
  29237. for (var index = 0, len = postProcesses.length; index < len; index++) {
  29238. if (index < len - 1) {
  29239. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29240. }
  29241. else {
  29242. if (targetTexture) {
  29243. engine.bindFramebuffer(targetTexture, faceIndex);
  29244. }
  29245. else {
  29246. engine.restoreDefaultFramebuffer();
  29247. }
  29248. }
  29249. if (doNotPresent) {
  29250. break;
  29251. }
  29252. var pp = postProcesses[index];
  29253. var effect = pp.apply();
  29254. if (effect) {
  29255. pp.onBeforeRenderObservable.notifyObservers(effect);
  29256. // VBOs
  29257. this._prepareBuffers();
  29258. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29259. // Draw order
  29260. engine.draw(true, 0, 6);
  29261. pp.onAfterRenderObservable.notifyObservers(effect);
  29262. }
  29263. }
  29264. // Restore states
  29265. engine.setDepthBuffer(true);
  29266. engine.setDepthWrite(true);
  29267. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29268. };
  29269. PostProcessManager.prototype.dispose = function () {
  29270. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  29271. if (buffer) {
  29272. buffer.dispose();
  29273. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  29274. }
  29275. if (this._indexBuffer) {
  29276. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  29277. this._indexBuffer = null;
  29278. }
  29279. };
  29280. return PostProcessManager;
  29281. }());
  29282. BABYLON.PostProcessManager = PostProcessManager;
  29283. })(BABYLON || (BABYLON = {}));
  29284. //# sourceMappingURL=babylon.postProcessManager.js.map
  29285. var BABYLON;
  29286. (function (BABYLON) {
  29287. /**
  29288. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  29289. */
  29290. var PerformanceMonitor = (function () {
  29291. /**
  29292. * constructor
  29293. * @param frameSampleSize The number of samples required to saturate the sliding window
  29294. */
  29295. function PerformanceMonitor(frameSampleSize) {
  29296. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  29297. this._enabled = true;
  29298. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  29299. }
  29300. /**
  29301. * Samples current frame
  29302. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  29303. */
  29304. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  29305. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  29306. if (!this._enabled)
  29307. return;
  29308. if (this._lastFrameTimeMs != null) {
  29309. var dt = timeMs - this._lastFrameTimeMs;
  29310. this._rollingFrameTime.add(dt);
  29311. }
  29312. this._lastFrameTimeMs = timeMs;
  29313. };
  29314. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  29315. /**
  29316. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  29317. * @return Average frame time in milliseconds
  29318. */
  29319. get: function () {
  29320. return this._rollingFrameTime.average;
  29321. },
  29322. enumerable: true,
  29323. configurable: true
  29324. });
  29325. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  29326. /**
  29327. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  29328. * @return Frame time variance in milliseconds squared
  29329. */
  29330. get: function () {
  29331. return this._rollingFrameTime.variance;
  29332. },
  29333. enumerable: true,
  29334. configurable: true
  29335. });
  29336. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  29337. /**
  29338. * Returns the frame time of the most recent frame
  29339. * @return Frame time in milliseconds
  29340. */
  29341. get: function () {
  29342. return this._rollingFrameTime.history(0);
  29343. },
  29344. enumerable: true,
  29345. configurable: true
  29346. });
  29347. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  29348. /**
  29349. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  29350. * @return Framerate in frames per second
  29351. */
  29352. get: function () {
  29353. return 1000.0 / this._rollingFrameTime.average;
  29354. },
  29355. enumerable: true,
  29356. configurable: true
  29357. });
  29358. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  29359. /**
  29360. * Returns the average framerate in frames per second using the most recent frame time
  29361. * @return Framerate in frames per second
  29362. */
  29363. get: function () {
  29364. return 1000.0 / this._rollingFrameTime.history(0);
  29365. },
  29366. enumerable: true,
  29367. configurable: true
  29368. });
  29369. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  29370. /**
  29371. * Returns true if enough samples have been taken to completely fill the sliding window
  29372. * @return true if saturated
  29373. */
  29374. get: function () {
  29375. return this._rollingFrameTime.isSaturated();
  29376. },
  29377. enumerable: true,
  29378. configurable: true
  29379. });
  29380. /**
  29381. * Enables contributions to the sliding window sample set
  29382. */
  29383. PerformanceMonitor.prototype.enable = function () {
  29384. this._enabled = true;
  29385. };
  29386. /**
  29387. * Disables contributions to the sliding window sample set
  29388. * Samples will not be interpolated over the disabled period
  29389. */
  29390. PerformanceMonitor.prototype.disable = function () {
  29391. this._enabled = false;
  29392. //clear last sample to avoid interpolating over the disabled period when next enabled
  29393. this._lastFrameTimeMs = null;
  29394. this._lastChangeTimeMs = null;
  29395. };
  29396. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  29397. /**
  29398. * Returns true if sampling is enabled
  29399. * @return true if enabled
  29400. */
  29401. get: function () {
  29402. return this._enabled;
  29403. },
  29404. enumerable: true,
  29405. configurable: true
  29406. });
  29407. /**
  29408. * Resets performance monitor
  29409. */
  29410. PerformanceMonitor.prototype.reset = function () {
  29411. //clear last sample to avoid interpolating over the disabled period when next enabled
  29412. this._lastFrameTimeMs = null;
  29413. this._lastChangeTimeMs = null;
  29414. //wipe record
  29415. this._rollingFrameTime.reset();
  29416. };
  29417. return PerformanceMonitor;
  29418. }());
  29419. BABYLON.PerformanceMonitor = PerformanceMonitor;
  29420. /**
  29421. * RollingAverage
  29422. *
  29423. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  29424. */
  29425. var RollingAverage = (function () {
  29426. /**
  29427. * constructor
  29428. * @param length The number of samples required to saturate the sliding window
  29429. */
  29430. function RollingAverage(length) {
  29431. this._samples = new Array(length);
  29432. this.reset();
  29433. }
  29434. /**
  29435. * Adds a sample to the sample set
  29436. * @param v The sample value
  29437. */
  29438. RollingAverage.prototype.add = function (v) {
  29439. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  29440. var delta;
  29441. //we need to check if we've already wrapped round
  29442. if (this.isSaturated()) {
  29443. //remove bottom of stack from mean
  29444. var bottomValue = this._samples[this._pos];
  29445. delta = bottomValue - this.average;
  29446. this.average -= delta / (this._sampleCount - 1);
  29447. this._m2 -= delta * (bottomValue - this.average);
  29448. }
  29449. else {
  29450. this._sampleCount++;
  29451. }
  29452. //add new value to mean
  29453. delta = v - this.average;
  29454. this.average += delta / (this._sampleCount);
  29455. this._m2 += delta * (v - this.average);
  29456. //set the new variance
  29457. this.variance = this._m2 / (this._sampleCount - 1);
  29458. this._samples[this._pos] = v;
  29459. this._pos++;
  29460. this._pos %= this._samples.length; //positive wrap around
  29461. };
  29462. /**
  29463. * Returns previously added values or null if outside of history or outside the sliding window domain
  29464. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  29465. * @return Value previously recorded with add() or null if outside of range
  29466. */
  29467. RollingAverage.prototype.history = function (i) {
  29468. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  29469. return null;
  29470. }
  29471. var i0 = this._wrapPosition(this._pos - 1.0);
  29472. return this._samples[this._wrapPosition(i0 - i)];
  29473. };
  29474. /**
  29475. * Returns true if enough samples have been taken to completely fill the sliding window
  29476. * @return true if sample-set saturated
  29477. */
  29478. RollingAverage.prototype.isSaturated = function () {
  29479. return this._sampleCount >= this._samples.length;
  29480. };
  29481. /**
  29482. * Resets the rolling average (equivalent to 0 samples taken so far)
  29483. */
  29484. RollingAverage.prototype.reset = function () {
  29485. this.average = 0;
  29486. this.variance = 0;
  29487. this._sampleCount = 0;
  29488. this._pos = 0;
  29489. this._m2 = 0;
  29490. };
  29491. /**
  29492. * Wraps a value around the sample range boundaries
  29493. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  29494. * @return Wrapped position in sample range
  29495. */
  29496. RollingAverage.prototype._wrapPosition = function (i) {
  29497. var max = this._samples.length;
  29498. return ((i % max) + max) % max;
  29499. };
  29500. return RollingAverage;
  29501. }());
  29502. BABYLON.RollingAverage = RollingAverage;
  29503. })(BABYLON || (BABYLON = {}));
  29504. //# sourceMappingURL=babylon.performanceMonitor.js.map
  29505. var BABYLON;
  29506. (function (BABYLON) {
  29507. var StandardMaterialDefines = (function (_super) {
  29508. __extends(StandardMaterialDefines, _super);
  29509. function StandardMaterialDefines() {
  29510. var _this = _super.call(this) || this;
  29511. _this.MAINUV1 = false;
  29512. _this.MAINUV2 = false;
  29513. _this.DIFFUSE = false;
  29514. _this.DIFFUSEDIRECTUV = 0;
  29515. _this.AMBIENT = false;
  29516. _this.AMBIENTDIRECTUV = 0;
  29517. _this.OPACITY = false;
  29518. _this.OPACITYDIRECTUV = 0;
  29519. _this.OPACITYRGB = false;
  29520. _this.REFLECTION = false;
  29521. _this.EMISSIVE = false;
  29522. _this.EMISSIVEDIRECTUV = 0;
  29523. _this.SPECULAR = false;
  29524. _this.SPECULARDIRECTUV = 0;
  29525. _this.BUMP = false;
  29526. _this.BUMPDIRECTUV = 0;
  29527. _this.PARALLAX = false;
  29528. _this.PARALLAXOCCLUSION = false;
  29529. _this.SPECULAROVERALPHA = false;
  29530. _this.CLIPPLANE = false;
  29531. _this.ALPHATEST = false;
  29532. _this.ALPHAFROMDIFFUSE = false;
  29533. _this.POINTSIZE = false;
  29534. _this.FOG = false;
  29535. _this.SPECULARTERM = false;
  29536. _this.DIFFUSEFRESNEL = false;
  29537. _this.OPACITYFRESNEL = false;
  29538. _this.REFLECTIONFRESNEL = false;
  29539. _this.REFRACTIONFRESNEL = false;
  29540. _this.EMISSIVEFRESNEL = false;
  29541. _this.FRESNEL = false;
  29542. _this.NORMAL = false;
  29543. _this.UV1 = false;
  29544. _this.UV2 = false;
  29545. _this.VERTEXCOLOR = false;
  29546. _this.VERTEXALPHA = false;
  29547. _this.NUM_BONE_INFLUENCERS = 0;
  29548. _this.BonesPerMesh = 0;
  29549. _this.INSTANCES = false;
  29550. _this.GLOSSINESS = false;
  29551. _this.ROUGHNESS = false;
  29552. _this.EMISSIVEASILLUMINATION = false;
  29553. _this.LINKEMISSIVEWITHDIFFUSE = false;
  29554. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  29555. _this.LIGHTMAP = false;
  29556. _this.LIGHTMAPDIRECTUV = 0;
  29557. _this.USELIGHTMAPASSHADOWMAP = false;
  29558. _this.REFLECTIONMAP_3D = false;
  29559. _this.REFLECTIONMAP_SPHERICAL = false;
  29560. _this.REFLECTIONMAP_PLANAR = false;
  29561. _this.REFLECTIONMAP_CUBIC = false;
  29562. _this.REFLECTIONMAP_PROJECTION = false;
  29563. _this.REFLECTIONMAP_SKYBOX = false;
  29564. _this.REFLECTIONMAP_EXPLICIT = false;
  29565. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  29566. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  29567. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  29568. _this.INVERTCUBICMAP = false;
  29569. _this.LOGARITHMICDEPTH = false;
  29570. _this.REFRACTION = false;
  29571. _this.REFRACTIONMAP_3D = false;
  29572. _this.REFLECTIONOVERALPHA = false;
  29573. _this.TWOSIDEDLIGHTING = false;
  29574. _this.SHADOWFLOAT = false;
  29575. _this.MORPHTARGETS = false;
  29576. _this.MORPHTARGETS_NORMAL = false;
  29577. _this.MORPHTARGETS_TANGENT = false;
  29578. _this.NUM_MORPH_INFLUENCERS = 0;
  29579. _this.USERIGHTHANDEDSYSTEM = false;
  29580. _this.IMAGEPROCESSING = false;
  29581. _this.VIGNETTE = false;
  29582. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  29583. _this.VIGNETTEBLENDMODEOPAQUE = false;
  29584. _this.TONEMAPPING = false;
  29585. _this.CONTRAST = false;
  29586. _this.COLORCURVES = false;
  29587. _this.COLORGRADING = false;
  29588. _this.SAMPLER3DGREENDEPTH = false;
  29589. _this.SAMPLER3DBGRMAP = false;
  29590. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  29591. _this.EXPOSURE = false;
  29592. _this.rebuild();
  29593. return _this;
  29594. }
  29595. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  29596. var modes = [
  29597. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  29598. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  29599. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  29600. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  29601. ];
  29602. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  29603. var mode = modes_1[_i];
  29604. this[mode] = (mode === modeToEnable);
  29605. }
  29606. };
  29607. return StandardMaterialDefines;
  29608. }(BABYLON.MaterialDefines));
  29609. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  29610. var StandardMaterial = (function (_super) {
  29611. __extends(StandardMaterial, _super);
  29612. function StandardMaterial(name, scene) {
  29613. var _this = _super.call(this, name, scene) || this;
  29614. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  29615. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  29616. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  29617. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  29618. _this.specularPower = 64;
  29619. _this._useAlphaFromDiffuseTexture = false;
  29620. _this._useEmissiveAsIllumination = false;
  29621. _this._linkEmissiveWithDiffuse = false;
  29622. _this._useSpecularOverAlpha = false;
  29623. _this._useReflectionOverAlpha = false;
  29624. _this._disableLighting = false;
  29625. _this._useParallax = false;
  29626. _this._useParallaxOcclusion = false;
  29627. _this.parallaxScaleBias = 0.05;
  29628. _this._roughness = 0;
  29629. _this.indexOfRefraction = 0.98;
  29630. _this.invertRefractionY = true;
  29631. _this._useLightmapAsShadowmap = false;
  29632. _this._useReflectionFresnelFromSpecular = false;
  29633. _this._useGlossinessFromSpecularMapAlpha = false;
  29634. _this._maxSimultaneousLights = 4;
  29635. /**
  29636. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  29637. */
  29638. _this._invertNormalMapX = false;
  29639. /**
  29640. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  29641. */
  29642. _this._invertNormalMapY = false;
  29643. /**
  29644. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  29645. */
  29646. _this._twoSidedLighting = false;
  29647. _this._renderTargets = new BABYLON.SmartArray(16);
  29648. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  29649. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  29650. // Setup the default processing configuration to the scene.
  29651. _this._attachImageProcessingConfiguration(null);
  29652. _this.getRenderTargetTextures = function () {
  29653. _this._renderTargets.reset();
  29654. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  29655. _this._renderTargets.push(_this._reflectionTexture);
  29656. }
  29657. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  29658. _this._renderTargets.push(_this._refractionTexture);
  29659. }
  29660. return _this._renderTargets;
  29661. };
  29662. return _this;
  29663. }
  29664. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  29665. /**
  29666. * Gets the image processing configuration used either in this material.
  29667. */
  29668. get: function () {
  29669. return this._imageProcessingConfiguration;
  29670. },
  29671. /**
  29672. * Sets the Default image processing configuration used either in the this material.
  29673. *
  29674. * If sets to null, the scene one is in use.
  29675. */
  29676. set: function (value) {
  29677. this._attachImageProcessingConfiguration(value);
  29678. // Ensure the effect will be rebuilt.
  29679. this._markAllSubMeshesAsTexturesDirty();
  29680. },
  29681. enumerable: true,
  29682. configurable: true
  29683. });
  29684. /**
  29685. * Attaches a new image processing configuration to the Standard Material.
  29686. * @param configuration
  29687. */
  29688. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  29689. var _this = this;
  29690. if (configuration === this._imageProcessingConfiguration) {
  29691. return;
  29692. }
  29693. // Detaches observer.
  29694. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  29695. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  29696. }
  29697. // Pick the scene configuration if needed.
  29698. if (!configuration) {
  29699. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  29700. }
  29701. else {
  29702. this._imageProcessingConfiguration = configuration;
  29703. }
  29704. // Attaches observer.
  29705. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  29706. _this._markAllSubMeshesAsImageProcessingDirty();
  29707. });
  29708. };
  29709. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  29710. /**
  29711. * Gets wether the color curves effect is enabled.
  29712. */
  29713. get: function () {
  29714. return this.imageProcessingConfiguration.colorCurvesEnabled;
  29715. },
  29716. /**
  29717. * Sets wether the color curves effect is enabled.
  29718. */
  29719. set: function (value) {
  29720. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  29721. },
  29722. enumerable: true,
  29723. configurable: true
  29724. });
  29725. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  29726. /**
  29727. * Gets wether the color grading effect is enabled.
  29728. */
  29729. get: function () {
  29730. return this.imageProcessingConfiguration.colorGradingEnabled;
  29731. },
  29732. /**
  29733. * Gets wether the color grading effect is enabled.
  29734. */
  29735. set: function (value) {
  29736. this.imageProcessingConfiguration.colorGradingEnabled = value;
  29737. },
  29738. enumerable: true,
  29739. configurable: true
  29740. });
  29741. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  29742. /**
  29743. * Gets wether tonemapping is enabled or not.
  29744. */
  29745. get: function () {
  29746. return this._imageProcessingConfiguration.toneMappingEnabled;
  29747. },
  29748. /**
  29749. * Sets wether tonemapping is enabled or not
  29750. */
  29751. set: function (value) {
  29752. this._imageProcessingConfiguration.toneMappingEnabled = value;
  29753. },
  29754. enumerable: true,
  29755. configurable: true
  29756. });
  29757. ;
  29758. ;
  29759. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  29760. /**
  29761. * The camera exposure used on this material.
  29762. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  29763. * This corresponds to a photographic exposure.
  29764. */
  29765. get: function () {
  29766. return this._imageProcessingConfiguration.exposure;
  29767. },
  29768. /**
  29769. * The camera exposure used on this material.
  29770. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  29771. * This corresponds to a photographic exposure.
  29772. */
  29773. set: function (value) {
  29774. this._imageProcessingConfiguration.exposure = value;
  29775. },
  29776. enumerable: true,
  29777. configurable: true
  29778. });
  29779. ;
  29780. ;
  29781. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  29782. /**
  29783. * Gets The camera contrast used on this material.
  29784. */
  29785. get: function () {
  29786. return this._imageProcessingConfiguration.contrast;
  29787. },
  29788. /**
  29789. * Sets The camera contrast used on this material.
  29790. */
  29791. set: function (value) {
  29792. this._imageProcessingConfiguration.contrast = value;
  29793. },
  29794. enumerable: true,
  29795. configurable: true
  29796. });
  29797. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  29798. /**
  29799. * Gets the Color Grading 2D Lookup Texture.
  29800. */
  29801. get: function () {
  29802. return this._imageProcessingConfiguration.colorGradingTexture;
  29803. },
  29804. /**
  29805. * Sets the Color Grading 2D Lookup Texture.
  29806. */
  29807. set: function (value) {
  29808. this._imageProcessingConfiguration.colorGradingTexture = value;
  29809. },
  29810. enumerable: true,
  29811. configurable: true
  29812. });
  29813. StandardMaterial.prototype.getClassName = function () {
  29814. return "StandardMaterial";
  29815. };
  29816. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  29817. get: function () {
  29818. return this._useLogarithmicDepth;
  29819. },
  29820. set: function (value) {
  29821. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  29822. this._markAllSubMeshesAsMiscDirty();
  29823. },
  29824. enumerable: true,
  29825. configurable: true
  29826. });
  29827. StandardMaterial.prototype.needAlphaBlending = function () {
  29828. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  29829. };
  29830. StandardMaterial.prototype.needAlphaTesting = function () {
  29831. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  29832. };
  29833. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  29834. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  29835. };
  29836. StandardMaterial.prototype.getAlphaTestTexture = function () {
  29837. return this._diffuseTexture;
  29838. };
  29839. /**
  29840. * Child classes can use it to update shaders
  29841. */
  29842. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  29843. if (this.isFrozen) {
  29844. if (this._wasPreviouslyReady && subMesh.effect) {
  29845. return true;
  29846. }
  29847. }
  29848. if (!subMesh._materialDefines) {
  29849. subMesh._materialDefines = new StandardMaterialDefines();
  29850. }
  29851. var scene = this.getScene();
  29852. var defines = subMesh._materialDefines;
  29853. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  29854. if (defines._renderId === scene.getRenderId()) {
  29855. return true;
  29856. }
  29857. }
  29858. var engine = scene.getEngine();
  29859. // Lights
  29860. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  29861. // Textures
  29862. if (defines._areTexturesDirty) {
  29863. defines._needUVs = false;
  29864. defines.MAINUV1 = false;
  29865. defines.MAINUV2 = false;
  29866. if (scene.texturesEnabled) {
  29867. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  29868. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  29869. return false;
  29870. }
  29871. else {
  29872. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  29873. }
  29874. }
  29875. else {
  29876. defines.DIFFUSE = false;
  29877. }
  29878. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  29879. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  29880. return false;
  29881. }
  29882. else {
  29883. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  29884. }
  29885. }
  29886. else {
  29887. defines.AMBIENT = false;
  29888. }
  29889. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  29890. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  29891. return false;
  29892. }
  29893. else {
  29894. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  29895. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  29896. }
  29897. }
  29898. else {
  29899. defines.OPACITY = false;
  29900. }
  29901. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  29902. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  29903. return false;
  29904. }
  29905. else {
  29906. defines._needNormals = true;
  29907. defines.REFLECTION = true;
  29908. defines.ROUGHNESS = (this._roughness > 0);
  29909. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  29910. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  29911. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  29912. switch (this._reflectionTexture.coordinatesMode) {
  29913. case BABYLON.Texture.CUBIC_MODE:
  29914. case BABYLON.Texture.INVCUBIC_MODE:
  29915. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  29916. break;
  29917. case BABYLON.Texture.EXPLICIT_MODE:
  29918. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  29919. break;
  29920. case BABYLON.Texture.PLANAR_MODE:
  29921. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  29922. break;
  29923. case BABYLON.Texture.PROJECTION_MODE:
  29924. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  29925. break;
  29926. case BABYLON.Texture.SKYBOX_MODE:
  29927. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  29928. break;
  29929. case BABYLON.Texture.SPHERICAL_MODE:
  29930. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  29931. break;
  29932. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  29933. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  29934. break;
  29935. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  29936. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  29937. break;
  29938. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  29939. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  29940. break;
  29941. }
  29942. }
  29943. }
  29944. else {
  29945. defines.REFLECTION = false;
  29946. }
  29947. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  29948. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  29949. return false;
  29950. }
  29951. else {
  29952. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  29953. }
  29954. }
  29955. else {
  29956. defines.EMISSIVE = false;
  29957. }
  29958. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  29959. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  29960. return false;
  29961. }
  29962. else {
  29963. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  29964. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  29965. }
  29966. }
  29967. else {
  29968. defines.LIGHTMAP = false;
  29969. }
  29970. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  29971. if (!this._specularTexture.isReadyOrNotBlocking()) {
  29972. return false;
  29973. }
  29974. else {
  29975. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  29976. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  29977. }
  29978. }
  29979. else {
  29980. defines.SPECULAR = false;
  29981. }
  29982. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  29983. // Bump texure can not be not blocking.
  29984. if (!this._bumpTexture.isReady()) {
  29985. return false;
  29986. }
  29987. else {
  29988. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  29989. defines.PARALLAX = this._useParallax;
  29990. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  29991. }
  29992. }
  29993. else {
  29994. defines.BUMP = false;
  29995. }
  29996. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  29997. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  29998. return false;
  29999. }
  30000. else {
  30001. defines._needUVs = true;
  30002. defines.REFRACTION = true;
  30003. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  30004. }
  30005. }
  30006. else {
  30007. defines.REFRACTION = false;
  30008. }
  30009. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  30010. }
  30011. else {
  30012. defines.DIFFUSE = false;
  30013. defines.AMBIENT = false;
  30014. defines.OPACITY = false;
  30015. defines.REFLECTION = false;
  30016. defines.EMISSIVE = false;
  30017. defines.LIGHTMAP = false;
  30018. defines.BUMP = false;
  30019. defines.REFRACTION = false;
  30020. }
  30021. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  30022. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  30023. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  30024. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  30025. }
  30026. if (defines._areImageProcessingDirty) {
  30027. if (!this._imageProcessingConfiguration.isReady()) {
  30028. return false;
  30029. }
  30030. this._imageProcessingConfiguration.prepareDefines(defines);
  30031. }
  30032. if (defines._areFresnelDirty) {
  30033. if (StandardMaterial.FresnelEnabled) {
  30034. // Fresnel
  30035. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  30036. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  30037. this._reflectionFresnelParameters) {
  30038. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  30039. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  30040. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  30041. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  30042. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  30043. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  30044. defines._needNormals = true;
  30045. defines.FRESNEL = true;
  30046. }
  30047. }
  30048. else {
  30049. defines.FRESNEL = false;
  30050. }
  30051. }
  30052. // Misc.
  30053. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  30054. // Attribs
  30055. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  30056. // Values that need to be evaluated on every frame
  30057. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  30058. // Get correct effect
  30059. if (defines.isDirty) {
  30060. defines.markAsProcessed();
  30061. scene.resetCachedMaterial();
  30062. // Fallbacks
  30063. var fallbacks = new BABYLON.EffectFallbacks();
  30064. if (defines.REFLECTION) {
  30065. fallbacks.addFallback(0, "REFLECTION");
  30066. }
  30067. if (defines.SPECULAR) {
  30068. fallbacks.addFallback(0, "SPECULAR");
  30069. }
  30070. if (defines.BUMP) {
  30071. fallbacks.addFallback(0, "BUMP");
  30072. }
  30073. if (defines.PARALLAX) {
  30074. fallbacks.addFallback(1, "PARALLAX");
  30075. }
  30076. if (defines.PARALLAXOCCLUSION) {
  30077. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  30078. }
  30079. if (defines.SPECULAROVERALPHA) {
  30080. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  30081. }
  30082. if (defines.FOG) {
  30083. fallbacks.addFallback(1, "FOG");
  30084. }
  30085. if (defines.POINTSIZE) {
  30086. fallbacks.addFallback(0, "POINTSIZE");
  30087. }
  30088. if (defines.LOGARITHMICDEPTH) {
  30089. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  30090. }
  30091. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  30092. if (defines.SPECULARTERM) {
  30093. fallbacks.addFallback(0, "SPECULARTERM");
  30094. }
  30095. if (defines.DIFFUSEFRESNEL) {
  30096. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  30097. }
  30098. if (defines.OPACITYFRESNEL) {
  30099. fallbacks.addFallback(2, "OPACITYFRESNEL");
  30100. }
  30101. if (defines.REFLECTIONFRESNEL) {
  30102. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  30103. }
  30104. if (defines.EMISSIVEFRESNEL) {
  30105. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  30106. }
  30107. if (defines.FRESNEL) {
  30108. fallbacks.addFallback(4, "FRESNEL");
  30109. }
  30110. //Attributes
  30111. var attribs = [BABYLON.VertexBuffer.PositionKind];
  30112. if (defines.NORMAL) {
  30113. attribs.push(BABYLON.VertexBuffer.NormalKind);
  30114. }
  30115. if (defines.UV1) {
  30116. attribs.push(BABYLON.VertexBuffer.UVKind);
  30117. }
  30118. if (defines.UV2) {
  30119. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  30120. }
  30121. if (defines.VERTEXCOLOR) {
  30122. attribs.push(BABYLON.VertexBuffer.ColorKind);
  30123. }
  30124. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  30125. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  30126. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  30127. var shaderName = "default";
  30128. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  30129. "vFogInfos", "vFogColor", "pointSize",
  30130. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  30131. "mBones",
  30132. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  30133. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  30134. "logarithmicDepthConstant", "vNormalReoderParams"
  30135. ];
  30136. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  30137. var uniformBuffers = ["Material", "Scene"];
  30138. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  30139. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  30140. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  30141. uniformsNames: uniforms,
  30142. uniformBuffersNames: uniformBuffers,
  30143. samplers: samplers,
  30144. defines: defines,
  30145. maxSimultaneousLights: this._maxSimultaneousLights
  30146. });
  30147. if (this.customShaderNameResolve) {
  30148. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  30149. }
  30150. var join = defines.toString();
  30151. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  30152. attributes: attribs,
  30153. uniformsNames: uniforms,
  30154. uniformBuffersNames: uniformBuffers,
  30155. samplers: samplers,
  30156. defines: join,
  30157. fallbacks: fallbacks,
  30158. onCompiled: this.onCompiled,
  30159. onError: this.onError,
  30160. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  30161. }, engine), defines);
  30162. this.buildUniformLayout();
  30163. }
  30164. if (!subMesh.effect.isReady()) {
  30165. return false;
  30166. }
  30167. defines._renderId = scene.getRenderId();
  30168. this._wasPreviouslyReady = true;
  30169. return true;
  30170. };
  30171. StandardMaterial.prototype.buildUniformLayout = function () {
  30172. // Order is important !
  30173. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  30174. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  30175. this._uniformBuffer.addUniform("opacityParts", 4);
  30176. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  30177. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  30178. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  30179. this._uniformBuffer.addUniform("refractionRightColor", 4);
  30180. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  30181. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  30182. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  30183. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  30184. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  30185. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  30186. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  30187. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  30188. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  30189. this._uniformBuffer.addUniform("vBumpInfos", 3);
  30190. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  30191. this._uniformBuffer.addUniform("ambientMatrix", 16);
  30192. this._uniformBuffer.addUniform("opacityMatrix", 16);
  30193. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  30194. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  30195. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  30196. this._uniformBuffer.addUniform("specularMatrix", 16);
  30197. this._uniformBuffer.addUniform("bumpMatrix", 16);
  30198. this._uniformBuffer.addUniform("vNormalReoderParams", 4);
  30199. this._uniformBuffer.addUniform("refractionMatrix", 16);
  30200. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  30201. this._uniformBuffer.addUniform("vSpecularColor", 4);
  30202. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  30203. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  30204. this._uniformBuffer.addUniform("pointSize", 1);
  30205. this._uniformBuffer.create();
  30206. };
  30207. StandardMaterial.prototype.unbind = function () {
  30208. if (this._activeEffect) {
  30209. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  30210. this._activeEffect.setTexture("reflection2DSampler", null);
  30211. }
  30212. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  30213. this._activeEffect.setTexture("refraction2DSampler", null);
  30214. }
  30215. }
  30216. _super.prototype.unbind.call(this);
  30217. };
  30218. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  30219. var scene = this.getScene();
  30220. var defines = subMesh._materialDefines;
  30221. if (!defines) {
  30222. return;
  30223. }
  30224. var effect = subMesh.effect;
  30225. this._activeEffect = effect;
  30226. // Matrices
  30227. this.bindOnlyWorldMatrix(world);
  30228. // Bones
  30229. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  30230. if (this._mustRebind(scene, effect, mesh.visibility)) {
  30231. this._uniformBuffer.bindToEffect(effect, "Material");
  30232. this.bindViewProjection(effect);
  30233. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  30234. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  30235. // Fresnel
  30236. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  30237. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  30238. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  30239. }
  30240. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  30241. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  30242. }
  30243. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  30244. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  30245. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  30246. }
  30247. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  30248. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  30249. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  30250. }
  30251. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  30252. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  30253. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  30254. }
  30255. }
  30256. // Textures
  30257. if (scene.texturesEnabled) {
  30258. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  30259. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  30260. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  30261. }
  30262. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  30263. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  30264. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  30265. }
  30266. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  30267. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  30268. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  30269. }
  30270. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  30271. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  30272. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  30273. }
  30274. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  30275. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  30276. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  30277. }
  30278. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  30279. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  30280. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  30281. }
  30282. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  30283. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  30284. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  30285. }
  30286. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  30287. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  30288. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  30289. if (scene._mirroredCameraPosition) {
  30290. 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);
  30291. }
  30292. else {
  30293. 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);
  30294. }
  30295. }
  30296. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  30297. var depth = 1.0;
  30298. if (!this._refractionTexture.isCube) {
  30299. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  30300. if (this._refractionTexture.depth) {
  30301. depth = this._refractionTexture.depth;
  30302. }
  30303. }
  30304. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  30305. }
  30306. }
  30307. // Point size
  30308. if (this.pointsCloud) {
  30309. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  30310. }
  30311. if (defines.SPECULARTERM) {
  30312. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  30313. }
  30314. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  30315. // Diffuse
  30316. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  30317. }
  30318. // Textures
  30319. if (scene.texturesEnabled) {
  30320. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  30321. effect.setTexture("diffuseSampler", this._diffuseTexture);
  30322. }
  30323. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  30324. effect.setTexture("ambientSampler", this._ambientTexture);
  30325. }
  30326. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  30327. effect.setTexture("opacitySampler", this._opacityTexture);
  30328. }
  30329. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  30330. if (this._reflectionTexture.isCube) {
  30331. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  30332. }
  30333. else {
  30334. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  30335. }
  30336. }
  30337. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  30338. effect.setTexture("emissiveSampler", this._emissiveTexture);
  30339. }
  30340. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  30341. effect.setTexture("lightmapSampler", this._lightmapTexture);
  30342. }
  30343. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  30344. effect.setTexture("specularSampler", this._specularTexture);
  30345. }
  30346. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  30347. effect.setTexture("bumpSampler", this._bumpTexture);
  30348. }
  30349. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  30350. var depth = 1.0;
  30351. if (this._refractionTexture.isCube) {
  30352. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  30353. }
  30354. else {
  30355. effect.setTexture("refraction2DSampler", this._refractionTexture);
  30356. }
  30357. }
  30358. }
  30359. // Clip plane
  30360. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  30361. // Colors
  30362. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  30363. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  30364. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  30365. }
  30366. if (this._mustRebind(scene, effect) || !this.isFrozen) {
  30367. // Lights
  30368. if (scene.lightsEnabled && !this._disableLighting) {
  30369. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  30370. }
  30371. // View
  30372. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  30373. this.bindView(effect);
  30374. }
  30375. // Fog
  30376. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  30377. // Morph targets
  30378. if (defines.NUM_MORPH_INFLUENCERS) {
  30379. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  30380. }
  30381. // Log. depth
  30382. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  30383. // image processing
  30384. this._imageProcessingConfiguration.bind(this._activeEffect);
  30385. }
  30386. this._uniformBuffer.update();
  30387. this._afterBind(mesh, this._activeEffect);
  30388. };
  30389. StandardMaterial.prototype.getAnimatables = function () {
  30390. var results = [];
  30391. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  30392. results.push(this._diffuseTexture);
  30393. }
  30394. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  30395. results.push(this._ambientTexture);
  30396. }
  30397. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  30398. results.push(this._opacityTexture);
  30399. }
  30400. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  30401. results.push(this._reflectionTexture);
  30402. }
  30403. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  30404. results.push(this._emissiveTexture);
  30405. }
  30406. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  30407. results.push(this._specularTexture);
  30408. }
  30409. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  30410. results.push(this._bumpTexture);
  30411. }
  30412. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  30413. results.push(this._lightmapTexture);
  30414. }
  30415. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  30416. results.push(this._refractionTexture);
  30417. }
  30418. return results;
  30419. };
  30420. StandardMaterial.prototype.getActiveTextures = function () {
  30421. var activeTextures = _super.prototype.getActiveTextures.call(this);
  30422. if (this._diffuseTexture) {
  30423. activeTextures.push(this._diffuseTexture);
  30424. }
  30425. if (this._ambientTexture) {
  30426. activeTextures.push(this._ambientTexture);
  30427. }
  30428. if (this._opacityTexture) {
  30429. activeTextures.push(this._opacityTexture);
  30430. }
  30431. if (this._reflectionTexture) {
  30432. activeTextures.push(this._reflectionTexture);
  30433. }
  30434. if (this._emissiveTexture) {
  30435. activeTextures.push(this._emissiveTexture);
  30436. }
  30437. if (this._specularTexture) {
  30438. activeTextures.push(this._specularTexture);
  30439. }
  30440. if (this._bumpTexture) {
  30441. activeTextures.push(this._bumpTexture);
  30442. }
  30443. if (this._lightmapTexture) {
  30444. activeTextures.push(this._lightmapTexture);
  30445. }
  30446. if (this._refractionTexture) {
  30447. activeTextures.push(this._refractionTexture);
  30448. }
  30449. return activeTextures;
  30450. };
  30451. StandardMaterial.prototype.hasTexture = function (texture) {
  30452. if (_super.prototype.hasTexture.call(this, texture)) {
  30453. return true;
  30454. }
  30455. if (this._diffuseTexture === texture) {
  30456. return true;
  30457. }
  30458. if (this._ambientTexture === texture) {
  30459. return true;
  30460. }
  30461. if (this._opacityTexture === texture) {
  30462. return true;
  30463. }
  30464. if (this._reflectionTexture === texture) {
  30465. return true;
  30466. }
  30467. if (this._emissiveTexture === texture) {
  30468. return true;
  30469. }
  30470. if (this._specularTexture === texture) {
  30471. return true;
  30472. }
  30473. if (this._bumpTexture === texture) {
  30474. return true;
  30475. }
  30476. if (this._lightmapTexture === texture) {
  30477. return true;
  30478. }
  30479. if (this._refractionTexture === texture) {
  30480. return true;
  30481. }
  30482. return false;
  30483. };
  30484. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  30485. if (forceDisposeTextures) {
  30486. if (this._diffuseTexture) {
  30487. this._diffuseTexture.dispose();
  30488. }
  30489. if (this._ambientTexture) {
  30490. this._ambientTexture.dispose();
  30491. }
  30492. if (this._opacityTexture) {
  30493. this._opacityTexture.dispose();
  30494. }
  30495. if (this._reflectionTexture) {
  30496. this._reflectionTexture.dispose();
  30497. }
  30498. if (this._emissiveTexture) {
  30499. this._emissiveTexture.dispose();
  30500. }
  30501. if (this._specularTexture) {
  30502. this._specularTexture.dispose();
  30503. }
  30504. if (this._bumpTexture) {
  30505. this._bumpTexture.dispose();
  30506. }
  30507. if (this._lightmapTexture) {
  30508. this._lightmapTexture.dispose();
  30509. }
  30510. if (this._refractionTexture) {
  30511. this._refractionTexture.dispose();
  30512. }
  30513. }
  30514. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  30515. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  30516. }
  30517. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  30518. };
  30519. StandardMaterial.prototype.clone = function (name) {
  30520. var _this = this;
  30521. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  30522. result.name = name;
  30523. result.id = name;
  30524. return result;
  30525. };
  30526. StandardMaterial.prototype.serialize = function () {
  30527. return BABYLON.SerializationHelper.Serialize(this);
  30528. };
  30529. // Statics
  30530. StandardMaterial.Parse = function (source, scene, rootUrl) {
  30531. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  30532. };
  30533. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  30534. get: function () {
  30535. return StandardMaterial._DiffuseTextureEnabled;
  30536. },
  30537. set: function (value) {
  30538. if (StandardMaterial._DiffuseTextureEnabled === value) {
  30539. return;
  30540. }
  30541. StandardMaterial._DiffuseTextureEnabled = value;
  30542. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30543. },
  30544. enumerable: true,
  30545. configurable: true
  30546. });
  30547. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  30548. get: function () {
  30549. return StandardMaterial._AmbientTextureEnabled;
  30550. },
  30551. set: function (value) {
  30552. if (StandardMaterial._AmbientTextureEnabled === value) {
  30553. return;
  30554. }
  30555. StandardMaterial._AmbientTextureEnabled = value;
  30556. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30557. },
  30558. enumerable: true,
  30559. configurable: true
  30560. });
  30561. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  30562. get: function () {
  30563. return StandardMaterial._OpacityTextureEnabled;
  30564. },
  30565. set: function (value) {
  30566. if (StandardMaterial._OpacityTextureEnabled === value) {
  30567. return;
  30568. }
  30569. StandardMaterial._OpacityTextureEnabled = value;
  30570. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30571. },
  30572. enumerable: true,
  30573. configurable: true
  30574. });
  30575. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  30576. get: function () {
  30577. return StandardMaterial._ReflectionTextureEnabled;
  30578. },
  30579. set: function (value) {
  30580. if (StandardMaterial._ReflectionTextureEnabled === value) {
  30581. return;
  30582. }
  30583. StandardMaterial._ReflectionTextureEnabled = value;
  30584. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30585. },
  30586. enumerable: true,
  30587. configurable: true
  30588. });
  30589. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  30590. get: function () {
  30591. return StandardMaterial._EmissiveTextureEnabled;
  30592. },
  30593. set: function (value) {
  30594. if (StandardMaterial._EmissiveTextureEnabled === value) {
  30595. return;
  30596. }
  30597. StandardMaterial._EmissiveTextureEnabled = value;
  30598. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30599. },
  30600. enumerable: true,
  30601. configurable: true
  30602. });
  30603. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  30604. get: function () {
  30605. return StandardMaterial._SpecularTextureEnabled;
  30606. },
  30607. set: function (value) {
  30608. if (StandardMaterial._SpecularTextureEnabled === value) {
  30609. return;
  30610. }
  30611. StandardMaterial._SpecularTextureEnabled = value;
  30612. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30613. },
  30614. enumerable: true,
  30615. configurable: true
  30616. });
  30617. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  30618. get: function () {
  30619. return StandardMaterial._BumpTextureEnabled;
  30620. },
  30621. set: function (value) {
  30622. if (StandardMaterial._BumpTextureEnabled === value) {
  30623. return;
  30624. }
  30625. StandardMaterial._BumpTextureEnabled = value;
  30626. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30627. },
  30628. enumerable: true,
  30629. configurable: true
  30630. });
  30631. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  30632. get: function () {
  30633. return StandardMaterial._LightmapTextureEnabled;
  30634. },
  30635. set: function (value) {
  30636. if (StandardMaterial._LightmapTextureEnabled === value) {
  30637. return;
  30638. }
  30639. StandardMaterial._LightmapTextureEnabled = value;
  30640. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30641. },
  30642. enumerable: true,
  30643. configurable: true
  30644. });
  30645. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  30646. get: function () {
  30647. return StandardMaterial._RefractionTextureEnabled;
  30648. },
  30649. set: function (value) {
  30650. if (StandardMaterial._RefractionTextureEnabled === value) {
  30651. return;
  30652. }
  30653. StandardMaterial._RefractionTextureEnabled = value;
  30654. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30655. },
  30656. enumerable: true,
  30657. configurable: true
  30658. });
  30659. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  30660. get: function () {
  30661. return StandardMaterial._ColorGradingTextureEnabled;
  30662. },
  30663. set: function (value) {
  30664. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  30665. return;
  30666. }
  30667. StandardMaterial._ColorGradingTextureEnabled = value;
  30668. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30669. },
  30670. enumerable: true,
  30671. configurable: true
  30672. });
  30673. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  30674. get: function () {
  30675. return StandardMaterial._FresnelEnabled;
  30676. },
  30677. set: function (value) {
  30678. if (StandardMaterial._FresnelEnabled === value) {
  30679. return;
  30680. }
  30681. StandardMaterial._FresnelEnabled = value;
  30682. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  30683. },
  30684. enumerable: true,
  30685. configurable: true
  30686. });
  30687. return StandardMaterial;
  30688. }(BABYLON.PushMaterial));
  30689. // Flags used to enable or disable a type of texture for all Standard Materials
  30690. StandardMaterial._DiffuseTextureEnabled = true;
  30691. StandardMaterial._AmbientTextureEnabled = true;
  30692. StandardMaterial._OpacityTextureEnabled = true;
  30693. StandardMaterial._ReflectionTextureEnabled = true;
  30694. StandardMaterial._EmissiveTextureEnabled = true;
  30695. StandardMaterial._SpecularTextureEnabled = true;
  30696. StandardMaterial._BumpTextureEnabled = true;
  30697. StandardMaterial._LightmapTextureEnabled = true;
  30698. StandardMaterial._RefractionTextureEnabled = true;
  30699. StandardMaterial._ColorGradingTextureEnabled = true;
  30700. StandardMaterial._FresnelEnabled = true;
  30701. __decorate([
  30702. BABYLON.serializeAsTexture("diffuseTexture")
  30703. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  30704. __decorate([
  30705. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30706. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  30707. __decorate([
  30708. BABYLON.serializeAsTexture("ambientTexture")
  30709. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  30710. __decorate([
  30711. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30712. ], StandardMaterial.prototype, "ambientTexture", void 0);
  30713. __decorate([
  30714. BABYLON.serializeAsTexture("opacityTexture")
  30715. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  30716. __decorate([
  30717. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30718. ], StandardMaterial.prototype, "opacityTexture", void 0);
  30719. __decorate([
  30720. BABYLON.serializeAsTexture("reflectionTexture")
  30721. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  30722. __decorate([
  30723. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30724. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  30725. __decorate([
  30726. BABYLON.serializeAsTexture("emissiveTexture")
  30727. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  30728. __decorate([
  30729. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30730. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  30731. __decorate([
  30732. BABYLON.serializeAsTexture("specularTexture")
  30733. ], StandardMaterial.prototype, "_specularTexture", void 0);
  30734. __decorate([
  30735. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30736. ], StandardMaterial.prototype, "specularTexture", void 0);
  30737. __decorate([
  30738. BABYLON.serializeAsTexture("bumpTexture")
  30739. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  30740. __decorate([
  30741. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30742. ], StandardMaterial.prototype, "bumpTexture", void 0);
  30743. __decorate([
  30744. BABYLON.serializeAsTexture("lightmapTexture")
  30745. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  30746. __decorate([
  30747. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30748. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  30749. __decorate([
  30750. BABYLON.serializeAsTexture("refractionTexture")
  30751. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  30752. __decorate([
  30753. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30754. ], StandardMaterial.prototype, "refractionTexture", void 0);
  30755. __decorate([
  30756. BABYLON.serializeAsColor3("ambient")
  30757. ], StandardMaterial.prototype, "ambientColor", void 0);
  30758. __decorate([
  30759. BABYLON.serializeAsColor3("diffuse")
  30760. ], StandardMaterial.prototype, "diffuseColor", void 0);
  30761. __decorate([
  30762. BABYLON.serializeAsColor3("specular")
  30763. ], StandardMaterial.prototype, "specularColor", void 0);
  30764. __decorate([
  30765. BABYLON.serializeAsColor3("emissive")
  30766. ], StandardMaterial.prototype, "emissiveColor", void 0);
  30767. __decorate([
  30768. BABYLON.serialize()
  30769. ], StandardMaterial.prototype, "specularPower", void 0);
  30770. __decorate([
  30771. BABYLON.serialize("useAlphaFromDiffuseTexture")
  30772. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  30773. __decorate([
  30774. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30775. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  30776. __decorate([
  30777. BABYLON.serialize("useEmissiveAsIllumination")
  30778. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  30779. __decorate([
  30780. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30781. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  30782. __decorate([
  30783. BABYLON.serialize("linkEmissiveWithDiffuse")
  30784. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  30785. __decorate([
  30786. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30787. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  30788. __decorate([
  30789. BABYLON.serialize("useSpecularOverAlpha")
  30790. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  30791. __decorate([
  30792. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30793. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  30794. __decorate([
  30795. BABYLON.serialize("useReflectionOverAlpha")
  30796. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  30797. __decorate([
  30798. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30799. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  30800. __decorate([
  30801. BABYLON.serialize("disableLighting")
  30802. ], StandardMaterial.prototype, "_disableLighting", void 0);
  30803. __decorate([
  30804. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  30805. ], StandardMaterial.prototype, "disableLighting", void 0);
  30806. __decorate([
  30807. BABYLON.serialize("useParallax")
  30808. ], StandardMaterial.prototype, "_useParallax", void 0);
  30809. __decorate([
  30810. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30811. ], StandardMaterial.prototype, "useParallax", void 0);
  30812. __decorate([
  30813. BABYLON.serialize("useParallaxOcclusion")
  30814. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  30815. __decorate([
  30816. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30817. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  30818. __decorate([
  30819. BABYLON.serialize()
  30820. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  30821. __decorate([
  30822. BABYLON.serialize("roughness")
  30823. ], StandardMaterial.prototype, "_roughness", void 0);
  30824. __decorate([
  30825. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30826. ], StandardMaterial.prototype, "roughness", void 0);
  30827. __decorate([
  30828. BABYLON.serialize()
  30829. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  30830. __decorate([
  30831. BABYLON.serialize()
  30832. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  30833. __decorate([
  30834. BABYLON.serialize("useLightmapAsShadowmap")
  30835. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  30836. __decorate([
  30837. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30838. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  30839. __decorate([
  30840. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  30841. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  30842. __decorate([
  30843. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  30844. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  30845. __decorate([
  30846. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  30847. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  30848. __decorate([
  30849. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  30850. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  30851. __decorate([
  30852. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  30853. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  30854. __decorate([
  30855. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  30856. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  30857. __decorate([
  30858. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  30859. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  30860. __decorate([
  30861. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  30862. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  30863. __decorate([
  30864. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  30865. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  30866. __decorate([
  30867. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  30868. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  30869. __decorate([
  30870. BABYLON.serialize("useReflectionFresnelFromSpecular")
  30871. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  30872. __decorate([
  30873. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  30874. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  30875. __decorate([
  30876. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  30877. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  30878. __decorate([
  30879. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30880. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  30881. __decorate([
  30882. BABYLON.serialize("maxSimultaneousLights")
  30883. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  30884. __decorate([
  30885. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  30886. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  30887. __decorate([
  30888. BABYLON.serialize("invertNormalMapX")
  30889. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  30890. __decorate([
  30891. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30892. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  30893. __decorate([
  30894. BABYLON.serialize("invertNormalMapY")
  30895. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  30896. __decorate([
  30897. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30898. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  30899. __decorate([
  30900. BABYLON.serialize("twoSidedLighting")
  30901. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  30902. __decorate([
  30903. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30904. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  30905. __decorate([
  30906. BABYLON.serialize()
  30907. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  30908. BABYLON.StandardMaterial = StandardMaterial;
  30909. })(BABYLON || (BABYLON = {}));
  30910. //# sourceMappingURL=babylon.standardMaterial.js.map
  30911. var BABYLON;
  30912. (function (BABYLON) {
  30913. var PBRMaterialDefines = (function (_super) {
  30914. __extends(PBRMaterialDefines, _super);
  30915. function PBRMaterialDefines() {
  30916. var _this = _super.call(this) || this;
  30917. _this.PBR = true;
  30918. _this.MAINUV1 = false;
  30919. _this.MAINUV2 = false;
  30920. _this.UV1 = false;
  30921. _this.UV2 = false;
  30922. _this.ALBEDO = false;
  30923. _this.ALBEDODIRECTUV = 0;
  30924. _this.VERTEXCOLOR = false;
  30925. _this.AMBIENT = false;
  30926. _this.AMBIENTDIRECTUV = 0;
  30927. _this.AMBIENTINGRAYSCALE = false;
  30928. _this.OPACITY = false;
  30929. _this.VERTEXALPHA = false;
  30930. _this.OPACITYDIRECTUV = 0;
  30931. _this.OPACITYRGB = false;
  30932. _this.ALPHATEST = false;
  30933. _this.ALPHABLEND = false;
  30934. _this.ALPHAFROMALBEDO = false;
  30935. _this.ALPHATESTVALUE = 0.5;
  30936. _this.SPECULAROVERALPHA = false;
  30937. _this.RADIANCEOVERALPHA = false;
  30938. _this.ALPHAFRESNEL = false;
  30939. _this.PREMULTIPLYALPHA = false;
  30940. _this.EMISSIVE = false;
  30941. _this.EMISSIVEDIRECTUV = 0;
  30942. _this.REFLECTIVITY = false;
  30943. _this.REFLECTIVITYDIRECTUV = 0;
  30944. _this.SPECULARTERM = false;
  30945. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  30946. _this.MICROSURFACEAUTOMATIC = false;
  30947. _this.LODBASEDMICROSFURACE = false;
  30948. _this.MICROSURFACEMAP = false;
  30949. _this.MICROSURFACEMAPDIRECTUV = 0;
  30950. _this.METALLICWORKFLOW = false;
  30951. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  30952. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  30953. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  30954. _this.AOSTOREINMETALMAPRED = false;
  30955. _this.ENVIRONMENTBRDF = false;
  30956. _this.NORMAL = false;
  30957. _this.TANGENT = false;
  30958. _this.BUMP = false;
  30959. _this.BUMPDIRECTUV = 0;
  30960. _this.PARALLAX = false;
  30961. _this.PARALLAXOCCLUSION = false;
  30962. _this.NORMALXYSCALE = true;
  30963. _this.LIGHTMAP = false;
  30964. _this.LIGHTMAPDIRECTUV = 0;
  30965. _this.USELIGHTMAPASSHADOWMAP = false;
  30966. _this.REFLECTION = false;
  30967. _this.REFLECTIONMAP_3D = false;
  30968. _this.REFLECTIONMAP_SPHERICAL = false;
  30969. _this.REFLECTIONMAP_PLANAR = false;
  30970. _this.REFLECTIONMAP_CUBIC = false;
  30971. _this.REFLECTIONMAP_PROJECTION = false;
  30972. _this.REFLECTIONMAP_SKYBOX = false;
  30973. _this.REFLECTIONMAP_EXPLICIT = false;
  30974. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  30975. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  30976. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  30977. _this.INVERTCUBICMAP = false;
  30978. _this.USESPHERICALFROMREFLECTIONMAP = false;
  30979. _this.USESPHERICALINFRAGMENT = false;
  30980. _this.REFLECTIONMAP_OPPOSITEZ = false;
  30981. _this.LODINREFLECTIONALPHA = false;
  30982. _this.GAMMAREFLECTION = false;
  30983. _this.REFRACTION = false;
  30984. _this.REFRACTIONMAP_3D = false;
  30985. _this.REFRACTIONMAP_OPPOSITEZ = false;
  30986. _this.LODINREFRACTIONALPHA = false;
  30987. _this.GAMMAREFRACTION = false;
  30988. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  30989. _this.INSTANCES = false;
  30990. _this.NUM_BONE_INFLUENCERS = 0;
  30991. _this.BonesPerMesh = 0;
  30992. _this.MORPHTARGETS = false;
  30993. _this.MORPHTARGETS_NORMAL = false;
  30994. _this.MORPHTARGETS_TANGENT = false;
  30995. _this.NUM_MORPH_INFLUENCERS = 0;
  30996. _this.IMAGEPROCESSING = false;
  30997. _this.VIGNETTE = false;
  30998. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  30999. _this.VIGNETTEBLENDMODEOPAQUE = false;
  31000. _this.TONEMAPPING = false;
  31001. _this.CONTRAST = false;
  31002. _this.COLORCURVES = false;
  31003. _this.COLORGRADING = false;
  31004. _this.SAMPLER3DGREENDEPTH = false;
  31005. _this.SAMPLER3DBGRMAP = false;
  31006. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  31007. _this.EXPOSURE = false;
  31008. _this.USEPHYSICALLIGHTFALLOFF = false;
  31009. _this.TWOSIDEDLIGHTING = false;
  31010. _this.SHADOWFLOAT = false;
  31011. _this.USERIGHTHANDEDSYSTEM = false;
  31012. _this.CLIPPLANE = false;
  31013. _this.POINTSIZE = false;
  31014. _this.FOG = false;
  31015. _this.LOGARITHMICDEPTH = false;
  31016. _this.FORCENORMALFORWARD = false;
  31017. _this.rebuild();
  31018. return _this;
  31019. }
  31020. PBRMaterialDefines.prototype.reset = function () {
  31021. _super.prototype.reset.call(this);
  31022. this.ALPHATESTVALUE = 0.5;
  31023. this.PBR = true;
  31024. };
  31025. return PBRMaterialDefines;
  31026. }(BABYLON.MaterialDefines));
  31027. /**
  31028. * The Physically based material base class of BJS.
  31029. *
  31030. * This offers the main features of a standard PBR material.
  31031. * For more information, please refer to the documentation :
  31032. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  31033. */
  31034. var PBRBaseMaterial = (function (_super) {
  31035. __extends(PBRBaseMaterial, _super);
  31036. /**
  31037. * Instantiates a new PBRMaterial instance.
  31038. *
  31039. * @param name The material name
  31040. * @param scene The scene the material will be use in.
  31041. */
  31042. function PBRBaseMaterial(name, scene) {
  31043. var _this = _super.call(this, name, scene) || this;
  31044. /**
  31045. * Intensity of the direct lights e.g. the four lights available in your scene.
  31046. * This impacts both the direct diffuse and specular highlights.
  31047. */
  31048. _this._directIntensity = 1.0;
  31049. /**
  31050. * Intensity of the emissive part of the material.
  31051. * This helps controlling the emissive effect without modifying the emissive color.
  31052. */
  31053. _this._emissiveIntensity = 1.0;
  31054. /**
  31055. * Intensity of the environment e.g. how much the environment will light the object
  31056. * either through harmonics for rough material or through the refelction for shiny ones.
  31057. */
  31058. _this._environmentIntensity = 1.0;
  31059. /**
  31060. * This is a special control allowing the reduction of the specular highlights coming from the
  31061. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  31062. */
  31063. _this._specularIntensity = 1.0;
  31064. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  31065. /**
  31066. * Debug Control allowing disabling the bump map on this material.
  31067. */
  31068. _this._disableBumpMap = false;
  31069. /**
  31070. * AKA Occlusion Texture Intensity in other nomenclature.
  31071. */
  31072. _this._ambientTextureStrength = 1.0;
  31073. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  31074. /**
  31075. * AKA Diffuse Color in other nomenclature.
  31076. */
  31077. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  31078. /**
  31079. * AKA Specular Color in other nomenclature.
  31080. */
  31081. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  31082. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  31083. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  31084. /**
  31085. * AKA Glossiness in other nomenclature.
  31086. */
  31087. _this._microSurface = 0.9;
  31088. /**
  31089. * source material index of refraction (IOR)' / 'destination material IOR.
  31090. */
  31091. _this._indexOfRefraction = 0.66;
  31092. /**
  31093. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  31094. */
  31095. _this._invertRefractionY = false;
  31096. /**
  31097. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  31098. * Materials half opaque for instance using refraction could benefit from this control.
  31099. */
  31100. _this._linkRefractionWithTransparency = false;
  31101. _this._useLightmapAsShadowmap = false;
  31102. /**
  31103. * Specifies that the alpha is coming form the albedo channel alpha channel.
  31104. */
  31105. _this._useAlphaFromAlbedoTexture = false;
  31106. /**
  31107. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  31108. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  31109. */
  31110. _this._useSpecularOverAlpha = true;
  31111. /**
  31112. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  31113. */
  31114. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  31115. /**
  31116. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  31117. */
  31118. _this._useRoughnessFromMetallicTextureAlpha = true;
  31119. /**
  31120. * Specifies if the metallic texture contains the roughness information in its green channel.
  31121. */
  31122. _this._useRoughnessFromMetallicTextureGreen = false;
  31123. /**
  31124. * Specifies if the metallic texture contains the metallness information in its blue channel.
  31125. */
  31126. _this._useMetallnessFromMetallicTextureBlue = false;
  31127. /**
  31128. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  31129. */
  31130. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  31131. /**
  31132. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  31133. */
  31134. _this._useAmbientInGrayScale = false;
  31135. /**
  31136. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  31137. * The material will try to infer what glossiness each pixel should be.
  31138. */
  31139. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  31140. /**
  31141. * BJS is using an harcoded light falloff based on a manually sets up range.
  31142. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  31143. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  31144. */
  31145. _this._usePhysicalLightFalloff = true;
  31146. /**
  31147. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  31148. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  31149. */
  31150. _this._useRadianceOverAlpha = true;
  31151. /**
  31152. * Allows using the bump map in parallax mode.
  31153. */
  31154. _this._useParallax = false;
  31155. /**
  31156. * Allows using the bump map in parallax occlusion mode.
  31157. */
  31158. _this._useParallaxOcclusion = false;
  31159. /**
  31160. * Controls the scale bias of the parallax mode.
  31161. */
  31162. _this._parallaxScaleBias = 0.05;
  31163. /**
  31164. * If sets to true, disables all the lights affecting the material.
  31165. */
  31166. _this._disableLighting = false;
  31167. /**
  31168. * Number of Simultaneous lights allowed on the material.
  31169. */
  31170. _this._maxSimultaneousLights = 4;
  31171. /**
  31172. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  31173. */
  31174. _this._invertNormalMapX = false;
  31175. /**
  31176. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  31177. */
  31178. _this._invertNormalMapY = false;
  31179. /**
  31180. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  31181. */
  31182. _this._twoSidedLighting = false;
  31183. /**
  31184. * Defines the alpha limits in alpha test mode.
  31185. */
  31186. _this._alphaCutOff = 0.4;
  31187. /**
  31188. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  31189. */
  31190. _this._forceAlphaTest = false;
  31191. /**
  31192. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  31193. * in your scene composition.
  31194. */
  31195. _this._preMultiplyAlpha = false;
  31196. /**
  31197. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  31198. * And/Or occlude the blended part.
  31199. */
  31200. _this._useAlphaFresnel = false;
  31201. /**
  31202. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  31203. * from cos thetav and roughness:
  31204. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  31205. */
  31206. _this._environmentBRDFTexture = null;
  31207. /**
  31208. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  31209. */
  31210. _this._forceIrradianceInFragment = false;
  31211. /**
  31212. * Force normal to face away from face.
  31213. * (Temporary internal fix to remove before 3.1)
  31214. */
  31215. _this._forceNormalForward = false;
  31216. _this._renderTargets = new BABYLON.SmartArray(16);
  31217. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  31218. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  31219. _this._tempColor = new BABYLON.Color3();
  31220. // Setup the default processing configuration to the scene.
  31221. _this._attachImageProcessingConfiguration(null);
  31222. _this.getRenderTargetTextures = function () {
  31223. _this._renderTargets.reset();
  31224. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  31225. _this._renderTargets.push(_this._reflectionTexture);
  31226. }
  31227. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  31228. _this._renderTargets.push(_this._refractionTexture);
  31229. }
  31230. return _this._renderTargets;
  31231. };
  31232. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  31233. return _this;
  31234. }
  31235. /**
  31236. * Attaches a new image processing configuration to the PBR Material.
  31237. * @param configuration
  31238. */
  31239. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  31240. var _this = this;
  31241. if (configuration === this._imageProcessingConfiguration) {
  31242. return;
  31243. }
  31244. // Detaches observer.
  31245. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  31246. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  31247. }
  31248. // Pick the scene configuration if needed.
  31249. if (!configuration) {
  31250. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  31251. }
  31252. else {
  31253. this._imageProcessingConfiguration = configuration;
  31254. }
  31255. // Attaches observer.
  31256. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  31257. _this._markAllSubMeshesAsImageProcessingDirty();
  31258. });
  31259. };
  31260. PBRBaseMaterial.prototype.getClassName = function () {
  31261. return "PBRBaseMaterial";
  31262. };
  31263. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  31264. get: function () {
  31265. return this._useLogarithmicDepth;
  31266. },
  31267. set: function (value) {
  31268. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  31269. },
  31270. enumerable: true,
  31271. configurable: true
  31272. });
  31273. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  31274. if (this._linkRefractionWithTransparency) {
  31275. return false;
  31276. }
  31277. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  31278. };
  31279. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  31280. if (this._forceAlphaTest) {
  31281. return true;
  31282. }
  31283. if (this._linkRefractionWithTransparency) {
  31284. return false;
  31285. }
  31286. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  31287. };
  31288. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  31289. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  31290. };
  31291. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  31292. return this._albedoTexture;
  31293. };
  31294. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31295. if (this.isFrozen) {
  31296. if (this._wasPreviouslyReady) {
  31297. return true;
  31298. }
  31299. }
  31300. if (!subMesh._materialDefines) {
  31301. subMesh._materialDefines = new PBRMaterialDefines();
  31302. }
  31303. var scene = this.getScene();
  31304. var defines = subMesh._materialDefines;
  31305. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  31306. if (defines._renderId === scene.getRenderId()) {
  31307. return true;
  31308. }
  31309. }
  31310. var engine = scene.getEngine();
  31311. // Lights
  31312. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  31313. defines._needNormals = true;
  31314. // Textures
  31315. if (defines._areTexturesDirty) {
  31316. defines._needUVs = false;
  31317. if (scene.texturesEnabled) {
  31318. if (scene.getEngine().getCaps().textureLOD) {
  31319. defines.LODBASEDMICROSFURACE = true;
  31320. }
  31321. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  31322. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  31323. return false;
  31324. }
  31325. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  31326. }
  31327. else {
  31328. defines.ALBEDO = false;
  31329. }
  31330. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  31331. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  31332. return false;
  31333. }
  31334. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  31335. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  31336. }
  31337. else {
  31338. defines.AMBIENT = false;
  31339. }
  31340. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  31341. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  31342. return false;
  31343. }
  31344. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  31345. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  31346. }
  31347. else {
  31348. defines.OPACITY = false;
  31349. }
  31350. var reflectionTexture = this._getReflectionTexture();
  31351. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  31352. if (!reflectionTexture.isReadyOrNotBlocking()) {
  31353. return false;
  31354. }
  31355. defines.REFLECTION = true;
  31356. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  31357. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  31358. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  31359. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  31360. defines.INVERTCUBICMAP = true;
  31361. }
  31362. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  31363. switch (reflectionTexture.coordinatesMode) {
  31364. case BABYLON.Texture.CUBIC_MODE:
  31365. case BABYLON.Texture.INVCUBIC_MODE:
  31366. defines.REFLECTIONMAP_CUBIC = true;
  31367. break;
  31368. case BABYLON.Texture.EXPLICIT_MODE:
  31369. defines.REFLECTIONMAP_EXPLICIT = true;
  31370. break;
  31371. case BABYLON.Texture.PLANAR_MODE:
  31372. defines.REFLECTIONMAP_PLANAR = true;
  31373. break;
  31374. case BABYLON.Texture.PROJECTION_MODE:
  31375. defines.REFLECTIONMAP_PROJECTION = true;
  31376. break;
  31377. case BABYLON.Texture.SKYBOX_MODE:
  31378. defines.REFLECTIONMAP_SKYBOX = true;
  31379. break;
  31380. case BABYLON.Texture.SPHERICAL_MODE:
  31381. defines.REFLECTIONMAP_SPHERICAL = true;
  31382. break;
  31383. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  31384. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  31385. break;
  31386. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  31387. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  31388. break;
  31389. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  31390. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  31391. break;
  31392. }
  31393. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  31394. if (reflectionTexture.sphericalPolynomial) {
  31395. defines.USESPHERICALFROMREFLECTIONMAP = true;
  31396. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  31397. defines.USESPHERICALINFRAGMENT = true;
  31398. }
  31399. }
  31400. }
  31401. }
  31402. else {
  31403. defines.REFLECTION = false;
  31404. defines.REFLECTIONMAP_3D = false;
  31405. defines.REFLECTIONMAP_SPHERICAL = false;
  31406. defines.REFLECTIONMAP_PLANAR = false;
  31407. defines.REFLECTIONMAP_CUBIC = false;
  31408. defines.REFLECTIONMAP_PROJECTION = false;
  31409. defines.REFLECTIONMAP_SKYBOX = false;
  31410. defines.REFLECTIONMAP_EXPLICIT = false;
  31411. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  31412. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  31413. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  31414. defines.INVERTCUBICMAP = false;
  31415. defines.USESPHERICALFROMREFLECTIONMAP = false;
  31416. defines.USESPHERICALINFRAGMENT = false;
  31417. defines.REFLECTIONMAP_OPPOSITEZ = false;
  31418. defines.LODINREFLECTIONALPHA = false;
  31419. defines.GAMMAREFLECTION = false;
  31420. }
  31421. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  31422. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  31423. return false;
  31424. }
  31425. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  31426. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  31427. }
  31428. else {
  31429. defines.LIGHTMAP = false;
  31430. }
  31431. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  31432. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  31433. return false;
  31434. }
  31435. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  31436. }
  31437. else {
  31438. defines.EMISSIVE = false;
  31439. }
  31440. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  31441. if (this._metallicTexture) {
  31442. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  31443. return false;
  31444. }
  31445. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  31446. defines.METALLICWORKFLOW = true;
  31447. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  31448. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  31449. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  31450. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  31451. }
  31452. else if (this._reflectivityTexture) {
  31453. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  31454. return false;
  31455. }
  31456. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  31457. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  31458. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  31459. }
  31460. else {
  31461. defines.REFLECTIVITY = false;
  31462. }
  31463. if (this._microSurfaceTexture) {
  31464. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  31465. return false;
  31466. }
  31467. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  31468. }
  31469. else {
  31470. defines.MICROSURFACEMAP = false;
  31471. }
  31472. }
  31473. else {
  31474. defines.REFLECTIVITY = false;
  31475. defines.MICROSURFACEMAP = false;
  31476. }
  31477. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  31478. // Bump texure can not be none blocking.
  31479. if (!this._bumpTexture.isReady()) {
  31480. return false;
  31481. }
  31482. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  31483. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  31484. defines.PARALLAX = true;
  31485. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  31486. }
  31487. else {
  31488. defines.PARALLAX = false;
  31489. }
  31490. defines.USERIGHTHANDEDSYSTEM = scene.useRightHandedSystem;
  31491. }
  31492. else {
  31493. defines.BUMP = false;
  31494. }
  31495. var refractionTexture = this._getRefractionTexture();
  31496. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  31497. if (!refractionTexture.isReadyOrNotBlocking()) {
  31498. return false;
  31499. }
  31500. defines.REFRACTION = true;
  31501. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  31502. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  31503. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  31504. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  31505. if (this._linkRefractionWithTransparency) {
  31506. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  31507. }
  31508. }
  31509. else {
  31510. defines.REFRACTION = false;
  31511. }
  31512. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  31513. // This is blocking.
  31514. if (!this._environmentBRDFTexture.isReady()) {
  31515. return false;
  31516. }
  31517. defines.ENVIRONMENTBRDF = true;
  31518. }
  31519. if (this._shouldUseAlphaFromAlbedoTexture()) {
  31520. defines.ALPHAFROMALBEDO = true;
  31521. }
  31522. }
  31523. if (this._useSpecularOverAlpha) {
  31524. defines.SPECULAROVERALPHA = true;
  31525. }
  31526. if (this._usePhysicalLightFalloff) {
  31527. defines.USEPHYSICALLIGHTFALLOFF = true;
  31528. }
  31529. if (this._useRadianceOverAlpha) {
  31530. defines.RADIANCEOVERALPHA = true;
  31531. }
  31532. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  31533. defines.METALLICWORKFLOW = true;
  31534. }
  31535. if (!this.backFaceCulling && this._twoSidedLighting) {
  31536. defines.TWOSIDEDLIGHTING = true;
  31537. }
  31538. defines.ALPHATESTVALUE = this._alphaCutOff;
  31539. defines.PREMULTIPLYALPHA = this._preMultiplyAlpha;
  31540. defines.ALPHABLEND = this.needAlphaBlending();
  31541. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  31542. }
  31543. if (defines._areImageProcessingDirty) {
  31544. if (!this._imageProcessingConfiguration.isReady()) {
  31545. return false;
  31546. }
  31547. this._imageProcessingConfiguration.prepareDefines(defines);
  31548. }
  31549. defines.FORCENORMALFORWARD = this._forceNormalForward;
  31550. // Misc.
  31551. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  31552. // Values that need to be evaluated on every frame
  31553. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._forceAlphaTest);
  31554. // Attribs
  31555. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true)) {
  31556. if (mesh) {
  31557. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31558. mesh.createNormals(true);
  31559. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  31560. }
  31561. }
  31562. }
  31563. // Get correct effect
  31564. if (defines.isDirty) {
  31565. defines.markAsProcessed();
  31566. scene.resetCachedMaterial();
  31567. // Fallbacks
  31568. var fallbacks = new BABYLON.EffectFallbacks();
  31569. if (defines.ENVIRONMENTBRDF) {
  31570. fallbacks.addFallback(0, "ENVIRONMENTBRDF");
  31571. }
  31572. if (defines.REFLECTION) {
  31573. fallbacks.addFallback(0, "REFLECTION");
  31574. }
  31575. if (defines.REFRACTION) {
  31576. fallbacks.addFallback(0, "REFRACTION");
  31577. }
  31578. if (defines.REFLECTIVITY) {
  31579. fallbacks.addFallback(0, "REFLECTIVITY");
  31580. }
  31581. if (defines.BUMP) {
  31582. fallbacks.addFallback(0, "BUMP");
  31583. }
  31584. if (defines.PARALLAX) {
  31585. fallbacks.addFallback(1, "PARALLAX");
  31586. }
  31587. if (defines.PARALLAXOCCLUSION) {
  31588. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  31589. }
  31590. if (defines.SPECULAROVERALPHA) {
  31591. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  31592. }
  31593. if (defines.FOG) {
  31594. fallbacks.addFallback(1, "FOG");
  31595. }
  31596. if (defines.POINTSIZE) {
  31597. fallbacks.addFallback(0, "POINTSIZE");
  31598. }
  31599. if (defines.LOGARITHMICDEPTH) {
  31600. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  31601. }
  31602. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  31603. if (defines.SPECULARTERM) {
  31604. fallbacks.addFallback(0, "SPECULARTERM");
  31605. }
  31606. if (defines.NUM_BONE_INFLUENCERS > 0) {
  31607. fallbacks.addCPUSkinningFallback(0, mesh);
  31608. }
  31609. //Attributes
  31610. var attribs = [BABYLON.VertexBuffer.PositionKind];
  31611. if (defines.NORMAL) {
  31612. attribs.push(BABYLON.VertexBuffer.NormalKind);
  31613. }
  31614. if (defines.TANGENT) {
  31615. attribs.push(BABYLON.VertexBuffer.TangentKind);
  31616. }
  31617. if (defines.UV1) {
  31618. attribs.push(BABYLON.VertexBuffer.UVKind);
  31619. }
  31620. if (defines.UV2) {
  31621. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31622. }
  31623. if (defines.VERTEXCOLOR) {
  31624. attribs.push(BABYLON.VertexBuffer.ColorKind);
  31625. }
  31626. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  31627. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  31628. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  31629. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  31630. "vFogInfos", "vFogColor", "pointSize",
  31631. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  31632. "mBones",
  31633. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  31634. "vLightingIntensity",
  31635. "logarithmicDepthConstant",
  31636. "vSphericalX", "vSphericalY", "vSphericalZ",
  31637. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  31638. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  31639. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  31640. "vNormalReoderParams"
  31641. ];
  31642. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  31643. "bumpSampler", "lightmapSampler", "opacitySampler",
  31644. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  31645. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  31646. "microSurfaceSampler", "environmentBrdfSampler"];
  31647. var uniformBuffers = ["Material", "Scene"];
  31648. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  31649. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  31650. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  31651. uniformsNames: uniforms,
  31652. uniformBuffersNames: uniformBuffers,
  31653. samplers: samplers,
  31654. defines: defines,
  31655. maxSimultaneousLights: this._maxSimultaneousLights
  31656. });
  31657. var onCompiled = function (effect) {
  31658. if (this.onCompiled) {
  31659. this.onCompiled(effect);
  31660. }
  31661. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  31662. }.bind(this);
  31663. var join = defines.toString();
  31664. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  31665. attributes: attribs,
  31666. uniformsNames: uniforms,
  31667. uniformBuffersNames: uniformBuffers,
  31668. samplers: samplers,
  31669. defines: join,
  31670. fallbacks: fallbacks,
  31671. onCompiled: onCompiled,
  31672. onError: this.onError,
  31673. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  31674. }, engine), defines);
  31675. this.buildUniformLayout();
  31676. }
  31677. if (!subMesh.effect.isReady()) {
  31678. return false;
  31679. }
  31680. defines._renderId = scene.getRenderId();
  31681. this._wasPreviouslyReady = true;
  31682. return true;
  31683. };
  31684. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  31685. // Order is important !
  31686. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  31687. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  31688. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  31689. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  31690. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  31691. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  31692. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  31693. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  31694. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  31695. this._uniformBuffer.addUniform("vBumpInfos", 3);
  31696. this._uniformBuffer.addUniform("albedoMatrix", 16);
  31697. this._uniformBuffer.addUniform("ambientMatrix", 16);
  31698. this._uniformBuffer.addUniform("opacityMatrix", 16);
  31699. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  31700. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  31701. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  31702. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  31703. this._uniformBuffer.addUniform("bumpMatrix", 16);
  31704. this._uniformBuffer.addUniform("vNormalReoderParams", 4);
  31705. this._uniformBuffer.addUniform("refractionMatrix", 16);
  31706. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  31707. this._uniformBuffer.addUniform("vReflectionColor", 3);
  31708. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  31709. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  31710. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  31711. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  31712. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  31713. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  31714. this._uniformBuffer.addUniform("pointSize", 1);
  31715. this._uniformBuffer.create();
  31716. };
  31717. PBRBaseMaterial.prototype.unbind = function () {
  31718. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  31719. this._uniformBuffer.setTexture("reflectionSampler", null);
  31720. }
  31721. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  31722. this._uniformBuffer.setTexture("refractionSampler", null);
  31723. }
  31724. _super.prototype.unbind.call(this);
  31725. };
  31726. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  31727. this._activeEffect.setMatrix("world", world);
  31728. };
  31729. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31730. var scene = this.getScene();
  31731. var defines = subMesh._materialDefines;
  31732. if (!defines) {
  31733. return;
  31734. }
  31735. var effect = subMesh.effect;
  31736. this._activeEffect = effect;
  31737. // Matrices
  31738. this.bindOnlyWorldMatrix(world);
  31739. // Bones
  31740. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  31741. if (this._mustRebind(scene, effect, mesh.visibility)) {
  31742. this._uniformBuffer.bindToEffect(effect, "Material");
  31743. this.bindViewProjection(effect);
  31744. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  31745. // Texture uniforms
  31746. if (scene.texturesEnabled) {
  31747. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  31748. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  31749. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  31750. }
  31751. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  31752. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  31753. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  31754. }
  31755. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  31756. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  31757. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  31758. }
  31759. var reflectionTexture = this._getReflectionTexture();
  31760. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  31761. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  31762. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  31763. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  31764. var polynomials = reflectionTexture.sphericalPolynomial;
  31765. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  31766. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  31767. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  31768. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  31769. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  31770. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  31771. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  31772. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  31773. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  31774. }
  31775. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  31776. }
  31777. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  31778. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  31779. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  31780. }
  31781. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  31782. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  31783. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  31784. }
  31785. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  31786. if (this._metallicTexture) {
  31787. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  31788. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  31789. }
  31790. else if (this._reflectivityTexture) {
  31791. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  31792. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  31793. }
  31794. if (this._microSurfaceTexture) {
  31795. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  31796. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  31797. }
  31798. }
  31799. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  31800. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  31801. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  31802. if (scene._mirroredCameraPosition) {
  31803. 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);
  31804. }
  31805. else {
  31806. 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);
  31807. }
  31808. }
  31809. var refractionTexture = this._getRefractionTexture();
  31810. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  31811. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  31812. var depth = 1.0;
  31813. if (!refractionTexture.isCube) {
  31814. if (refractionTexture.depth) {
  31815. depth = refractionTexture.depth;
  31816. }
  31817. }
  31818. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  31819. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  31820. }
  31821. }
  31822. // Point size
  31823. if (this.pointsCloud) {
  31824. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  31825. }
  31826. // Colors
  31827. if (defines.METALLICWORKFLOW) {
  31828. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  31829. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  31830. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  31831. }
  31832. else {
  31833. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  31834. }
  31835. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  31836. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  31837. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  31838. // Misc
  31839. this._lightingInfos.x = this._directIntensity;
  31840. this._lightingInfos.y = this._emissiveIntensity;
  31841. this._lightingInfos.z = this._environmentIntensity;
  31842. this._lightingInfos.w = this._specularIntensity;
  31843. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  31844. }
  31845. // Textures
  31846. if (scene.texturesEnabled) {
  31847. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  31848. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  31849. }
  31850. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  31851. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  31852. }
  31853. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  31854. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  31855. }
  31856. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  31857. if (defines.LODBASEDMICROSFURACE) {
  31858. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  31859. }
  31860. else {
  31861. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  31862. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  31863. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  31864. }
  31865. }
  31866. if (defines.ENVIRONMENTBRDF) {
  31867. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  31868. }
  31869. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  31870. if (defines.LODBASEDMICROSFURACE) {
  31871. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  31872. }
  31873. else {
  31874. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  31875. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  31876. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  31877. }
  31878. }
  31879. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  31880. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  31881. }
  31882. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  31883. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  31884. }
  31885. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  31886. if (this._metallicTexture) {
  31887. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  31888. }
  31889. else if (this._reflectivityTexture) {
  31890. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  31891. }
  31892. if (this._microSurfaceTexture) {
  31893. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  31894. }
  31895. }
  31896. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  31897. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  31898. }
  31899. }
  31900. // Clip plane
  31901. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  31902. // Colors
  31903. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  31904. var eyePosition = scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition;
  31905. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, scene._mirroredCameraPosition ? -1 : 1);
  31906. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  31907. }
  31908. if (this._mustRebind(scene, effect) || !this.isFrozen) {
  31909. // Lights
  31910. if (scene.lightsEnabled && !this._disableLighting) {
  31911. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  31912. }
  31913. // View
  31914. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  31915. this.bindView(effect);
  31916. }
  31917. // Fog
  31918. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  31919. // Morph targets
  31920. if (defines.NUM_MORPH_INFLUENCERS) {
  31921. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  31922. }
  31923. // image processing
  31924. this._imageProcessingConfiguration.bind(this._activeEffect);
  31925. // Log. depth
  31926. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  31927. }
  31928. this._uniformBuffer.update();
  31929. this._afterBind(mesh);
  31930. scene = null;
  31931. };
  31932. PBRBaseMaterial.prototype.getAnimatables = function () {
  31933. var results = [];
  31934. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  31935. results.push(this._albedoTexture);
  31936. }
  31937. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  31938. results.push(this._ambientTexture);
  31939. }
  31940. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  31941. results.push(this._opacityTexture);
  31942. }
  31943. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  31944. results.push(this._reflectionTexture);
  31945. }
  31946. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  31947. results.push(this._emissiveTexture);
  31948. }
  31949. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  31950. results.push(this._metallicTexture);
  31951. }
  31952. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  31953. results.push(this._reflectivityTexture);
  31954. }
  31955. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  31956. results.push(this._bumpTexture);
  31957. }
  31958. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  31959. results.push(this._lightmapTexture);
  31960. }
  31961. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  31962. results.push(this._refractionTexture);
  31963. }
  31964. return results;
  31965. };
  31966. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  31967. if (this._reflectionTexture) {
  31968. return this._reflectionTexture;
  31969. }
  31970. return this.getScene().environmentTexture;
  31971. };
  31972. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  31973. if (this._refractionTexture) {
  31974. return this._refractionTexture;
  31975. }
  31976. if (this._linkRefractionWithTransparency) {
  31977. return this.getScene().environmentTexture;
  31978. }
  31979. return null;
  31980. };
  31981. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31982. if (forceDisposeTextures) {
  31983. if (this._albedoTexture) {
  31984. this._albedoTexture.dispose();
  31985. }
  31986. if (this._ambientTexture) {
  31987. this._ambientTexture.dispose();
  31988. }
  31989. if (this._opacityTexture) {
  31990. this._opacityTexture.dispose();
  31991. }
  31992. if (this._reflectionTexture) {
  31993. this._reflectionTexture.dispose();
  31994. }
  31995. if (this._environmentBRDFTexture) {
  31996. this._environmentBRDFTexture.dispose();
  31997. }
  31998. if (this._emissiveTexture) {
  31999. this._emissiveTexture.dispose();
  32000. }
  32001. if (this._metallicTexture) {
  32002. this._metallicTexture.dispose();
  32003. }
  32004. if (this._reflectivityTexture) {
  32005. this._reflectivityTexture.dispose();
  32006. }
  32007. if (this._bumpTexture) {
  32008. this._bumpTexture.dispose();
  32009. }
  32010. if (this._lightmapTexture) {
  32011. this._lightmapTexture.dispose();
  32012. }
  32013. if (this._refractionTexture) {
  32014. this._refractionTexture.dispose();
  32015. }
  32016. }
  32017. this._renderTargets.dispose();
  32018. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  32019. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  32020. }
  32021. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  32022. };
  32023. return PBRBaseMaterial;
  32024. }(BABYLON.PushMaterial));
  32025. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  32026. __decorate([
  32027. BABYLON.serializeAsImageProcessingConfiguration()
  32028. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  32029. __decorate([
  32030. BABYLON.serialize()
  32031. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  32032. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  32033. })(BABYLON || (BABYLON = {}));
  32034. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  32035. var BABYLON;
  32036. (function (BABYLON) {
  32037. var Internals;
  32038. (function (Internals) {
  32039. /**
  32040. * The Physically based simple base material of BJS.
  32041. *
  32042. * This enables better naming and convention enforcements on top of the pbrMaterial.
  32043. * It is used as the base class for both the specGloss and metalRough conventions.
  32044. */
  32045. var PBRBaseSimpleMaterial = (function (_super) {
  32046. __extends(PBRBaseSimpleMaterial, _super);
  32047. /**
  32048. * Instantiates a new PBRMaterial instance.
  32049. *
  32050. * @param name The material name
  32051. * @param scene The scene the material will be use in.
  32052. */
  32053. function PBRBaseSimpleMaterial(name, scene) {
  32054. var _this = _super.call(this, name, scene) || this;
  32055. /**
  32056. * Number of Simultaneous lights allowed on the material.
  32057. */
  32058. _this.maxSimultaneousLights = 4;
  32059. /**
  32060. * If sets to true, disables all the lights affecting the material.
  32061. */
  32062. _this.disableLighting = false;
  32063. /**
  32064. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  32065. */
  32066. _this.invertNormalMapX = false;
  32067. /**
  32068. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  32069. */
  32070. _this.invertNormalMapY = false;
  32071. /**
  32072. * Emissivie color used to self-illuminate the model.
  32073. */
  32074. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  32075. /**
  32076. * Occlusion Channel Strenght.
  32077. */
  32078. _this.occlusionStrength = 1.0;
  32079. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  32080. _this._useAmbientInGrayScale = true;
  32081. return _this;
  32082. }
  32083. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  32084. /**
  32085. * Gets the current transparency mode.
  32086. */
  32087. get: function () {
  32088. return this._transparencyMode;
  32089. },
  32090. /**
  32091. * Sets the transparency mode of the material.
  32092. */
  32093. set: function (value) {
  32094. if (this._transparencyMode === value) {
  32095. return;
  32096. }
  32097. this._transparencyMode = value;
  32098. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  32099. this._forceAlphaTest = true;
  32100. }
  32101. else {
  32102. this._forceAlphaTest = false;
  32103. }
  32104. this._markAllSubMeshesAsTexturesDirty();
  32105. },
  32106. enumerable: true,
  32107. configurable: true
  32108. });
  32109. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  32110. /**
  32111. * Gets the current double sided mode.
  32112. */
  32113. get: function () {
  32114. return this._twoSidedLighting;
  32115. },
  32116. /**
  32117. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  32118. */
  32119. set: function (value) {
  32120. if (this._twoSidedLighting === value) {
  32121. return;
  32122. }
  32123. this._twoSidedLighting = value;
  32124. this.backFaceCulling = !value;
  32125. this._markAllSubMeshesAsTexturesDirty();
  32126. },
  32127. enumerable: true,
  32128. configurable: true
  32129. });
  32130. /**
  32131. * Specifies wether or not the alpha value of the albedo texture should be used.
  32132. */
  32133. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  32134. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  32135. };
  32136. /**
  32137. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  32138. */
  32139. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  32140. if (this._linkRefractionWithTransparency) {
  32141. return false;
  32142. }
  32143. return (this.alpha < 1.0) ||
  32144. (this._shouldUseAlphaFromAlbedoTexture() &&
  32145. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  32146. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  32147. };
  32148. /**
  32149. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  32150. */
  32151. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  32152. if (this._linkRefractionWithTransparency) {
  32153. return false;
  32154. }
  32155. return this._shouldUseAlphaFromAlbedoTexture() &&
  32156. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  32157. };
  32158. /**
  32159. * Return the active textures of the material.
  32160. */
  32161. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  32162. var activeTextures = _super.prototype.getActiveTextures.call(this);
  32163. if (this.environmentTexture) {
  32164. activeTextures.push(this.environmentTexture);
  32165. }
  32166. if (this.normalTexture) {
  32167. activeTextures.push(this.normalTexture);
  32168. }
  32169. if (this.emissiveTexture) {
  32170. activeTextures.push(this.emissiveTexture);
  32171. }
  32172. if (this.occlusionTexture) {
  32173. activeTextures.push(this.occlusionTexture);
  32174. }
  32175. return activeTextures;
  32176. };
  32177. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  32178. return "PBRBaseSimpleMaterial";
  32179. };
  32180. return PBRBaseSimpleMaterial;
  32181. }(BABYLON.PBRBaseMaterial));
  32182. __decorate([
  32183. BABYLON.serialize(),
  32184. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  32185. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  32186. __decorate([
  32187. BABYLON.serialize(),
  32188. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  32189. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  32190. __decorate([
  32191. BABYLON.serializeAsTexture(),
  32192. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  32193. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  32194. __decorate([
  32195. BABYLON.serialize(),
  32196. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32197. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  32198. __decorate([
  32199. BABYLON.serialize(),
  32200. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32201. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  32202. __decorate([
  32203. BABYLON.serializeAsTexture(),
  32204. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  32205. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  32206. __decorate([
  32207. BABYLON.serializeAsColor3("emissive"),
  32208. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32209. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  32210. __decorate([
  32211. BABYLON.serializeAsTexture(),
  32212. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32213. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  32214. __decorate([
  32215. BABYLON.serialize(),
  32216. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  32217. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  32218. __decorate([
  32219. BABYLON.serializeAsTexture(),
  32220. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  32221. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  32222. __decorate([
  32223. BABYLON.serialize(),
  32224. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  32225. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  32226. __decorate([
  32227. BABYLON.serialize()
  32228. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  32229. __decorate([
  32230. BABYLON.serialize()
  32231. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  32232. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  32233. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  32234. })(BABYLON || (BABYLON = {}));
  32235. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  32236. var BABYLON;
  32237. (function (BABYLON) {
  32238. /**
  32239. * The Physically based material of BJS.
  32240. *
  32241. * This offers the main features of a standard PBR material.
  32242. * For more information, please refer to the documentation :
  32243. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  32244. */
  32245. var PBRMaterial = (function (_super) {
  32246. __extends(PBRMaterial, _super);
  32247. /**
  32248. * Instantiates a new PBRMaterial instance.
  32249. *
  32250. * @param name The material name
  32251. * @param scene The scene the material will be use in.
  32252. */
  32253. function PBRMaterial(name, scene) {
  32254. var _this = _super.call(this, name, scene) || this;
  32255. /**
  32256. * Intensity of the direct lights e.g. the four lights available in your scene.
  32257. * This impacts both the direct diffuse and specular highlights.
  32258. */
  32259. _this.directIntensity = 1.0;
  32260. /**
  32261. * Intensity of the emissive part of the material.
  32262. * This helps controlling the emissive effect without modifying the emissive color.
  32263. */
  32264. _this.emissiveIntensity = 1.0;
  32265. /**
  32266. * Intensity of the environment e.g. how much the environment will light the object
  32267. * either through harmonics for rough material or through the refelction for shiny ones.
  32268. */
  32269. _this.environmentIntensity = 1.0;
  32270. /**
  32271. * This is a special control allowing the reduction of the specular highlights coming from the
  32272. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  32273. */
  32274. _this.specularIntensity = 1.0;
  32275. /**
  32276. * Debug Control allowing disabling the bump map on this material.
  32277. */
  32278. _this.disableBumpMap = false;
  32279. /**
  32280. * AKA Occlusion Texture Intensity in other nomenclature.
  32281. */
  32282. _this.ambientTextureStrength = 1.0;
  32283. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  32284. /**
  32285. * AKA Diffuse Color in other nomenclature.
  32286. */
  32287. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  32288. /**
  32289. * AKA Specular Color in other nomenclature.
  32290. */
  32291. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  32292. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  32293. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  32294. /**
  32295. * AKA Glossiness in other nomenclature.
  32296. */
  32297. _this.microSurface = 1.0;
  32298. /**
  32299. * source material index of refraction (IOR)' / 'destination material IOR.
  32300. */
  32301. _this.indexOfRefraction = 0.66;
  32302. /**
  32303. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  32304. */
  32305. _this.invertRefractionY = false;
  32306. /**
  32307. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  32308. * Materials half opaque for instance using refraction could benefit from this control.
  32309. */
  32310. _this.linkRefractionWithTransparency = false;
  32311. _this.useLightmapAsShadowmap = false;
  32312. /**
  32313. * Specifies that the alpha is coming form the albedo channel alpha channel.
  32314. */
  32315. _this.useAlphaFromAlbedoTexture = false;
  32316. /**
  32317. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  32318. */
  32319. _this.forceAlphaTest = false;
  32320. /**
  32321. * Defines the alpha limits in alpha test mode.
  32322. */
  32323. _this.alphaCutOff = 0.4;
  32324. /**
  32325. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  32326. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  32327. */
  32328. _this.useSpecularOverAlpha = true;
  32329. /**
  32330. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  32331. */
  32332. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  32333. /**
  32334. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  32335. */
  32336. _this.useRoughnessFromMetallicTextureAlpha = true;
  32337. /**
  32338. * Specifies if the metallic texture contains the roughness information in its green channel.
  32339. */
  32340. _this.useRoughnessFromMetallicTextureGreen = false;
  32341. /**
  32342. * Specifies if the metallic texture contains the metallness information in its blue channel.
  32343. */
  32344. _this.useMetallnessFromMetallicTextureBlue = false;
  32345. /**
  32346. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  32347. */
  32348. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  32349. /**
  32350. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  32351. */
  32352. _this.useAmbientInGrayScale = false;
  32353. /**
  32354. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  32355. * The material will try to infer what glossiness each pixel should be.
  32356. */
  32357. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  32358. /**
  32359. * BJS is using an harcoded light falloff based on a manually sets up range.
  32360. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  32361. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  32362. */
  32363. _this.usePhysicalLightFalloff = true;
  32364. /**
  32365. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  32366. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  32367. */
  32368. _this.useRadianceOverAlpha = true;
  32369. /**
  32370. * Allows using the bump map in parallax mode.
  32371. */
  32372. _this.useParallax = false;
  32373. /**
  32374. * Allows using the bump map in parallax occlusion mode.
  32375. */
  32376. _this.useParallaxOcclusion = false;
  32377. /**
  32378. * Controls the scale bias of the parallax mode.
  32379. */
  32380. _this.parallaxScaleBias = 0.05;
  32381. /**
  32382. * If sets to true, disables all the lights affecting the material.
  32383. */
  32384. _this.disableLighting = false;
  32385. /**
  32386. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  32387. */
  32388. _this.forceIrradianceInFragment = false;
  32389. /**
  32390. * Number of Simultaneous lights allowed on the material.
  32391. */
  32392. _this.maxSimultaneousLights = 4;
  32393. /**
  32394. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  32395. */
  32396. _this.invertNormalMapX = false;
  32397. /**
  32398. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  32399. */
  32400. _this.invertNormalMapY = false;
  32401. /**
  32402. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  32403. */
  32404. _this.twoSidedLighting = false;
  32405. /**
  32406. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  32407. * in your scene composition.
  32408. */
  32409. _this.preMultiplyAlpha = false;
  32410. /**
  32411. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  32412. * And/Or occlude the blended part.
  32413. */
  32414. _this.useAlphaFresnel = false;
  32415. /**
  32416. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  32417. * And/Or occlude the blended part.
  32418. */
  32419. _this.environmentBRDFTexture = null;
  32420. /**
  32421. * Force normal to face away from face.
  32422. * (Temporary internal fix to remove before 3.1)
  32423. */
  32424. _this.forceNormalForward = false;
  32425. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  32426. return _this;
  32427. }
  32428. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  32429. /**
  32430. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  32431. */
  32432. get: function () {
  32433. return this._PBRMATERIAL_OPAQUE;
  32434. },
  32435. enumerable: true,
  32436. configurable: true
  32437. });
  32438. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  32439. /**
  32440. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  32441. */
  32442. get: function () {
  32443. return this._PBRMATERIAL_ALPHATEST;
  32444. },
  32445. enumerable: true,
  32446. configurable: true
  32447. });
  32448. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  32449. /**
  32450. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  32451. */
  32452. get: function () {
  32453. return this._PBRMATERIAL_ALPHABLEND;
  32454. },
  32455. enumerable: true,
  32456. configurable: true
  32457. });
  32458. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  32459. /**
  32460. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  32461. * They are also discarded below the alpha cutoff threshold to improve performances.
  32462. */
  32463. get: function () {
  32464. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  32465. },
  32466. enumerable: true,
  32467. configurable: true
  32468. });
  32469. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  32470. /**
  32471. * Gets the image processing configuration used either in this material.
  32472. */
  32473. get: function () {
  32474. return this._imageProcessingConfiguration;
  32475. },
  32476. /**
  32477. * Sets the Default image processing configuration used either in the this material.
  32478. *
  32479. * If sets to null, the scene one is in use.
  32480. */
  32481. set: function (value) {
  32482. this._attachImageProcessingConfiguration(value);
  32483. // Ensure the effect will be rebuilt.
  32484. this._markAllSubMeshesAsTexturesDirty();
  32485. },
  32486. enumerable: true,
  32487. configurable: true
  32488. });
  32489. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  32490. /**
  32491. * Gets wether the color curves effect is enabled.
  32492. */
  32493. get: function () {
  32494. return this.imageProcessingConfiguration.colorCurvesEnabled;
  32495. },
  32496. /**
  32497. * Sets wether the color curves effect is enabled.
  32498. */
  32499. set: function (value) {
  32500. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  32501. },
  32502. enumerable: true,
  32503. configurable: true
  32504. });
  32505. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  32506. /**
  32507. * Gets wether the color grading effect is enabled.
  32508. */
  32509. get: function () {
  32510. return this.imageProcessingConfiguration.colorGradingEnabled;
  32511. },
  32512. /**
  32513. * Gets wether the color grading effect is enabled.
  32514. */
  32515. set: function (value) {
  32516. this.imageProcessingConfiguration.colorGradingEnabled = value;
  32517. },
  32518. enumerable: true,
  32519. configurable: true
  32520. });
  32521. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  32522. /**
  32523. * Gets wether tonemapping is enabled or not.
  32524. */
  32525. get: function () {
  32526. return this._imageProcessingConfiguration.toneMappingEnabled;
  32527. },
  32528. /**
  32529. * Sets wether tonemapping is enabled or not
  32530. */
  32531. set: function (value) {
  32532. this._imageProcessingConfiguration.toneMappingEnabled = value;
  32533. },
  32534. enumerable: true,
  32535. configurable: true
  32536. });
  32537. ;
  32538. ;
  32539. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  32540. /**
  32541. * The camera exposure used on this material.
  32542. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  32543. * This corresponds to a photographic exposure.
  32544. */
  32545. get: function () {
  32546. return this._imageProcessingConfiguration.exposure;
  32547. },
  32548. /**
  32549. * The camera exposure used on this material.
  32550. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  32551. * This corresponds to a photographic exposure.
  32552. */
  32553. set: function (value) {
  32554. this._imageProcessingConfiguration.exposure = value;
  32555. },
  32556. enumerable: true,
  32557. configurable: true
  32558. });
  32559. ;
  32560. ;
  32561. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  32562. /**
  32563. * Gets The camera contrast used on this material.
  32564. */
  32565. get: function () {
  32566. return this._imageProcessingConfiguration.contrast;
  32567. },
  32568. /**
  32569. * Sets The camera contrast used on this material.
  32570. */
  32571. set: function (value) {
  32572. this._imageProcessingConfiguration.contrast = value;
  32573. },
  32574. enumerable: true,
  32575. configurable: true
  32576. });
  32577. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  32578. /**
  32579. * Gets the Color Grading 2D Lookup Texture.
  32580. */
  32581. get: function () {
  32582. return this._imageProcessingConfiguration.colorGradingTexture;
  32583. },
  32584. /**
  32585. * Sets the Color Grading 2D Lookup Texture.
  32586. */
  32587. set: function (value) {
  32588. this._imageProcessingConfiguration.colorGradingTexture = value;
  32589. },
  32590. enumerable: true,
  32591. configurable: true
  32592. });
  32593. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  32594. /**
  32595. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  32596. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  32597. * 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;
  32598. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  32599. */
  32600. get: function () {
  32601. return this._imageProcessingConfiguration.colorCurves;
  32602. },
  32603. /**
  32604. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  32605. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  32606. * 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;
  32607. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  32608. */
  32609. set: function (value) {
  32610. this._imageProcessingConfiguration.colorCurves = value;
  32611. },
  32612. enumerable: true,
  32613. configurable: true
  32614. });
  32615. PBRMaterial.prototype.getClassName = function () {
  32616. return "PBRMaterial";
  32617. };
  32618. PBRMaterial.prototype.getActiveTextures = function () {
  32619. var activeTextures = _super.prototype.getActiveTextures.call(this);
  32620. if (this._albedoTexture) {
  32621. activeTextures.push(this._albedoTexture);
  32622. }
  32623. if (this._ambientTexture) {
  32624. activeTextures.push(this._ambientTexture);
  32625. }
  32626. if (this._opacityTexture) {
  32627. activeTextures.push(this._opacityTexture);
  32628. }
  32629. if (this._reflectionTexture) {
  32630. activeTextures.push(this._reflectionTexture);
  32631. }
  32632. if (this._emissiveTexture) {
  32633. activeTextures.push(this._emissiveTexture);
  32634. }
  32635. if (this._reflectivityTexture) {
  32636. activeTextures.push(this._reflectivityTexture);
  32637. }
  32638. if (this._metallicTexture) {
  32639. activeTextures.push(this._metallicTexture);
  32640. }
  32641. if (this._microSurfaceTexture) {
  32642. activeTextures.push(this._microSurfaceTexture);
  32643. }
  32644. if (this._bumpTexture) {
  32645. activeTextures.push(this._bumpTexture);
  32646. }
  32647. if (this._lightmapTexture) {
  32648. activeTextures.push(this._lightmapTexture);
  32649. }
  32650. if (this._refractionTexture) {
  32651. activeTextures.push(this._refractionTexture);
  32652. }
  32653. return activeTextures;
  32654. };
  32655. PBRMaterial.prototype.hasTexture = function (texture) {
  32656. if (_super.prototype.hasTexture.call(this, texture)) {
  32657. return true;
  32658. }
  32659. if (this._albedoTexture === texture) {
  32660. return true;
  32661. }
  32662. if (this._ambientTexture === texture) {
  32663. return true;
  32664. }
  32665. if (this._opacityTexture === texture) {
  32666. return true;
  32667. }
  32668. if (this._reflectionTexture === texture) {
  32669. return true;
  32670. }
  32671. if (this._reflectivityTexture === texture) {
  32672. return true;
  32673. }
  32674. if (this._metallicTexture === texture) {
  32675. return true;
  32676. }
  32677. if (this._microSurfaceTexture === texture) {
  32678. return true;
  32679. }
  32680. if (this._bumpTexture === texture) {
  32681. return true;
  32682. }
  32683. if (this._lightmapTexture === texture) {
  32684. return true;
  32685. }
  32686. if (this._refractionTexture === texture) {
  32687. return true;
  32688. }
  32689. return false;
  32690. };
  32691. PBRMaterial.prototype.clone = function (name) {
  32692. var _this = this;
  32693. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  32694. };
  32695. PBRMaterial.prototype.serialize = function () {
  32696. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  32697. serializationObject.customType = "BABYLON.PBRMaterial";
  32698. return serializationObject;
  32699. };
  32700. // Statics
  32701. PBRMaterial.Parse = function (source, scene, rootUrl) {
  32702. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  32703. };
  32704. return PBRMaterial;
  32705. }(BABYLON.PBRBaseMaterial));
  32706. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  32707. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  32708. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  32709. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  32710. __decorate([
  32711. BABYLON.serialize(),
  32712. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32713. ], PBRMaterial.prototype, "directIntensity", void 0);
  32714. __decorate([
  32715. BABYLON.serialize(),
  32716. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32717. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  32718. __decorate([
  32719. BABYLON.serialize(),
  32720. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32721. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  32722. __decorate([
  32723. BABYLON.serialize(),
  32724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32725. ], PBRMaterial.prototype, "specularIntensity", void 0);
  32726. __decorate([
  32727. BABYLON.serialize(),
  32728. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32729. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  32730. __decorate([
  32731. BABYLON.serializeAsTexture(),
  32732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32733. ], PBRMaterial.prototype, "albedoTexture", void 0);
  32734. __decorate([
  32735. BABYLON.serializeAsTexture(),
  32736. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32737. ], PBRMaterial.prototype, "ambientTexture", void 0);
  32738. __decorate([
  32739. BABYLON.serialize(),
  32740. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32741. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  32742. __decorate([
  32743. BABYLON.serializeAsTexture(),
  32744. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32745. ], PBRMaterial.prototype, "opacityTexture", void 0);
  32746. __decorate([
  32747. BABYLON.serializeAsTexture(),
  32748. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32749. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  32750. __decorate([
  32751. BABYLON.serializeAsTexture(),
  32752. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32753. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  32754. __decorate([
  32755. BABYLON.serializeAsTexture(),
  32756. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32757. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  32758. __decorate([
  32759. BABYLON.serializeAsTexture(),
  32760. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32761. ], PBRMaterial.prototype, "metallicTexture", void 0);
  32762. __decorate([
  32763. BABYLON.serialize(),
  32764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32765. ], PBRMaterial.prototype, "metallic", void 0);
  32766. __decorate([
  32767. BABYLON.serialize(),
  32768. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32769. ], PBRMaterial.prototype, "roughness", void 0);
  32770. __decorate([
  32771. BABYLON.serializeAsTexture(),
  32772. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32773. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  32774. __decorate([
  32775. BABYLON.serializeAsTexture(),
  32776. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32777. ], PBRMaterial.prototype, "bumpTexture", void 0);
  32778. __decorate([
  32779. BABYLON.serializeAsTexture(),
  32780. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  32781. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  32782. __decorate([
  32783. BABYLON.serializeAsTexture(),
  32784. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32785. ], PBRMaterial.prototype, "refractionTexture", void 0);
  32786. __decorate([
  32787. BABYLON.serializeAsColor3("ambient"),
  32788. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32789. ], PBRMaterial.prototype, "ambientColor", void 0);
  32790. __decorate([
  32791. BABYLON.serializeAsColor3("albedo"),
  32792. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32793. ], PBRMaterial.prototype, "albedoColor", void 0);
  32794. __decorate([
  32795. BABYLON.serializeAsColor3("reflectivity"),
  32796. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32797. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  32798. __decorate([
  32799. BABYLON.serializeAsColor3("reflection"),
  32800. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32801. ], PBRMaterial.prototype, "reflectionColor", void 0);
  32802. __decorate([
  32803. BABYLON.serializeAsColor3("emissive"),
  32804. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32805. ], PBRMaterial.prototype, "emissiveColor", void 0);
  32806. __decorate([
  32807. BABYLON.serialize(),
  32808. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32809. ], PBRMaterial.prototype, "microSurface", void 0);
  32810. __decorate([
  32811. BABYLON.serialize(),
  32812. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32813. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  32814. __decorate([
  32815. BABYLON.serialize(),
  32816. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32817. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  32818. __decorate([
  32819. BABYLON.serialize(),
  32820. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32821. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  32822. __decorate([
  32823. BABYLON.serialize(),
  32824. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32825. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  32826. __decorate([
  32827. BABYLON.serialize(),
  32828. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32829. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  32830. __decorate([
  32831. BABYLON.serialize(),
  32832. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32833. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  32834. __decorate([
  32835. BABYLON.serialize(),
  32836. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32837. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  32838. __decorate([
  32839. BABYLON.serialize(),
  32840. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32841. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  32842. __decorate([
  32843. BABYLON.serialize(),
  32844. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32845. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  32846. __decorate([
  32847. BABYLON.serialize(),
  32848. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32849. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  32850. __decorate([
  32851. BABYLON.serialize(),
  32852. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32853. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  32854. __decorate([
  32855. BABYLON.serialize(),
  32856. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32857. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  32858. __decorate([
  32859. BABYLON.serialize(),
  32860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32861. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  32862. __decorate([
  32863. BABYLON.serialize(),
  32864. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32865. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  32866. __decorate([
  32867. BABYLON.serialize(),
  32868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32869. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  32870. __decorate([
  32871. BABYLON.serialize(),
  32872. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32873. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  32874. __decorate([
  32875. BABYLON.serialize(),
  32876. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32877. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  32878. __decorate([
  32879. BABYLON.serialize(),
  32880. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32881. ], PBRMaterial.prototype, "useParallax", void 0);
  32882. __decorate([
  32883. BABYLON.serialize(),
  32884. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32885. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  32886. __decorate([
  32887. BABYLON.serialize(),
  32888. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32889. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  32890. __decorate([
  32891. BABYLON.serialize(),
  32892. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  32893. ], PBRMaterial.prototype, "disableLighting", void 0);
  32894. __decorate([
  32895. BABYLON.serialize(),
  32896. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32897. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  32898. __decorate([
  32899. BABYLON.serialize(),
  32900. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  32901. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  32902. __decorate([
  32903. BABYLON.serialize(),
  32904. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32905. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  32906. __decorate([
  32907. BABYLON.serialize(),
  32908. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32909. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  32910. __decorate([
  32911. BABYLON.serialize(),
  32912. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32913. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  32914. __decorate([
  32915. BABYLON.serialize(),
  32916. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32917. ], PBRMaterial.prototype, "preMultiplyAlpha", void 0);
  32918. __decorate([
  32919. BABYLON.serialize(),
  32920. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32921. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  32922. __decorate([
  32923. BABYLON.serializeAsTexture(),
  32924. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32925. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  32926. __decorate([
  32927. BABYLON.serialize(),
  32928. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32929. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  32930. BABYLON.PBRMaterial = PBRMaterial;
  32931. })(BABYLON || (BABYLON = {}));
  32932. //# sourceMappingURL=babylon.pbrMaterial.js.map
  32933. var BABYLON;
  32934. (function (BABYLON) {
  32935. /**
  32936. * The PBR material of BJS following the metal roughness convention.
  32937. *
  32938. * This fits to the PBR convention in the GLTF definition:
  32939. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  32940. */
  32941. var PBRMetallicRoughnessMaterial = (function (_super) {
  32942. __extends(PBRMetallicRoughnessMaterial, _super);
  32943. /**
  32944. * Instantiates a new PBRMetalRoughnessMaterial instance.
  32945. *
  32946. * @param name The material name
  32947. * @param scene The scene the material will be use in.
  32948. */
  32949. function PBRMetallicRoughnessMaterial(name, scene) {
  32950. var _this = _super.call(this, name, scene) || this;
  32951. _this._useRoughnessFromMetallicTextureAlpha = false;
  32952. _this._useRoughnessFromMetallicTextureGreen = true;
  32953. _this._useMetallnessFromMetallicTextureBlue = true;
  32954. return _this;
  32955. }
  32956. /**
  32957. * Return the currrent class name of the material.
  32958. */
  32959. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  32960. return "PBRMetallicRoughnessMaterial";
  32961. };
  32962. /**
  32963. * Return the active textures of the material.
  32964. */
  32965. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  32966. var activeTextures = _super.prototype.getActiveTextures.call(this);
  32967. if (this.baseTexture) {
  32968. activeTextures.push(this.baseTexture);
  32969. }
  32970. if (this.metallicRoughnessTexture) {
  32971. activeTextures.push(this.metallicRoughnessTexture);
  32972. }
  32973. return activeTextures;
  32974. };
  32975. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  32976. if (_super.prototype.hasTexture.call(this, texture)) {
  32977. return true;
  32978. }
  32979. if (this.baseTexture === texture) {
  32980. return true;
  32981. }
  32982. if (this.metallicRoughnessTexture === texture) {
  32983. return true;
  32984. }
  32985. return false;
  32986. };
  32987. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  32988. var _this = this;
  32989. return BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  32990. };
  32991. /**
  32992. * Serialize the material to a parsable JSON object.
  32993. */
  32994. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  32995. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  32996. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  32997. return serializationObject;
  32998. };
  32999. /**
  33000. * Parses a JSON object correponding to the serialize function.
  33001. */
  33002. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  33003. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  33004. };
  33005. return PBRMetallicRoughnessMaterial;
  33006. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  33007. __decorate([
  33008. BABYLON.serializeAsColor3(),
  33009. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  33010. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  33011. __decorate([
  33012. BABYLON.serializeAsTexture(),
  33013. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  33014. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  33015. __decorate([
  33016. BABYLON.serialize(),
  33017. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33018. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  33019. __decorate([
  33020. BABYLON.serialize(),
  33021. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33022. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  33023. __decorate([
  33024. BABYLON.serializeAsTexture(),
  33025. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  33026. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  33027. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  33028. })(BABYLON || (BABYLON = {}));
  33029. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  33030. var BABYLON;
  33031. (function (BABYLON) {
  33032. /**
  33033. * The PBR material of BJS following the specular glossiness convention.
  33034. *
  33035. * This fits to the PBR convention in the GLTF definition:
  33036. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  33037. */
  33038. var PBRSpecularGlossinessMaterial = (function (_super) {
  33039. __extends(PBRSpecularGlossinessMaterial, _super);
  33040. /**
  33041. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  33042. *
  33043. * @param name The material name
  33044. * @param scene The scene the material will be use in.
  33045. */
  33046. function PBRSpecularGlossinessMaterial(name, scene) {
  33047. var _this = _super.call(this, name, scene) || this;
  33048. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  33049. return _this;
  33050. }
  33051. /**
  33052. * Return the currrent class name of the material.
  33053. */
  33054. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  33055. return "PBRSpecularGlossinessMaterial";
  33056. };
  33057. /**
  33058. * Return the active textures of the material.
  33059. */
  33060. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  33061. var activeTextures = _super.prototype.getActiveTextures.call(this);
  33062. if (this.diffuseTexture) {
  33063. activeTextures.push(this.diffuseTexture);
  33064. }
  33065. if (this.specularGlossinessTexture) {
  33066. activeTextures.push(this.specularGlossinessTexture);
  33067. }
  33068. return activeTextures;
  33069. };
  33070. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  33071. if (_super.prototype.hasTexture.call(this, texture)) {
  33072. return true;
  33073. }
  33074. if (this.diffuseTexture === texture) {
  33075. return true;
  33076. }
  33077. if (this.specularGlossinessTexture === texture) {
  33078. return true;
  33079. }
  33080. return false;
  33081. };
  33082. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  33083. var _this = this;
  33084. return BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  33085. };
  33086. /**
  33087. * Serialize the material to a parsable JSON object.
  33088. */
  33089. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  33090. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  33091. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  33092. return serializationObject;
  33093. };
  33094. /**
  33095. * Parses a JSON object correponding to the serialize function.
  33096. */
  33097. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  33098. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  33099. };
  33100. return PBRSpecularGlossinessMaterial;
  33101. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  33102. __decorate([
  33103. BABYLON.serializeAsColor3("diffuse"),
  33104. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  33105. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  33106. __decorate([
  33107. BABYLON.serializeAsTexture(),
  33108. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  33109. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  33110. __decorate([
  33111. BABYLON.serializeAsColor3("specular"),
  33112. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  33113. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  33114. __decorate([
  33115. BABYLON.serialize(),
  33116. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  33117. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  33118. __decorate([
  33119. BABYLON.serializeAsTexture(),
  33120. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  33121. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  33122. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  33123. })(BABYLON || (BABYLON = {}));
  33124. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  33125. var BABYLON;
  33126. (function (BABYLON) {
  33127. BABYLON.CameraInputTypes = {};
  33128. var CameraInputsManager = (function () {
  33129. function CameraInputsManager(camera) {
  33130. this.attached = {};
  33131. this.camera = camera;
  33132. this.checkInputs = function () { };
  33133. }
  33134. CameraInputsManager.prototype.add = function (input) {
  33135. var type = input.getSimpleName();
  33136. if (this.attached[type]) {
  33137. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  33138. return;
  33139. }
  33140. this.attached[type] = input;
  33141. input.camera = this.camera;
  33142. //for checkInputs, we are dynamically creating a function
  33143. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  33144. if (input.checkInputs) {
  33145. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  33146. }
  33147. if (this.attachedElement) {
  33148. input.attachControl(this.attachedElement);
  33149. }
  33150. };
  33151. CameraInputsManager.prototype.remove = function (inputToRemove) {
  33152. for (var cam in this.attached) {
  33153. var input = this.attached[cam];
  33154. if (input === inputToRemove) {
  33155. input.detachControl(this.attachedElement);
  33156. delete this.attached[cam];
  33157. this.rebuildInputCheck();
  33158. }
  33159. }
  33160. };
  33161. CameraInputsManager.prototype.removeByType = function (inputType) {
  33162. for (var cam in this.attached) {
  33163. var input = this.attached[cam];
  33164. if (input.getClassName() === inputType) {
  33165. input.detachControl(this.attachedElement);
  33166. delete this.attached[cam];
  33167. this.rebuildInputCheck();
  33168. }
  33169. }
  33170. };
  33171. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  33172. var current = this.checkInputs;
  33173. return function () {
  33174. current();
  33175. fn();
  33176. };
  33177. };
  33178. CameraInputsManager.prototype.attachInput = function (input) {
  33179. input.attachControl(this.attachedElement, this.noPreventDefault);
  33180. };
  33181. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  33182. if (this.attachedElement) {
  33183. return;
  33184. }
  33185. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  33186. this.attachedElement = element;
  33187. this.noPreventDefault = noPreventDefault;
  33188. for (var cam in this.attached) {
  33189. var input = this.attached[cam];
  33190. this.attached[cam].attachControl(element, noPreventDefault);
  33191. }
  33192. };
  33193. CameraInputsManager.prototype.detachElement = function (element) {
  33194. if (this.attachedElement !== element) {
  33195. return;
  33196. }
  33197. for (var cam in this.attached) {
  33198. var input = this.attached[cam];
  33199. this.attached[cam].detachControl(element);
  33200. }
  33201. this.attachedElement = null;
  33202. };
  33203. CameraInputsManager.prototype.rebuildInputCheck = function () {
  33204. this.checkInputs = function () { };
  33205. for (var cam in this.attached) {
  33206. var input = this.attached[cam];
  33207. if (input.checkInputs) {
  33208. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  33209. }
  33210. }
  33211. };
  33212. CameraInputsManager.prototype.clear = function () {
  33213. if (this.attachedElement) {
  33214. this.detachElement(this.attachedElement);
  33215. }
  33216. this.attached = {};
  33217. this.attachedElement = null;
  33218. this.checkInputs = function () { };
  33219. };
  33220. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  33221. var inputs = {};
  33222. for (var cam in this.attached) {
  33223. var input = this.attached[cam];
  33224. var res = BABYLON.SerializationHelper.Serialize(input);
  33225. inputs[input.getClassName()] = res;
  33226. }
  33227. serializedCamera.inputsmgr = inputs;
  33228. };
  33229. CameraInputsManager.prototype.parse = function (parsedCamera) {
  33230. var parsedInputs = parsedCamera.inputsmgr;
  33231. if (parsedInputs) {
  33232. this.clear();
  33233. for (var n in parsedInputs) {
  33234. var construct = BABYLON.CameraInputTypes[n];
  33235. if (construct) {
  33236. var parsedinput = parsedInputs[n];
  33237. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  33238. this.add(input);
  33239. }
  33240. }
  33241. }
  33242. else {
  33243. //2016-03-08 this part is for managing backward compatibility
  33244. for (var n in this.attached) {
  33245. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  33246. if (construct) {
  33247. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  33248. this.remove(this.attached[n]);
  33249. this.add(input);
  33250. }
  33251. }
  33252. }
  33253. };
  33254. return CameraInputsManager;
  33255. }());
  33256. BABYLON.CameraInputsManager = CameraInputsManager;
  33257. })(BABYLON || (BABYLON = {}));
  33258. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  33259. var BABYLON;
  33260. (function (BABYLON) {
  33261. var FreeCameraMouseInput = (function () {
  33262. function FreeCameraMouseInput(touchEnabled) {
  33263. if (touchEnabled === void 0) { touchEnabled = true; }
  33264. this.touchEnabled = touchEnabled;
  33265. this.buttons = [0, 1, 2];
  33266. this.angularSensibility = 2000.0;
  33267. }
  33268. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  33269. var _this = this;
  33270. var engine = this.camera.getEngine();
  33271. if (!this._pointerInput) {
  33272. this._pointerInput = function (p, s) {
  33273. var evt = p.event;
  33274. if (!_this.touchEnabled && evt.pointerType === "touch") {
  33275. return;
  33276. }
  33277. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  33278. return;
  33279. }
  33280. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  33281. try {
  33282. evt.srcElement.setPointerCapture(evt.pointerId);
  33283. }
  33284. catch (e) {
  33285. //Nothing to do with the error. Execution will continue.
  33286. }
  33287. _this.previousPosition = {
  33288. x: evt.clientX,
  33289. y: evt.clientY
  33290. };
  33291. if (!noPreventDefault) {
  33292. evt.preventDefault();
  33293. element.focus();
  33294. }
  33295. }
  33296. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  33297. try {
  33298. evt.srcElement.releasePointerCapture(evt.pointerId);
  33299. }
  33300. catch (e) {
  33301. //Nothing to do with the error.
  33302. }
  33303. _this.previousPosition = null;
  33304. if (!noPreventDefault) {
  33305. evt.preventDefault();
  33306. }
  33307. }
  33308. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  33309. if (!_this.previousPosition || engine.isPointerLock) {
  33310. return;
  33311. }
  33312. var offsetX = evt.clientX - _this.previousPosition.x;
  33313. var offsetY = evt.clientY - _this.previousPosition.y;
  33314. if (_this.camera.getScene().useRightHandedSystem) {
  33315. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  33316. }
  33317. else {
  33318. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  33319. }
  33320. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  33321. _this.previousPosition = {
  33322. x: evt.clientX,
  33323. y: evt.clientY
  33324. };
  33325. if (!noPreventDefault) {
  33326. evt.preventDefault();
  33327. }
  33328. }
  33329. };
  33330. }
  33331. this._onMouseMove = function (evt) {
  33332. if (!engine.isPointerLock) {
  33333. return;
  33334. }
  33335. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  33336. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  33337. if (_this.camera.getScene().useRightHandedSystem) {
  33338. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  33339. }
  33340. else {
  33341. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  33342. }
  33343. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  33344. _this.previousPosition = null;
  33345. if (!noPreventDefault) {
  33346. evt.preventDefault();
  33347. }
  33348. };
  33349. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  33350. element.addEventListener("mousemove", this._onMouseMove, false);
  33351. };
  33352. FreeCameraMouseInput.prototype.detachControl = function (element) {
  33353. if (this._observer && element) {
  33354. this.camera.getScene().onPointerObservable.remove(this._observer);
  33355. element.removeEventListener("mousemove", this._onMouseMove);
  33356. this._observer = null;
  33357. this._onMouseMove = null;
  33358. this.previousPosition = null;
  33359. }
  33360. };
  33361. FreeCameraMouseInput.prototype.getClassName = function () {
  33362. return "FreeCameraMouseInput";
  33363. };
  33364. FreeCameraMouseInput.prototype.getSimpleName = function () {
  33365. return "mouse";
  33366. };
  33367. return FreeCameraMouseInput;
  33368. }());
  33369. __decorate([
  33370. BABYLON.serialize()
  33371. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  33372. __decorate([
  33373. BABYLON.serialize()
  33374. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  33375. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  33376. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  33377. })(BABYLON || (BABYLON = {}));
  33378. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  33379. var BABYLON;
  33380. (function (BABYLON) {
  33381. var FreeCameraKeyboardMoveInput = (function () {
  33382. function FreeCameraKeyboardMoveInput() {
  33383. this._keys = [];
  33384. this.keysUp = [38];
  33385. this.keysDown = [40];
  33386. this.keysLeft = [37];
  33387. this.keysRight = [39];
  33388. }
  33389. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  33390. var _this = this;
  33391. if (!this._onKeyDown) {
  33392. element.tabIndex = 1;
  33393. this._onKeyDown = function (evt) {
  33394. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  33395. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  33396. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  33397. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  33398. var index = _this._keys.indexOf(evt.keyCode);
  33399. if (index === -1) {
  33400. _this._keys.push(evt.keyCode);
  33401. }
  33402. if (!noPreventDefault) {
  33403. evt.preventDefault();
  33404. }
  33405. }
  33406. };
  33407. this._onKeyUp = function (evt) {
  33408. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  33409. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  33410. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  33411. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  33412. var index = _this._keys.indexOf(evt.keyCode);
  33413. if (index >= 0) {
  33414. _this._keys.splice(index, 1);
  33415. }
  33416. if (!noPreventDefault) {
  33417. evt.preventDefault();
  33418. }
  33419. }
  33420. };
  33421. element.addEventListener("keydown", this._onKeyDown, false);
  33422. element.addEventListener("keyup", this._onKeyUp, false);
  33423. BABYLON.Tools.RegisterTopRootEvents([
  33424. { name: "blur", handler: this._onLostFocus }
  33425. ]);
  33426. }
  33427. };
  33428. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  33429. if (this._onKeyDown) {
  33430. element.removeEventListener("keydown", this._onKeyDown);
  33431. element.removeEventListener("keyup", this._onKeyUp);
  33432. BABYLON.Tools.UnregisterTopRootEvents([
  33433. { name: "blur", handler: this._onLostFocus }
  33434. ]);
  33435. this._keys = [];
  33436. this._onKeyDown = null;
  33437. this._onKeyUp = null;
  33438. }
  33439. };
  33440. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  33441. if (this._onKeyDown) {
  33442. var camera = this.camera;
  33443. // Keyboard
  33444. for (var index = 0; index < this._keys.length; index++) {
  33445. var keyCode = this._keys[index];
  33446. var speed = camera._computeLocalCameraSpeed();
  33447. if (this.keysLeft.indexOf(keyCode) !== -1) {
  33448. camera._localDirection.copyFromFloats(-speed, 0, 0);
  33449. }
  33450. else if (this.keysUp.indexOf(keyCode) !== -1) {
  33451. camera._localDirection.copyFromFloats(0, 0, speed);
  33452. }
  33453. else if (this.keysRight.indexOf(keyCode) !== -1) {
  33454. camera._localDirection.copyFromFloats(speed, 0, 0);
  33455. }
  33456. else if (this.keysDown.indexOf(keyCode) !== -1) {
  33457. camera._localDirection.copyFromFloats(0, 0, -speed);
  33458. }
  33459. if (camera.getScene().useRightHandedSystem) {
  33460. camera._localDirection.z *= -1;
  33461. }
  33462. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  33463. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  33464. camera.cameraDirection.addInPlace(camera._transformedDirection);
  33465. }
  33466. }
  33467. };
  33468. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  33469. return "FreeCameraKeyboardMoveInput";
  33470. };
  33471. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  33472. this._keys = [];
  33473. };
  33474. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  33475. return "keyboard";
  33476. };
  33477. return FreeCameraKeyboardMoveInput;
  33478. }());
  33479. __decorate([
  33480. BABYLON.serialize()
  33481. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  33482. __decorate([
  33483. BABYLON.serialize()
  33484. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  33485. __decorate([
  33486. BABYLON.serialize()
  33487. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  33488. __decorate([
  33489. BABYLON.serialize()
  33490. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  33491. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  33492. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  33493. })(BABYLON || (BABYLON = {}));
  33494. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  33495. var BABYLON;
  33496. (function (BABYLON) {
  33497. var FreeCameraInputsManager = (function (_super) {
  33498. __extends(FreeCameraInputsManager, _super);
  33499. function FreeCameraInputsManager(camera) {
  33500. return _super.call(this, camera) || this;
  33501. }
  33502. FreeCameraInputsManager.prototype.addKeyboard = function () {
  33503. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  33504. return this;
  33505. };
  33506. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  33507. if (touchEnabled === void 0) { touchEnabled = true; }
  33508. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  33509. return this;
  33510. };
  33511. FreeCameraInputsManager.prototype.addGamepad = function () {
  33512. this.add(new BABYLON.FreeCameraGamepadInput());
  33513. return this;
  33514. };
  33515. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  33516. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  33517. return this;
  33518. };
  33519. FreeCameraInputsManager.prototype.addTouch = function () {
  33520. this.add(new BABYLON.FreeCameraTouchInput());
  33521. return this;
  33522. };
  33523. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  33524. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  33525. return this;
  33526. };
  33527. return FreeCameraInputsManager;
  33528. }(BABYLON.CameraInputsManager));
  33529. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  33530. })(BABYLON || (BABYLON = {}));
  33531. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  33532. /// <reference path="babylon.camera.ts" />
  33533. var BABYLON;
  33534. (function (BABYLON) {
  33535. var TargetCamera = (function (_super) {
  33536. __extends(TargetCamera, _super);
  33537. function TargetCamera(name, position, scene) {
  33538. var _this = _super.call(this, name, position, scene) || this;
  33539. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  33540. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  33541. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  33542. _this.speed = 2.0;
  33543. _this.noRotationConstraint = false;
  33544. _this.lockedTarget = null;
  33545. _this._currentTarget = BABYLON.Vector3.Zero();
  33546. _this._viewMatrix = BABYLON.Matrix.Zero();
  33547. _this._camMatrix = BABYLON.Matrix.Zero();
  33548. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  33549. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  33550. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  33551. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  33552. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  33553. _this._lookAtTemp = BABYLON.Matrix.Zero();
  33554. _this._tempMatrix = BABYLON.Matrix.Zero();
  33555. return _this;
  33556. }
  33557. TargetCamera.prototype.getFrontPosition = function (distance) {
  33558. var direction = this.getTarget().subtract(this.position);
  33559. direction.normalize();
  33560. direction.scaleInPlace(distance);
  33561. return this.globalPosition.add(direction);
  33562. };
  33563. TargetCamera.prototype._getLockedTargetPosition = function () {
  33564. if (!this.lockedTarget) {
  33565. return null;
  33566. }
  33567. if (this.lockedTarget.absolutePosition) {
  33568. this.lockedTarget.computeWorldMatrix();
  33569. }
  33570. return this.lockedTarget.absolutePosition || this.lockedTarget;
  33571. };
  33572. // Cache
  33573. TargetCamera.prototype._initCache = function () {
  33574. _super.prototype._initCache.call(this);
  33575. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  33576. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  33577. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  33578. };
  33579. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  33580. if (!ignoreParentClass) {
  33581. _super.prototype._updateCache.call(this);
  33582. }
  33583. var lockedTargetPosition = this._getLockedTargetPosition();
  33584. if (!lockedTargetPosition) {
  33585. this._cache.lockedTarget = null;
  33586. }
  33587. else {
  33588. if (!this._cache.lockedTarget) {
  33589. this._cache.lockedTarget = lockedTargetPosition.clone();
  33590. }
  33591. else {
  33592. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  33593. }
  33594. }
  33595. this._cache.rotation.copyFrom(this.rotation);
  33596. if (this.rotationQuaternion)
  33597. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  33598. };
  33599. // Synchronized
  33600. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  33601. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  33602. return false;
  33603. }
  33604. var lockedTargetPosition = this._getLockedTargetPosition();
  33605. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  33606. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  33607. };
  33608. // Methods
  33609. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  33610. var engine = this.getEngine();
  33611. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  33612. };
  33613. // Target
  33614. TargetCamera.prototype.setTarget = function (target) {
  33615. this.upVector.normalize();
  33616. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  33617. this._camMatrix.invert();
  33618. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  33619. var vDir = target.subtract(this.position);
  33620. if (vDir.x >= 0.0) {
  33621. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  33622. }
  33623. else {
  33624. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  33625. }
  33626. this.rotation.z = 0;
  33627. if (isNaN(this.rotation.x)) {
  33628. this.rotation.x = 0;
  33629. }
  33630. if (isNaN(this.rotation.y)) {
  33631. this.rotation.y = 0;
  33632. }
  33633. if (isNaN(this.rotation.z)) {
  33634. this.rotation.z = 0;
  33635. }
  33636. if (this.rotationQuaternion) {
  33637. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  33638. }
  33639. };
  33640. /**
  33641. * Return the current target position of the camera. This value is expressed in local space.
  33642. */
  33643. TargetCamera.prototype.getTarget = function () {
  33644. return this._currentTarget;
  33645. };
  33646. TargetCamera.prototype._decideIfNeedsToMove = function () {
  33647. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  33648. };
  33649. TargetCamera.prototype._updatePosition = function () {
  33650. if (this.parent) {
  33651. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  33652. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  33653. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  33654. return;
  33655. }
  33656. this.position.addInPlace(this.cameraDirection);
  33657. };
  33658. TargetCamera.prototype._checkInputs = function () {
  33659. var needToMove = this._decideIfNeedsToMove();
  33660. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  33661. // Move
  33662. if (needToMove) {
  33663. this._updatePosition();
  33664. }
  33665. // Rotate
  33666. if (needToRotate) {
  33667. this.rotation.x += this.cameraRotation.x;
  33668. this.rotation.y += this.cameraRotation.y;
  33669. //rotate, if quaternion is set and rotation was used
  33670. if (this.rotationQuaternion) {
  33671. var len = this.rotation.lengthSquared();
  33672. if (len) {
  33673. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  33674. }
  33675. }
  33676. if (!this.noRotationConstraint) {
  33677. var limit = (Math.PI / 2) * 0.95;
  33678. if (this.rotation.x > limit)
  33679. this.rotation.x = limit;
  33680. if (this.rotation.x < -limit)
  33681. this.rotation.x = -limit;
  33682. }
  33683. }
  33684. // Inertia
  33685. if (needToMove) {
  33686. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  33687. this.cameraDirection.x = 0;
  33688. }
  33689. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  33690. this.cameraDirection.y = 0;
  33691. }
  33692. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  33693. this.cameraDirection.z = 0;
  33694. }
  33695. this.cameraDirection.scaleInPlace(this.inertia);
  33696. }
  33697. if (needToRotate) {
  33698. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  33699. this.cameraRotation.x = 0;
  33700. }
  33701. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  33702. this.cameraRotation.y = 0;
  33703. }
  33704. this.cameraRotation.scaleInPlace(this.inertia);
  33705. }
  33706. _super.prototype._checkInputs.call(this);
  33707. };
  33708. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  33709. if (this.rotationQuaternion) {
  33710. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  33711. //update the up vector!
  33712. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  33713. }
  33714. else {
  33715. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  33716. }
  33717. };
  33718. TargetCamera.prototype._getViewMatrix = function () {
  33719. if (!this.lockedTarget) {
  33720. // Compute
  33721. this._updateCameraRotationMatrix();
  33722. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  33723. // Computing target and final matrix
  33724. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  33725. }
  33726. else {
  33727. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  33728. }
  33729. if (this.getScene().useRightHandedSystem) {
  33730. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  33731. }
  33732. else {
  33733. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  33734. }
  33735. return this._viewMatrix;
  33736. };
  33737. /**
  33738. * @override
  33739. * Override Camera.createRigCamera
  33740. */
  33741. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  33742. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  33743. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  33744. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  33745. if (!this.rotationQuaternion) {
  33746. this.rotationQuaternion = new BABYLON.Quaternion();
  33747. }
  33748. rigCamera._cameraRigParams = {};
  33749. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  33750. }
  33751. return rigCamera;
  33752. }
  33753. return null;
  33754. };
  33755. /**
  33756. * @override
  33757. * Override Camera._updateRigCameras
  33758. */
  33759. TargetCamera.prototype._updateRigCameras = function () {
  33760. var camLeft = this._rigCameras[0];
  33761. var camRight = this._rigCameras[1];
  33762. switch (this.cameraRigMode) {
  33763. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  33764. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  33765. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  33766. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  33767. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  33768. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  33769. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  33770. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  33771. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  33772. camLeft.setTarget(this.getTarget());
  33773. camRight.setTarget(this.getTarget());
  33774. break;
  33775. case BABYLON.Camera.RIG_MODE_VR:
  33776. if (camLeft.rotationQuaternion) {
  33777. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  33778. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  33779. }
  33780. else {
  33781. camLeft.rotation.copyFrom(this.rotation);
  33782. camRight.rotation.copyFrom(this.rotation);
  33783. }
  33784. camLeft.position.copyFrom(this.position);
  33785. camRight.position.copyFrom(this.position);
  33786. break;
  33787. }
  33788. _super.prototype._updateRigCameras.call(this);
  33789. };
  33790. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  33791. if (!this._rigCamTransformMatrix) {
  33792. this._rigCamTransformMatrix = new BABYLON.Matrix();
  33793. }
  33794. var target = this.getTarget();
  33795. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  33796. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  33797. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  33798. };
  33799. TargetCamera.prototype.getClassName = function () {
  33800. return "TargetCamera";
  33801. };
  33802. return TargetCamera;
  33803. }(BABYLON.Camera));
  33804. __decorate([
  33805. BABYLON.serializeAsVector3()
  33806. ], TargetCamera.prototype, "rotation", void 0);
  33807. __decorate([
  33808. BABYLON.serialize()
  33809. ], TargetCamera.prototype, "speed", void 0);
  33810. __decorate([
  33811. BABYLON.serializeAsMeshReference("lockedTargetId")
  33812. ], TargetCamera.prototype, "lockedTarget", void 0);
  33813. BABYLON.TargetCamera = TargetCamera;
  33814. })(BABYLON || (BABYLON = {}));
  33815. //# sourceMappingURL=babylon.targetCamera.js.map
  33816. var BABYLON;
  33817. (function (BABYLON) {
  33818. var FreeCamera = (function (_super) {
  33819. __extends(FreeCamera, _super);
  33820. function FreeCamera(name, position, scene) {
  33821. var _this = _super.call(this, name, position, scene) || this;
  33822. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  33823. _this.checkCollisions = false;
  33824. _this.applyGravity = false;
  33825. _this._needMoveForGravity = false;
  33826. _this._oldPosition = BABYLON.Vector3.Zero();
  33827. _this._diffPosition = BABYLON.Vector3.Zero();
  33828. _this._newPosition = BABYLON.Vector3.Zero();
  33829. // Collisions
  33830. _this._collisionMask = -1;
  33831. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  33832. if (collidedMesh === void 0) { collidedMesh = null; }
  33833. //TODO move this to the collision coordinator!
  33834. if (_this.getScene().workerCollisions)
  33835. newPosition.multiplyInPlace(_this._collider.radius);
  33836. var updatePosition = function (newPos) {
  33837. _this._newPosition.copyFrom(newPos);
  33838. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  33839. var oldPosition = _this.position.clone();
  33840. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  33841. _this.position.addInPlace(_this._diffPosition);
  33842. if (_this.onCollide && collidedMesh) {
  33843. _this.onCollide(collidedMesh);
  33844. }
  33845. }
  33846. };
  33847. updatePosition(newPosition);
  33848. };
  33849. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  33850. _this.inputs.addKeyboard().addMouse();
  33851. return _this;
  33852. }
  33853. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  33854. //-- begin properties for backward compatibility for inputs
  33855. get: function () {
  33856. var mouse = this.inputs.attached["mouse"];
  33857. if (mouse)
  33858. return mouse.angularSensibility;
  33859. },
  33860. set: function (value) {
  33861. var mouse = this.inputs.attached["mouse"];
  33862. if (mouse)
  33863. mouse.angularSensibility = value;
  33864. },
  33865. enumerable: true,
  33866. configurable: true
  33867. });
  33868. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  33869. get: function () {
  33870. var keyboard = this.inputs.attached["keyboard"];
  33871. if (keyboard)
  33872. return keyboard.keysUp;
  33873. },
  33874. set: function (value) {
  33875. var keyboard = this.inputs.attached["keyboard"];
  33876. if (keyboard)
  33877. keyboard.keysUp = value;
  33878. },
  33879. enumerable: true,
  33880. configurable: true
  33881. });
  33882. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  33883. get: function () {
  33884. var keyboard = this.inputs.attached["keyboard"];
  33885. if (keyboard)
  33886. return keyboard.keysDown;
  33887. },
  33888. set: function (value) {
  33889. var keyboard = this.inputs.attached["keyboard"];
  33890. if (keyboard)
  33891. keyboard.keysDown = value;
  33892. },
  33893. enumerable: true,
  33894. configurable: true
  33895. });
  33896. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  33897. get: function () {
  33898. var keyboard = this.inputs.attached["keyboard"];
  33899. if (keyboard)
  33900. return keyboard.keysLeft;
  33901. },
  33902. set: function (value) {
  33903. var keyboard = this.inputs.attached["keyboard"];
  33904. if (keyboard)
  33905. keyboard.keysLeft = value;
  33906. },
  33907. enumerable: true,
  33908. configurable: true
  33909. });
  33910. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  33911. get: function () {
  33912. var keyboard = this.inputs.attached["keyboard"];
  33913. if (keyboard)
  33914. return keyboard.keysRight;
  33915. },
  33916. set: function (value) {
  33917. var keyboard = this.inputs.attached["keyboard"];
  33918. if (keyboard)
  33919. keyboard.keysRight = value;
  33920. },
  33921. enumerable: true,
  33922. configurable: true
  33923. });
  33924. // Controls
  33925. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  33926. this.inputs.attachElement(element, noPreventDefault);
  33927. };
  33928. FreeCamera.prototype.detachControl = function (element) {
  33929. this.inputs.detachElement(element);
  33930. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  33931. this.cameraRotation = new BABYLON.Vector2(0, 0);
  33932. };
  33933. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  33934. get: function () {
  33935. return this._collisionMask;
  33936. },
  33937. set: function (mask) {
  33938. this._collisionMask = !isNaN(mask) ? mask : -1;
  33939. },
  33940. enumerable: true,
  33941. configurable: true
  33942. });
  33943. FreeCamera.prototype._collideWithWorld = function (velocity) {
  33944. var globalPosition;
  33945. if (this.parent) {
  33946. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  33947. }
  33948. else {
  33949. globalPosition = this.position;
  33950. }
  33951. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  33952. if (!this._collider) {
  33953. this._collider = new BABYLON.Collider();
  33954. }
  33955. this._collider.radius = this.ellipsoid;
  33956. this._collider.collisionMask = this._collisionMask;
  33957. //no need for clone, as long as gravity is not on.
  33958. var actualVelocity = velocity;
  33959. //add gravity to the velocity to prevent the dual-collision checking
  33960. if (this.applyGravity) {
  33961. //this prevents mending with cameraDirection, a global variable of the free camera class.
  33962. actualVelocity = velocity.add(this.getScene().gravity);
  33963. }
  33964. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  33965. };
  33966. FreeCamera.prototype._checkInputs = function () {
  33967. if (!this._localDirection) {
  33968. this._localDirection = BABYLON.Vector3.Zero();
  33969. this._transformedDirection = BABYLON.Vector3.Zero();
  33970. }
  33971. this.inputs.checkInputs();
  33972. _super.prototype._checkInputs.call(this);
  33973. };
  33974. FreeCamera.prototype._decideIfNeedsToMove = function () {
  33975. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  33976. };
  33977. FreeCamera.prototype._updatePosition = function () {
  33978. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  33979. this._collideWithWorld(this.cameraDirection);
  33980. }
  33981. else {
  33982. _super.prototype._updatePosition.call(this);
  33983. }
  33984. };
  33985. FreeCamera.prototype.dispose = function () {
  33986. this.inputs.clear();
  33987. _super.prototype.dispose.call(this);
  33988. };
  33989. FreeCamera.prototype.getClassName = function () {
  33990. return "FreeCamera";
  33991. };
  33992. return FreeCamera;
  33993. }(BABYLON.TargetCamera));
  33994. __decorate([
  33995. BABYLON.serializeAsVector3()
  33996. ], FreeCamera.prototype, "ellipsoid", void 0);
  33997. __decorate([
  33998. BABYLON.serialize()
  33999. ], FreeCamera.prototype, "checkCollisions", void 0);
  34000. __decorate([
  34001. BABYLON.serialize()
  34002. ], FreeCamera.prototype, "applyGravity", void 0);
  34003. BABYLON.FreeCamera = FreeCamera;
  34004. })(BABYLON || (BABYLON = {}));
  34005. //# sourceMappingURL=babylon.freeCamera.js.map
  34006. var BABYLON;
  34007. (function (BABYLON) {
  34008. var ArcRotateCameraKeyboardMoveInput = (function () {
  34009. function ArcRotateCameraKeyboardMoveInput() {
  34010. this._keys = [];
  34011. this.keysUp = [38];
  34012. this.keysDown = [40];
  34013. this.keysLeft = [37];
  34014. this.keysRight = [39];
  34015. }
  34016. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  34017. var _this = this;
  34018. element.tabIndex = 1;
  34019. this._onKeyDown = function (evt) {
  34020. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  34021. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  34022. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  34023. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  34024. var index = _this._keys.indexOf(evt.keyCode);
  34025. if (index === -1) {
  34026. _this._keys.push(evt.keyCode);
  34027. }
  34028. if (evt.preventDefault) {
  34029. if (!noPreventDefault) {
  34030. evt.preventDefault();
  34031. }
  34032. }
  34033. }
  34034. };
  34035. this._onKeyUp = function (evt) {
  34036. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  34037. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  34038. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  34039. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  34040. var index = _this._keys.indexOf(evt.keyCode);
  34041. if (index >= 0) {
  34042. _this._keys.splice(index, 1);
  34043. }
  34044. if (evt.preventDefault) {
  34045. if (!noPreventDefault) {
  34046. evt.preventDefault();
  34047. }
  34048. }
  34049. }
  34050. };
  34051. this._onLostFocus = function () {
  34052. _this._keys = [];
  34053. };
  34054. element.addEventListener("keydown", this._onKeyDown, false);
  34055. element.addEventListener("keyup", this._onKeyUp, false);
  34056. BABYLON.Tools.RegisterTopRootEvents([
  34057. { name: "blur", handler: this._onLostFocus }
  34058. ]);
  34059. };
  34060. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  34061. if (element) {
  34062. element.removeEventListener("keydown", this._onKeyDown);
  34063. element.removeEventListener("keyup", this._onKeyUp);
  34064. }
  34065. BABYLON.Tools.UnregisterTopRootEvents([
  34066. { name: "blur", handler: this._onLostFocus }
  34067. ]);
  34068. this._keys = [];
  34069. this._onKeyDown = null;
  34070. this._onKeyUp = null;
  34071. this._onLostFocus = null;
  34072. };
  34073. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  34074. if (this._onKeyDown) {
  34075. var camera = this.camera;
  34076. for (var index = 0; index < this._keys.length; index++) {
  34077. var keyCode = this._keys[index];
  34078. if (this.keysLeft.indexOf(keyCode) !== -1) {
  34079. camera.inertialAlphaOffset -= 0.01;
  34080. }
  34081. else if (this.keysUp.indexOf(keyCode) !== -1) {
  34082. camera.inertialBetaOffset -= 0.01;
  34083. }
  34084. else if (this.keysRight.indexOf(keyCode) !== -1) {
  34085. camera.inertialAlphaOffset += 0.01;
  34086. }
  34087. else if (this.keysDown.indexOf(keyCode) !== -1) {
  34088. camera.inertialBetaOffset += 0.01;
  34089. }
  34090. }
  34091. }
  34092. };
  34093. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  34094. return "ArcRotateCameraKeyboardMoveInput";
  34095. };
  34096. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  34097. return "keyboard";
  34098. };
  34099. return ArcRotateCameraKeyboardMoveInput;
  34100. }());
  34101. __decorate([
  34102. BABYLON.serialize()
  34103. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  34104. __decorate([
  34105. BABYLON.serialize()
  34106. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  34107. __decorate([
  34108. BABYLON.serialize()
  34109. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  34110. __decorate([
  34111. BABYLON.serialize()
  34112. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  34113. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  34114. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  34115. })(BABYLON || (BABYLON = {}));
  34116. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  34117. var BABYLON;
  34118. (function (BABYLON) {
  34119. var ArcRotateCameraMouseWheelInput = (function () {
  34120. function ArcRotateCameraMouseWheelInput() {
  34121. this.wheelPrecision = 3.0;
  34122. }
  34123. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  34124. var _this = this;
  34125. this._wheel = function (p, s) {
  34126. //sanity check - this should be a PointerWheel event.
  34127. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  34128. return;
  34129. var event = p.event;
  34130. var delta = 0;
  34131. if (event.wheelDelta) {
  34132. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  34133. }
  34134. else if (event.detail) {
  34135. delta = -event.detail / _this.wheelPrecision;
  34136. }
  34137. if (delta)
  34138. _this.camera.inertialRadiusOffset += delta;
  34139. if (event.preventDefault) {
  34140. if (!noPreventDefault) {
  34141. event.preventDefault();
  34142. }
  34143. }
  34144. };
  34145. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  34146. };
  34147. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  34148. if (this._observer && element) {
  34149. this.camera.getScene().onPointerObservable.remove(this._observer);
  34150. this._observer = null;
  34151. this._wheel = null;
  34152. }
  34153. };
  34154. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  34155. return "ArcRotateCameraMouseWheelInput";
  34156. };
  34157. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  34158. return "mousewheel";
  34159. };
  34160. return ArcRotateCameraMouseWheelInput;
  34161. }());
  34162. __decorate([
  34163. BABYLON.serialize()
  34164. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  34165. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  34166. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  34167. })(BABYLON || (BABYLON = {}));
  34168. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  34169. var BABYLON;
  34170. (function (BABYLON) {
  34171. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  34172. var ArcRotateCameraPointersInput = (function () {
  34173. function ArcRotateCameraPointersInput() {
  34174. this.buttons = [0, 1, 2];
  34175. this.angularSensibilityX = 1000.0;
  34176. this.angularSensibilityY = 1000.0;
  34177. this.pinchPrecision = 6.0;
  34178. this.panningSensibility = 50.0;
  34179. this._isPanClick = false;
  34180. this.pinchInwards = true;
  34181. }
  34182. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  34183. var _this = this;
  34184. var engine = this.camera.getEngine();
  34185. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  34186. var pointA, pointB;
  34187. var previousPinchDistance = 0;
  34188. this._pointerInput = function (p, s) {
  34189. var evt = p.event;
  34190. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  34191. return;
  34192. }
  34193. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  34194. try {
  34195. evt.srcElement.setPointerCapture(evt.pointerId);
  34196. }
  34197. catch (e) {
  34198. //Nothing to do with the error. Execution will continue.
  34199. }
  34200. // Manage panning with pan button click
  34201. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  34202. // manage pointers
  34203. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  34204. if (pointA === undefined) {
  34205. pointA = cacheSoloPointer;
  34206. }
  34207. else if (pointB === undefined) {
  34208. pointB = cacheSoloPointer;
  34209. }
  34210. if (!noPreventDefault) {
  34211. evt.preventDefault();
  34212. element.focus();
  34213. }
  34214. }
  34215. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  34216. try {
  34217. evt.srcElement.releasePointerCapture(evt.pointerId);
  34218. }
  34219. catch (e) {
  34220. //Nothing to do with the error.
  34221. }
  34222. cacheSoloPointer = null;
  34223. previousPinchDistance = 0;
  34224. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  34225. //but emptying completly pointers collection is required to fix a bug on iPhone :
  34226. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  34227. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  34228. pointA = pointB = undefined;
  34229. if (!noPreventDefault) {
  34230. evt.preventDefault();
  34231. }
  34232. }
  34233. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  34234. if (!noPreventDefault) {
  34235. evt.preventDefault();
  34236. }
  34237. // One button down
  34238. if (pointA && pointB === undefined) {
  34239. if (_this.panningSensibility !== 0 &&
  34240. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  34241. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  34242. _this.camera
  34243. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  34244. _this.camera
  34245. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  34246. }
  34247. else {
  34248. var offsetX = evt.clientX - cacheSoloPointer.x;
  34249. var offsetY = evt.clientY - cacheSoloPointer.y;
  34250. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  34251. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  34252. }
  34253. cacheSoloPointer.x = evt.clientX;
  34254. cacheSoloPointer.y = evt.clientY;
  34255. }
  34256. else if (pointA && pointB) {
  34257. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  34258. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  34259. ed.x = evt.clientX;
  34260. ed.y = evt.clientY;
  34261. var direction = _this.pinchInwards ? 1 : -1;
  34262. var distX = pointA.x - pointB.x;
  34263. var distY = pointA.y - pointB.y;
  34264. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  34265. if (previousPinchDistance === 0) {
  34266. previousPinchDistance = pinchSquaredDistance;
  34267. return;
  34268. }
  34269. if (pinchSquaredDistance !== previousPinchDistance) {
  34270. _this.camera
  34271. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  34272. (_this.pinchPrecision *
  34273. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  34274. direction);
  34275. previousPinchDistance = pinchSquaredDistance;
  34276. }
  34277. }
  34278. }
  34279. };
  34280. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  34281. this._onContextMenu = function (evt) {
  34282. evt.preventDefault();
  34283. };
  34284. if (!this.camera._useCtrlForPanning) {
  34285. element.addEventListener("contextmenu", this._onContextMenu, false);
  34286. }
  34287. this._onLostFocus = function () {
  34288. //this._keys = [];
  34289. pointA = pointB = undefined;
  34290. previousPinchDistance = 0;
  34291. cacheSoloPointer = null;
  34292. };
  34293. this._onMouseMove = function (evt) {
  34294. if (!engine.isPointerLock) {
  34295. return;
  34296. }
  34297. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  34298. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  34299. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  34300. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  34301. if (!noPreventDefault) {
  34302. evt.preventDefault();
  34303. }
  34304. };
  34305. this._onGestureStart = function (e) {
  34306. if (window.MSGesture === undefined) {
  34307. return;
  34308. }
  34309. if (!_this._MSGestureHandler) {
  34310. _this._MSGestureHandler = new MSGesture();
  34311. _this._MSGestureHandler.target = element;
  34312. }
  34313. _this._MSGestureHandler.addPointer(e.pointerId);
  34314. };
  34315. this._onGesture = function (e) {
  34316. _this.camera.radius *= e.scale;
  34317. if (e.preventDefault) {
  34318. if (!noPreventDefault) {
  34319. e.stopPropagation();
  34320. e.preventDefault();
  34321. }
  34322. }
  34323. };
  34324. element.addEventListener("mousemove", this._onMouseMove, false);
  34325. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  34326. element.addEventListener("MSGestureChange", this._onGesture, false);
  34327. BABYLON.Tools.RegisterTopRootEvents([
  34328. { name: "blur", handler: this._onLostFocus }
  34329. ]);
  34330. };
  34331. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  34332. BABYLON.Tools.UnregisterTopRootEvents([
  34333. { name: "blur", handler: this._onLostFocus }
  34334. ]);
  34335. if (element && this._observer) {
  34336. this.camera.getScene().onPointerObservable.remove(this._observer);
  34337. this._observer = null;
  34338. element.removeEventListener("contextmenu", this._onContextMenu);
  34339. element.removeEventListener("mousemove", this._onMouseMove);
  34340. element.removeEventListener("MSPointerDown", this._onGestureStart);
  34341. element.removeEventListener("MSGestureChange", this._onGesture);
  34342. this._isPanClick = false;
  34343. this.pinchInwards = true;
  34344. this._onMouseMove = null;
  34345. this._onGestureStart = null;
  34346. this._onGesture = null;
  34347. this._MSGestureHandler = null;
  34348. this._onLostFocus = null;
  34349. this._onContextMenu = null;
  34350. }
  34351. this.camera = null;
  34352. };
  34353. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  34354. return "ArcRotateCameraPointersInput";
  34355. };
  34356. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  34357. return "pointers";
  34358. };
  34359. return ArcRotateCameraPointersInput;
  34360. }());
  34361. __decorate([
  34362. BABYLON.serialize()
  34363. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  34364. __decorate([
  34365. BABYLON.serialize()
  34366. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  34367. __decorate([
  34368. BABYLON.serialize()
  34369. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  34370. __decorate([
  34371. BABYLON.serialize()
  34372. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  34373. __decorate([
  34374. BABYLON.serialize()
  34375. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  34376. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  34377. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  34378. })(BABYLON || (BABYLON = {}));
  34379. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  34380. /// <reference path="babylon.targetCamera.ts" />
  34381. /// <reference path="..\Tools\babylon.tools.ts" />
  34382. var BABYLON;
  34383. (function (BABYLON) {
  34384. var ArcRotateCamera = (function (_super) {
  34385. __extends(ArcRotateCamera, _super);
  34386. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  34387. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  34388. _this.inertialAlphaOffset = 0;
  34389. _this.inertialBetaOffset = 0;
  34390. _this.inertialRadiusOffset = 0;
  34391. _this.lowerAlphaLimit = null;
  34392. _this.upperAlphaLimit = null;
  34393. _this.lowerBetaLimit = 0.01;
  34394. _this.upperBetaLimit = Math.PI;
  34395. _this.lowerRadiusLimit = null;
  34396. _this.upperRadiusLimit = null;
  34397. _this.inertialPanningX = 0;
  34398. _this.inertialPanningY = 0;
  34399. _this.panningInertia = 0.9;
  34400. //-- end properties for backward compatibility for inputs
  34401. _this.zoomOnFactor = 1;
  34402. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  34403. _this.allowUpsideDown = true;
  34404. _this._viewMatrix = new BABYLON.Matrix();
  34405. // Panning
  34406. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  34407. _this.checkCollisions = false;
  34408. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  34409. _this._previousPosition = BABYLON.Vector3.Zero();
  34410. _this._collisionVelocity = BABYLON.Vector3.Zero();
  34411. _this._newPosition = BABYLON.Vector3.Zero();
  34412. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  34413. if (collidedMesh === void 0) { collidedMesh = null; }
  34414. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  34415. newPosition.multiplyInPlace(_this._collider.radius);
  34416. }
  34417. if (!collidedMesh) {
  34418. _this._previousPosition.copyFrom(_this.position);
  34419. }
  34420. else {
  34421. _this.setPosition(newPosition);
  34422. if (_this.onCollide) {
  34423. _this.onCollide(collidedMesh);
  34424. }
  34425. }
  34426. // Recompute because of constraints
  34427. var cosa = Math.cos(_this.alpha);
  34428. var sina = Math.sin(_this.alpha);
  34429. var cosb = Math.cos(_this.beta);
  34430. var sinb = Math.sin(_this.beta);
  34431. if (sinb === 0) {
  34432. sinb = 0.0001;
  34433. }
  34434. var target = _this._getTargetPosition();
  34435. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  34436. _this.position.copyFrom(_this._newPosition);
  34437. var up = _this.upVector;
  34438. if (_this.allowUpsideDown && _this.beta < 0) {
  34439. up = up.clone();
  34440. up = up.negate();
  34441. }
  34442. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  34443. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  34444. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  34445. _this._collisionTriggered = false;
  34446. };
  34447. _this._target = BABYLON.Vector3.Zero();
  34448. if (target) {
  34449. _this.setTarget(target);
  34450. }
  34451. _this.alpha = alpha;
  34452. _this.beta = beta;
  34453. _this.radius = radius;
  34454. _this.getViewMatrix();
  34455. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  34456. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  34457. return _this;
  34458. }
  34459. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  34460. get: function () {
  34461. return this._target;
  34462. },
  34463. set: function (value) {
  34464. this.setTarget(value);
  34465. },
  34466. enumerable: true,
  34467. configurable: true
  34468. });
  34469. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  34470. //-- begin properties for backward compatibility for inputs
  34471. get: function () {
  34472. var pointers = this.inputs.attached["pointers"];
  34473. if (pointers)
  34474. return pointers.angularSensibilityX;
  34475. },
  34476. set: function (value) {
  34477. var pointers = this.inputs.attached["pointers"];
  34478. if (pointers) {
  34479. pointers.angularSensibilityX = value;
  34480. }
  34481. },
  34482. enumerable: true,
  34483. configurable: true
  34484. });
  34485. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  34486. get: function () {
  34487. var pointers = this.inputs.attached["pointers"];
  34488. if (pointers)
  34489. return pointers.angularSensibilityY;
  34490. },
  34491. set: function (value) {
  34492. var pointers = this.inputs.attached["pointers"];
  34493. if (pointers) {
  34494. pointers.angularSensibilityY = value;
  34495. }
  34496. },
  34497. enumerable: true,
  34498. configurable: true
  34499. });
  34500. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  34501. get: function () {
  34502. var pointers = this.inputs.attached["pointers"];
  34503. if (pointers)
  34504. return pointers.pinchPrecision;
  34505. },
  34506. set: function (value) {
  34507. var pointers = this.inputs.attached["pointers"];
  34508. if (pointers) {
  34509. pointers.pinchPrecision = value;
  34510. }
  34511. },
  34512. enumerable: true,
  34513. configurable: true
  34514. });
  34515. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  34516. get: function () {
  34517. var pointers = this.inputs.attached["pointers"];
  34518. if (pointers)
  34519. return pointers.panningSensibility;
  34520. },
  34521. set: function (value) {
  34522. var pointers = this.inputs.attached["pointers"];
  34523. if (pointers) {
  34524. pointers.panningSensibility = value;
  34525. }
  34526. },
  34527. enumerable: true,
  34528. configurable: true
  34529. });
  34530. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  34531. get: function () {
  34532. var keyboard = this.inputs.attached["keyboard"];
  34533. if (keyboard)
  34534. return keyboard.keysUp;
  34535. },
  34536. set: function (value) {
  34537. var keyboard = this.inputs.attached["keyboard"];
  34538. if (keyboard)
  34539. keyboard.keysUp = value;
  34540. },
  34541. enumerable: true,
  34542. configurable: true
  34543. });
  34544. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  34545. get: function () {
  34546. var keyboard = this.inputs.attached["keyboard"];
  34547. if (keyboard)
  34548. return keyboard.keysDown;
  34549. },
  34550. set: function (value) {
  34551. var keyboard = this.inputs.attached["keyboard"];
  34552. if (keyboard)
  34553. keyboard.keysDown = value;
  34554. },
  34555. enumerable: true,
  34556. configurable: true
  34557. });
  34558. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  34559. get: function () {
  34560. var keyboard = this.inputs.attached["keyboard"];
  34561. if (keyboard)
  34562. return keyboard.keysLeft;
  34563. },
  34564. set: function (value) {
  34565. var keyboard = this.inputs.attached["keyboard"];
  34566. if (keyboard)
  34567. keyboard.keysLeft = value;
  34568. },
  34569. enumerable: true,
  34570. configurable: true
  34571. });
  34572. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  34573. get: function () {
  34574. var keyboard = this.inputs.attached["keyboard"];
  34575. if (keyboard)
  34576. return keyboard.keysRight;
  34577. },
  34578. set: function (value) {
  34579. var keyboard = this.inputs.attached["keyboard"];
  34580. if (keyboard)
  34581. keyboard.keysRight = value;
  34582. },
  34583. enumerable: true,
  34584. configurable: true
  34585. });
  34586. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  34587. get: function () {
  34588. var mousewheel = this.inputs.attached["mousewheel"];
  34589. if (mousewheel)
  34590. return mousewheel.wheelPrecision;
  34591. },
  34592. set: function (value) {
  34593. var mousewheel = this.inputs.attached["mousewheel"];
  34594. if (mousewheel)
  34595. mousewheel.wheelPrecision = value;
  34596. },
  34597. enumerable: true,
  34598. configurable: true
  34599. });
  34600. // Cache
  34601. ArcRotateCamera.prototype._initCache = function () {
  34602. _super.prototype._initCache.call(this);
  34603. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  34604. this._cache.alpha = undefined;
  34605. this._cache.beta = undefined;
  34606. this._cache.radius = undefined;
  34607. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  34608. };
  34609. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  34610. if (!ignoreParentClass) {
  34611. _super.prototype._updateCache.call(this);
  34612. }
  34613. this._cache._target.copyFrom(this._getTargetPosition());
  34614. this._cache.alpha = this.alpha;
  34615. this._cache.beta = this.beta;
  34616. this._cache.radius = this.radius;
  34617. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  34618. };
  34619. ArcRotateCamera.prototype._getTargetPosition = function () {
  34620. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  34621. var pos = this._targetHost.getAbsolutePosition();
  34622. if (this._targetBoundingCenter) {
  34623. pos.addToRef(this._targetBoundingCenter, this._target);
  34624. }
  34625. else {
  34626. this._target.copyFrom(pos);
  34627. }
  34628. }
  34629. var lockedTargetPosition = this._getLockedTargetPosition();
  34630. if (lockedTargetPosition) {
  34631. return lockedTargetPosition;
  34632. }
  34633. return this._target;
  34634. };
  34635. // Synchronized
  34636. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  34637. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  34638. return false;
  34639. return this._cache._target.equals(this._getTargetPosition())
  34640. && this._cache.alpha === this.alpha
  34641. && this._cache.beta === this.beta
  34642. && this._cache.radius === this.radius
  34643. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  34644. };
  34645. // Methods
  34646. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  34647. var _this = this;
  34648. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  34649. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  34650. this._useCtrlForPanning = useCtrlForPanning;
  34651. this._panningMouseButton = panningMouseButton;
  34652. this.inputs.attachElement(element, noPreventDefault);
  34653. this._reset = function () {
  34654. _this.inertialAlphaOffset = 0;
  34655. _this.inertialBetaOffset = 0;
  34656. _this.inertialRadiusOffset = 0;
  34657. };
  34658. };
  34659. ArcRotateCamera.prototype.detachControl = function (element) {
  34660. this.inputs.detachElement(element);
  34661. if (this._reset) {
  34662. this._reset();
  34663. }
  34664. };
  34665. ArcRotateCamera.prototype._checkInputs = function () {
  34666. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  34667. if (this._collisionTriggered) {
  34668. return;
  34669. }
  34670. this.inputs.checkInputs();
  34671. // Inertia
  34672. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  34673. if (this.getScene().useRightHandedSystem) {
  34674. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  34675. }
  34676. else {
  34677. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  34678. }
  34679. this.beta += this.inertialBetaOffset;
  34680. this.radius -= this.inertialRadiusOffset;
  34681. this.inertialAlphaOffset *= this.inertia;
  34682. this.inertialBetaOffset *= this.inertia;
  34683. this.inertialRadiusOffset *= this.inertia;
  34684. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  34685. this.inertialAlphaOffset = 0;
  34686. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  34687. this.inertialBetaOffset = 0;
  34688. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  34689. this.inertialRadiusOffset = 0;
  34690. }
  34691. // Panning inertia
  34692. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  34693. if (!this._localDirection) {
  34694. this._localDirection = BABYLON.Vector3.Zero();
  34695. this._transformedDirection = BABYLON.Vector3.Zero();
  34696. }
  34697. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  34698. this._localDirection.multiplyInPlace(this.panningAxis);
  34699. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  34700. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  34701. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  34702. if (!this.panningAxis.y) {
  34703. this._transformedDirection.y = 0;
  34704. }
  34705. if (!this._targetHost) {
  34706. this._target.addInPlace(this._transformedDirection);
  34707. }
  34708. this.inertialPanningX *= this.panningInertia;
  34709. this.inertialPanningY *= this.panningInertia;
  34710. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  34711. this.inertialPanningX = 0;
  34712. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  34713. this.inertialPanningY = 0;
  34714. }
  34715. // Limits
  34716. this._checkLimits();
  34717. _super.prototype._checkInputs.call(this);
  34718. };
  34719. ArcRotateCamera.prototype._checkLimits = function () {
  34720. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  34721. if (this.allowUpsideDown && this.beta > Math.PI) {
  34722. this.beta = this.beta - (2 * Math.PI);
  34723. }
  34724. }
  34725. else {
  34726. if (this.beta < this.lowerBetaLimit) {
  34727. this.beta = this.lowerBetaLimit;
  34728. }
  34729. }
  34730. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  34731. if (this.allowUpsideDown && this.beta < -Math.PI) {
  34732. this.beta = this.beta + (2 * Math.PI);
  34733. }
  34734. }
  34735. else {
  34736. if (this.beta > this.upperBetaLimit) {
  34737. this.beta = this.upperBetaLimit;
  34738. }
  34739. }
  34740. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  34741. this.alpha = this.lowerAlphaLimit;
  34742. }
  34743. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  34744. this.alpha = this.upperAlphaLimit;
  34745. }
  34746. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  34747. this.radius = this.lowerRadiusLimit;
  34748. }
  34749. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  34750. this.radius = this.upperRadiusLimit;
  34751. }
  34752. };
  34753. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  34754. var radiusv3 = this.position.subtract(this._getTargetPosition());
  34755. this.radius = radiusv3.length();
  34756. // Alpha
  34757. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  34758. if (radiusv3.z < 0) {
  34759. this.alpha = 2 * Math.PI - this.alpha;
  34760. }
  34761. // Beta
  34762. this.beta = Math.acos(radiusv3.y / this.radius);
  34763. this._checkLimits();
  34764. };
  34765. ArcRotateCamera.prototype.setPosition = function (position) {
  34766. if (this.position.equals(position)) {
  34767. return;
  34768. }
  34769. this.position.copyFrom(position);
  34770. this.rebuildAnglesAndRadius();
  34771. };
  34772. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  34773. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  34774. if (allowSamePosition === void 0) { allowSamePosition = false; }
  34775. if (target.getBoundingInfo) {
  34776. if (toBoundingCenter) {
  34777. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  34778. }
  34779. else {
  34780. this._targetBoundingCenter = null;
  34781. }
  34782. this._targetHost = target;
  34783. this._target = this._getTargetPosition();
  34784. }
  34785. else {
  34786. var newTarget = target;
  34787. var currentTarget = this._getTargetPosition();
  34788. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  34789. return;
  34790. }
  34791. this._target = newTarget;
  34792. this._targetBoundingCenter = null;
  34793. }
  34794. this.rebuildAnglesAndRadius();
  34795. };
  34796. ArcRotateCamera.prototype._getViewMatrix = function () {
  34797. // Compute
  34798. var cosa = Math.cos(this.alpha);
  34799. var sina = Math.sin(this.alpha);
  34800. var cosb = Math.cos(this.beta);
  34801. var sinb = Math.sin(this.beta);
  34802. if (sinb === 0) {
  34803. sinb = 0.0001;
  34804. }
  34805. var target = this._getTargetPosition();
  34806. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  34807. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  34808. if (!this._collider) {
  34809. this._collider = new BABYLON.Collider();
  34810. }
  34811. this._collider.radius = this.collisionRadius;
  34812. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  34813. this._collisionTriggered = true;
  34814. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  34815. }
  34816. else {
  34817. this.position.copyFrom(this._newPosition);
  34818. var up = this.upVector;
  34819. if (this.allowUpsideDown && sinb < 0) {
  34820. up = up.clone();
  34821. up = up.negate();
  34822. }
  34823. if (this.getScene().useRightHandedSystem) {
  34824. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  34825. }
  34826. else {
  34827. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  34828. }
  34829. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  34830. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  34831. }
  34832. this._currentTarget = target;
  34833. return this._viewMatrix;
  34834. };
  34835. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  34836. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  34837. meshes = meshes || this.getScene().meshes;
  34838. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  34839. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  34840. this.radius = distance * this.zoomOnFactor;
  34841. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  34842. };
  34843. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  34844. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  34845. var meshesOrMinMaxVector;
  34846. var distance;
  34847. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  34848. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  34849. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  34850. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  34851. }
  34852. else {
  34853. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  34854. distance = meshesOrMinMaxVectorAndDistance.distance;
  34855. }
  34856. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  34857. if (!doNotUpdateMaxZ) {
  34858. this.maxZ = distance * 2;
  34859. }
  34860. };
  34861. /**
  34862. * @override
  34863. * Override Camera.createRigCamera
  34864. */
  34865. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  34866. var alphaShift;
  34867. switch (this.cameraRigMode) {
  34868. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  34869. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  34870. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  34871. case BABYLON.Camera.RIG_MODE_VR:
  34872. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  34873. break;
  34874. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  34875. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  34876. break;
  34877. }
  34878. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  34879. rigCam._cameraRigParams = {};
  34880. return rigCam;
  34881. };
  34882. /**
  34883. * @override
  34884. * Override Camera._updateRigCameras
  34885. */
  34886. ArcRotateCamera.prototype._updateRigCameras = function () {
  34887. var camLeft = this._rigCameras[0];
  34888. var camRight = this._rigCameras[1];
  34889. camLeft.beta = camRight.beta = this.beta;
  34890. camLeft.radius = camRight.radius = this.radius;
  34891. switch (this.cameraRigMode) {
  34892. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  34893. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  34894. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  34895. case BABYLON.Camera.RIG_MODE_VR:
  34896. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  34897. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  34898. break;
  34899. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  34900. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  34901. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  34902. break;
  34903. }
  34904. _super.prototype._updateRigCameras.call(this);
  34905. };
  34906. ArcRotateCamera.prototype.dispose = function () {
  34907. this.inputs.clear();
  34908. _super.prototype.dispose.call(this);
  34909. };
  34910. ArcRotateCamera.prototype.getClassName = function () {
  34911. return "ArcRotateCamera";
  34912. };
  34913. return ArcRotateCamera;
  34914. }(BABYLON.TargetCamera));
  34915. __decorate([
  34916. BABYLON.serialize()
  34917. ], ArcRotateCamera.prototype, "alpha", void 0);
  34918. __decorate([
  34919. BABYLON.serialize()
  34920. ], ArcRotateCamera.prototype, "beta", void 0);
  34921. __decorate([
  34922. BABYLON.serialize()
  34923. ], ArcRotateCamera.prototype, "radius", void 0);
  34924. __decorate([
  34925. BABYLON.serializeAsVector3("target")
  34926. ], ArcRotateCamera.prototype, "_target", void 0);
  34927. __decorate([
  34928. BABYLON.serialize()
  34929. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  34930. __decorate([
  34931. BABYLON.serialize()
  34932. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  34933. __decorate([
  34934. BABYLON.serialize()
  34935. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  34936. __decorate([
  34937. BABYLON.serialize()
  34938. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  34939. __decorate([
  34940. BABYLON.serialize()
  34941. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  34942. __decorate([
  34943. BABYLON.serialize()
  34944. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  34945. __decorate([
  34946. BABYLON.serialize()
  34947. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  34948. __decorate([
  34949. BABYLON.serialize()
  34950. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  34951. __decorate([
  34952. BABYLON.serialize()
  34953. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  34954. __decorate([
  34955. BABYLON.serialize()
  34956. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  34957. __decorate([
  34958. BABYLON.serialize()
  34959. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  34960. __decorate([
  34961. BABYLON.serialize()
  34962. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  34963. __decorate([
  34964. BABYLON.serialize()
  34965. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  34966. __decorate([
  34967. BABYLON.serialize()
  34968. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  34969. BABYLON.ArcRotateCamera = ArcRotateCamera;
  34970. })(BABYLON || (BABYLON = {}));
  34971. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  34972. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  34973. var BABYLON;
  34974. (function (BABYLON) {
  34975. var ArcRotateCameraInputsManager = (function (_super) {
  34976. __extends(ArcRotateCameraInputsManager, _super);
  34977. function ArcRotateCameraInputsManager(camera) {
  34978. return _super.call(this, camera) || this;
  34979. }
  34980. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  34981. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  34982. return this;
  34983. };
  34984. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  34985. this.add(new BABYLON.ArcRotateCameraPointersInput());
  34986. return this;
  34987. };
  34988. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  34989. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  34990. return this;
  34991. };
  34992. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  34993. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  34994. return this;
  34995. };
  34996. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  34997. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  34998. return this;
  34999. };
  35000. return ArcRotateCameraInputsManager;
  35001. }(BABYLON.CameraInputsManager));
  35002. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  35003. })(BABYLON || (BABYLON = {}));
  35004. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  35005. var BABYLON;
  35006. (function (BABYLON) {
  35007. var HemisphericLight = (function (_super) {
  35008. __extends(HemisphericLight, _super);
  35009. /**
  35010. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  35011. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  35012. * The HemisphericLight can't cast shadows.
  35013. * Documentation : http://doc.babylonjs.com/tutorials/lights
  35014. */
  35015. function HemisphericLight(name, direction, scene) {
  35016. var _this = _super.call(this, name, scene) || this;
  35017. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  35018. _this.direction = direction || BABYLON.Vector3.Up();
  35019. return _this;
  35020. }
  35021. HemisphericLight.prototype._buildUniformLayout = function () {
  35022. this._uniformBuffer.addUniform("vLightData", 4);
  35023. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  35024. this._uniformBuffer.addUniform("vLightSpecular", 3);
  35025. this._uniformBuffer.addUniform("vLightGround", 3);
  35026. this._uniformBuffer.addUniform("shadowsInfo", 3);
  35027. this._uniformBuffer.addUniform("depthValues", 2);
  35028. this._uniformBuffer.create();
  35029. };
  35030. /**
  35031. * Returns the string "HemisphericLight".
  35032. */
  35033. HemisphericLight.prototype.getClassName = function () {
  35034. return "HemisphericLight";
  35035. };
  35036. /**
  35037. * Sets the HemisphericLight direction towards the passed target (Vector3).
  35038. * Returns the updated direction.
  35039. */
  35040. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  35041. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  35042. return this.direction;
  35043. };
  35044. HemisphericLight.prototype.getShadowGenerator = function () {
  35045. return null;
  35046. };
  35047. /**
  35048. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  35049. * Returns the HemisphericLight.
  35050. */
  35051. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  35052. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  35053. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  35054. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  35055. return this;
  35056. };
  35057. HemisphericLight.prototype._getWorldMatrix = function () {
  35058. if (!this._worldMatrix) {
  35059. this._worldMatrix = BABYLON.Matrix.Identity();
  35060. }
  35061. return this._worldMatrix;
  35062. };
  35063. /**
  35064. * Returns the integer 3.
  35065. */
  35066. HemisphericLight.prototype.getTypeID = function () {
  35067. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  35068. };
  35069. return HemisphericLight;
  35070. }(BABYLON.Light));
  35071. __decorate([
  35072. BABYLON.serializeAsColor3()
  35073. ], HemisphericLight.prototype, "groundColor", void 0);
  35074. __decorate([
  35075. BABYLON.serializeAsVector3()
  35076. ], HemisphericLight.prototype, "direction", void 0);
  35077. BABYLON.HemisphericLight = HemisphericLight;
  35078. })(BABYLON || (BABYLON = {}));
  35079. //# sourceMappingURL=babylon.hemisphericLight.js.map
  35080. var BABYLON;
  35081. (function (BABYLON) {
  35082. var ShadowLight = (function (_super) {
  35083. __extends(ShadowLight, _super);
  35084. function ShadowLight() {
  35085. var _this = _super !== null && _super.apply(this, arguments) || this;
  35086. _this._needProjectionMatrixCompute = true;
  35087. return _this;
  35088. }
  35089. Object.defineProperty(ShadowLight.prototype, "direction", {
  35090. get: function () {
  35091. return this._direction;
  35092. },
  35093. set: function (value) {
  35094. this._direction = value;
  35095. },
  35096. enumerable: true,
  35097. configurable: true
  35098. });
  35099. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  35100. get: function () {
  35101. return this._shadowMinZ;
  35102. },
  35103. set: function (value) {
  35104. this._shadowMinZ = value;
  35105. this.forceProjectionMatrixCompute();
  35106. },
  35107. enumerable: true,
  35108. configurable: true
  35109. });
  35110. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  35111. get: function () {
  35112. return this._shadowMaxZ;
  35113. },
  35114. set: function (value) {
  35115. this._shadowMaxZ = value;
  35116. this.forceProjectionMatrixCompute();
  35117. },
  35118. enumerable: true,
  35119. configurable: true
  35120. });
  35121. /**
  35122. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  35123. */
  35124. ShadowLight.prototype.computeTransformedInformation = function () {
  35125. if (this.parent && this.parent.getWorldMatrix) {
  35126. if (!this.transformedPosition) {
  35127. this.transformedPosition = BABYLON.Vector3.Zero();
  35128. }
  35129. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  35130. // In case the direction is present.
  35131. if (this.direction) {
  35132. if (!this.transformedDirection) {
  35133. this.transformedDirection = BABYLON.Vector3.Zero();
  35134. }
  35135. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  35136. }
  35137. return true;
  35138. }
  35139. return false;
  35140. };
  35141. /**
  35142. * Return the depth scale used for the shadow map.
  35143. */
  35144. ShadowLight.prototype.getDepthScale = function () {
  35145. return 50.0;
  35146. };
  35147. /**
  35148. * Returns the light direction (Vector3) for any passed face index.
  35149. */
  35150. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  35151. return this.transformedDirection ? this.transformedDirection : this.direction;
  35152. };
  35153. /**
  35154. * Returns the DirectionalLight absolute position in the World.
  35155. */
  35156. ShadowLight.prototype.getAbsolutePosition = function () {
  35157. return this.transformedPosition ? this.transformedPosition : this.position;
  35158. };
  35159. /**
  35160. * Sets the DirectionalLight direction toward the passed target (Vector3).
  35161. * Returns the updated DirectionalLight direction (Vector3).
  35162. */
  35163. ShadowLight.prototype.setDirectionToTarget = function (target) {
  35164. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  35165. return this.direction;
  35166. };
  35167. /**
  35168. * Returns the light rotation (Vector3).
  35169. */
  35170. ShadowLight.prototype.getRotation = function () {
  35171. this.direction.normalize();
  35172. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  35173. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  35174. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  35175. };
  35176. /**
  35177. * Boolean : false by default.
  35178. */
  35179. ShadowLight.prototype.needCube = function () {
  35180. return false;
  35181. };
  35182. /**
  35183. * Specifies wether or not the projection matrix should be recomputed this frame.
  35184. */
  35185. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  35186. return this._needProjectionMatrixCompute;
  35187. };
  35188. /**
  35189. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  35190. */
  35191. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  35192. this._needProjectionMatrixCompute = true;
  35193. };
  35194. /**
  35195. * Get the world matrix of the sahdow lights.
  35196. */
  35197. ShadowLight.prototype._getWorldMatrix = function () {
  35198. if (!this._worldMatrix) {
  35199. this._worldMatrix = BABYLON.Matrix.Identity();
  35200. }
  35201. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  35202. return this._worldMatrix;
  35203. };
  35204. /**
  35205. * Gets the minZ used for shadow according to both the scene and the light.
  35206. * @param activeCamera
  35207. */
  35208. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  35209. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  35210. };
  35211. /**
  35212. * Gets the maxZ used for shadow according to both the scene and the light.
  35213. * @param activeCamera
  35214. */
  35215. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  35216. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  35217. };
  35218. /**
  35219. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  35220. * Returns the light.
  35221. */
  35222. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  35223. if (this.customProjectionMatrixBuilder) {
  35224. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  35225. }
  35226. else {
  35227. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  35228. }
  35229. return this;
  35230. };
  35231. return ShadowLight;
  35232. }(BABYLON.Light));
  35233. __decorate([
  35234. BABYLON.serializeAsVector3()
  35235. ], ShadowLight.prototype, "position", void 0);
  35236. __decorate([
  35237. BABYLON.serializeAsVector3()
  35238. ], ShadowLight.prototype, "direction", null);
  35239. __decorate([
  35240. BABYLON.serialize()
  35241. ], ShadowLight.prototype, "shadowMinZ", null);
  35242. __decorate([
  35243. BABYLON.serialize()
  35244. ], ShadowLight.prototype, "shadowMaxZ", null);
  35245. BABYLON.ShadowLight = ShadowLight;
  35246. })(BABYLON || (BABYLON = {}));
  35247. //# sourceMappingURL=babylon.shadowLight.js.map
  35248. var BABYLON;
  35249. (function (BABYLON) {
  35250. var PointLight = (function (_super) {
  35251. __extends(PointLight, _super);
  35252. /**
  35253. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  35254. * A PointLight emits the light in every direction.
  35255. * It can cast shadows.
  35256. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  35257. * ```javascript
  35258. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  35259. * ```
  35260. * Documentation : http://doc.babylonjs.com/tutorials/lights
  35261. */
  35262. function PointLight(name, position, scene) {
  35263. var _this = _super.call(this, name, scene) || this;
  35264. _this._shadowAngle = Math.PI / 2;
  35265. _this.position = position;
  35266. return _this;
  35267. }
  35268. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  35269. /**
  35270. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  35271. * This specifies what angle the shadow will use to be created.
  35272. *
  35273. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  35274. */
  35275. get: function () {
  35276. return this._shadowAngle;
  35277. },
  35278. /**
  35279. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  35280. * This specifies what angle the shadow will use to be created.
  35281. *
  35282. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  35283. */
  35284. set: function (value) {
  35285. this._shadowAngle = value;
  35286. this.forceProjectionMatrixCompute();
  35287. },
  35288. enumerable: true,
  35289. configurable: true
  35290. });
  35291. Object.defineProperty(PointLight.prototype, "direction", {
  35292. get: function () {
  35293. return this._direction;
  35294. },
  35295. /**
  35296. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  35297. */
  35298. set: function (value) {
  35299. var previousNeedCube = this.needCube();
  35300. this._direction = value;
  35301. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  35302. this._shadowGenerator.recreateShadowMap();
  35303. }
  35304. },
  35305. enumerable: true,
  35306. configurable: true
  35307. });
  35308. /**
  35309. * Returns the string "PointLight"
  35310. */
  35311. PointLight.prototype.getClassName = function () {
  35312. return "PointLight";
  35313. };
  35314. /**
  35315. * Returns the integer 0.
  35316. */
  35317. PointLight.prototype.getTypeID = function () {
  35318. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  35319. };
  35320. /**
  35321. * Specifies wether or not the shadowmap should be a cube texture.
  35322. */
  35323. PointLight.prototype.needCube = function () {
  35324. return !this.direction;
  35325. };
  35326. /**
  35327. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  35328. */
  35329. PointLight.prototype.getShadowDirection = function (faceIndex) {
  35330. if (this.direction) {
  35331. return _super.prototype.getShadowDirection.call(this, faceIndex);
  35332. }
  35333. else {
  35334. switch (faceIndex) {
  35335. case 0:
  35336. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  35337. case 1:
  35338. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  35339. case 2:
  35340. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  35341. case 3:
  35342. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  35343. case 4:
  35344. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  35345. case 5:
  35346. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  35347. }
  35348. }
  35349. return BABYLON.Vector3.Zero();
  35350. };
  35351. /**
  35352. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  35353. * - fov = PI / 2
  35354. * - aspect ratio : 1.0
  35355. * - z-near and far equal to the active camera minZ and maxZ.
  35356. * Returns the PointLight.
  35357. */
  35358. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  35359. var activeCamera = this.getScene().activeCamera;
  35360. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  35361. };
  35362. PointLight.prototype._buildUniformLayout = function () {
  35363. this._uniformBuffer.addUniform("vLightData", 4);
  35364. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  35365. this._uniformBuffer.addUniform("vLightSpecular", 3);
  35366. this._uniformBuffer.addUniform("shadowsInfo", 3);
  35367. this._uniformBuffer.addUniform("depthValues", 2);
  35368. this._uniformBuffer.create();
  35369. };
  35370. /**
  35371. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  35372. * Returns the PointLight.
  35373. */
  35374. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  35375. if (this.computeTransformedInformation()) {
  35376. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  35377. return this;
  35378. }
  35379. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  35380. return this;
  35381. };
  35382. return PointLight;
  35383. }(BABYLON.ShadowLight));
  35384. __decorate([
  35385. BABYLON.serialize()
  35386. ], PointLight.prototype, "shadowAngle", null);
  35387. BABYLON.PointLight = PointLight;
  35388. })(BABYLON || (BABYLON = {}));
  35389. //# sourceMappingURL=babylon.pointLight.js.map
  35390. /// <reference path="babylon.light.ts" />
  35391. var BABYLON;
  35392. (function (BABYLON) {
  35393. var DirectionalLight = (function (_super) {
  35394. __extends(DirectionalLight, _super);
  35395. /**
  35396. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  35397. * The directional light is emitted from everywhere in the given direction.
  35398. * It can cast shawdows.
  35399. * Documentation : http://doc.babylonjs.com/tutorials/lights
  35400. */
  35401. function DirectionalLight(name, direction, scene) {
  35402. var _this = _super.call(this, name, scene) || this;
  35403. _this._shadowFrustumSize = 0;
  35404. _this._shadowOrthoScale = 0.5;
  35405. _this.autoUpdateExtends = true;
  35406. // Cache
  35407. _this._orthoLeft = Number.MAX_VALUE;
  35408. _this._orthoRight = Number.MIN_VALUE;
  35409. _this._orthoTop = Number.MIN_VALUE;
  35410. _this._orthoBottom = Number.MAX_VALUE;
  35411. _this.position = direction.scale(-1.0);
  35412. _this.direction = direction;
  35413. return _this;
  35414. }
  35415. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  35416. /**
  35417. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  35418. */
  35419. get: function () {
  35420. return this._shadowFrustumSize;
  35421. },
  35422. /**
  35423. * Specifies a fix frustum size for the shadow generation.
  35424. */
  35425. set: function (value) {
  35426. this._shadowFrustumSize = value;
  35427. this.forceProjectionMatrixCompute();
  35428. },
  35429. enumerable: true,
  35430. configurable: true
  35431. });
  35432. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  35433. get: function () {
  35434. return this._shadowOrthoScale;
  35435. },
  35436. set: function (value) {
  35437. this._shadowOrthoScale = value;
  35438. this.forceProjectionMatrixCompute();
  35439. },
  35440. enumerable: true,
  35441. configurable: true
  35442. });
  35443. /**
  35444. * Returns the string "DirectionalLight".
  35445. */
  35446. DirectionalLight.prototype.getClassName = function () {
  35447. return "DirectionalLight";
  35448. };
  35449. /**
  35450. * Returns the integer 1.
  35451. */
  35452. DirectionalLight.prototype.getTypeID = function () {
  35453. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  35454. };
  35455. /**
  35456. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  35457. * Returns the DirectionalLight Shadow projection matrix.
  35458. */
  35459. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  35460. if (this.shadowFrustumSize > 0) {
  35461. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  35462. }
  35463. else {
  35464. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  35465. }
  35466. };
  35467. /**
  35468. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  35469. * Returns the DirectionalLight Shadow projection matrix.
  35470. */
  35471. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  35472. var activeCamera = this.getScene().activeCamera;
  35473. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  35474. };
  35475. /**
  35476. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  35477. * Returns the DirectionalLight Shadow projection matrix.
  35478. */
  35479. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  35480. var activeCamera = this.getScene().activeCamera;
  35481. // Check extends
  35482. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  35483. var tempVector3 = BABYLON.Vector3.Zero();
  35484. this._orthoLeft = Number.MAX_VALUE;
  35485. this._orthoRight = Number.MIN_VALUE;
  35486. this._orthoTop = Number.MIN_VALUE;
  35487. this._orthoBottom = Number.MAX_VALUE;
  35488. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  35489. var mesh = renderList[meshIndex];
  35490. if (!mesh) {
  35491. continue;
  35492. }
  35493. var boundingInfo = mesh.getBoundingInfo();
  35494. if (!boundingInfo) {
  35495. continue;
  35496. }
  35497. var boundingBox = boundingInfo.boundingBox;
  35498. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  35499. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  35500. if (tempVector3.x < this._orthoLeft)
  35501. this._orthoLeft = tempVector3.x;
  35502. if (tempVector3.y < this._orthoBottom)
  35503. this._orthoBottom = tempVector3.y;
  35504. if (tempVector3.x > this._orthoRight)
  35505. this._orthoRight = tempVector3.x;
  35506. if (tempVector3.y > this._orthoTop)
  35507. this._orthoTop = tempVector3.y;
  35508. }
  35509. }
  35510. }
  35511. var xOffset = this._orthoRight - this._orthoLeft;
  35512. var yOffset = this._orthoTop - this._orthoBottom;
  35513. 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);
  35514. };
  35515. DirectionalLight.prototype._buildUniformLayout = function () {
  35516. this._uniformBuffer.addUniform("vLightData", 4);
  35517. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  35518. this._uniformBuffer.addUniform("vLightSpecular", 3);
  35519. this._uniformBuffer.addUniform("shadowsInfo", 3);
  35520. this._uniformBuffer.addUniform("depthValues", 2);
  35521. this._uniformBuffer.create();
  35522. };
  35523. /**
  35524. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  35525. * Returns the DirectionalLight.
  35526. */
  35527. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  35528. if (this.computeTransformedInformation()) {
  35529. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  35530. return this;
  35531. }
  35532. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  35533. return this;
  35534. };
  35535. /**
  35536. * Gets the minZ used for shadow according to both the scene and the light.
  35537. *
  35538. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  35539. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  35540. * @param activeCamera
  35541. */
  35542. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  35543. return 1;
  35544. };
  35545. /**
  35546. * Gets the maxZ used for shadow according to both the scene and the light.
  35547. *
  35548. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  35549. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  35550. * @param activeCamera
  35551. */
  35552. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  35553. return 1;
  35554. };
  35555. return DirectionalLight;
  35556. }(BABYLON.ShadowLight));
  35557. __decorate([
  35558. BABYLON.serialize()
  35559. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  35560. __decorate([
  35561. BABYLON.serialize()
  35562. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  35563. __decorate([
  35564. BABYLON.serialize()
  35565. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  35566. BABYLON.DirectionalLight = DirectionalLight;
  35567. })(BABYLON || (BABYLON = {}));
  35568. //# sourceMappingURL=babylon.directionalLight.js.map
  35569. var BABYLON;
  35570. (function (BABYLON) {
  35571. var SpotLight = (function (_super) {
  35572. __extends(SpotLight, _super);
  35573. /**
  35574. * Creates a SpotLight object in the scene with the passed parameters :
  35575. * - `position` (Vector3) is the initial SpotLight position,
  35576. * - `direction` (Vector3) is the initial SpotLight direction,
  35577. * - `angle` (float, in radians) is the spot light cone angle,
  35578. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  35579. * A spot light is a simply light oriented cone.
  35580. * It can cast shadows.
  35581. * Documentation : http://doc.babylonjs.com/tutorials/lights
  35582. */
  35583. function SpotLight(name, position, direction, angle, exponent, scene) {
  35584. var _this = _super.call(this, name, scene) || this;
  35585. _this.position = position;
  35586. _this.direction = direction;
  35587. _this.angle = angle;
  35588. _this.exponent = exponent;
  35589. return _this;
  35590. }
  35591. Object.defineProperty(SpotLight.prototype, "angle", {
  35592. get: function () {
  35593. return this._angle;
  35594. },
  35595. set: function (value) {
  35596. this._angle = value;
  35597. this.forceProjectionMatrixCompute();
  35598. },
  35599. enumerable: true,
  35600. configurable: true
  35601. });
  35602. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  35603. get: function () {
  35604. return this._shadowAngleScale;
  35605. },
  35606. /**
  35607. * Allows scaling the angle of the light for shadow generation only.
  35608. */
  35609. set: function (value) {
  35610. this._shadowAngleScale = value;
  35611. this.forceProjectionMatrixCompute();
  35612. },
  35613. enumerable: true,
  35614. configurable: true
  35615. });
  35616. /**
  35617. * Returns the string "SpotLight".
  35618. */
  35619. SpotLight.prototype.getClassName = function () {
  35620. return "SpotLight";
  35621. };
  35622. /**
  35623. * Returns the integer 2.
  35624. */
  35625. SpotLight.prototype.getTypeID = function () {
  35626. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  35627. };
  35628. /**
  35629. * 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.
  35630. * Returns the SpotLight.
  35631. */
  35632. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  35633. var activeCamera = this.getScene().activeCamera;
  35634. this._shadowAngleScale = this._shadowAngleScale || 1;
  35635. var angle = this._shadowAngleScale * this._angle;
  35636. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  35637. };
  35638. SpotLight.prototype._buildUniformLayout = function () {
  35639. this._uniformBuffer.addUniform("vLightData", 4);
  35640. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  35641. this._uniformBuffer.addUniform("vLightSpecular", 3);
  35642. this._uniformBuffer.addUniform("vLightDirection", 3);
  35643. this._uniformBuffer.addUniform("shadowsInfo", 3);
  35644. this._uniformBuffer.addUniform("depthValues", 2);
  35645. this._uniformBuffer.create();
  35646. };
  35647. /**
  35648. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  35649. * Return the SpotLight.
  35650. */
  35651. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  35652. var normalizeDirection;
  35653. if (this.computeTransformedInformation()) {
  35654. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  35655. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  35656. }
  35657. else {
  35658. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  35659. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  35660. }
  35661. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  35662. return this;
  35663. };
  35664. return SpotLight;
  35665. }(BABYLON.ShadowLight));
  35666. __decorate([
  35667. BABYLON.serialize()
  35668. ], SpotLight.prototype, "angle", null);
  35669. __decorate([
  35670. BABYLON.serialize()
  35671. /**
  35672. * Allows scaling the angle of the light for shadow generation only.
  35673. */
  35674. ], SpotLight.prototype, "shadowAngleScale", null);
  35675. __decorate([
  35676. BABYLON.serialize()
  35677. ], SpotLight.prototype, "exponent", void 0);
  35678. BABYLON.SpotLight = SpotLight;
  35679. })(BABYLON || (BABYLON = {}));
  35680. //# sourceMappingURL=babylon.spotLight.js.map
  35681. var BABYLON;
  35682. (function (BABYLON) {
  35683. var AnimationRange = (function () {
  35684. function AnimationRange(name, from, to) {
  35685. this.name = name;
  35686. this.from = from;
  35687. this.to = to;
  35688. }
  35689. AnimationRange.prototype.clone = function () {
  35690. return new AnimationRange(this.name, this.from, this.to);
  35691. };
  35692. return AnimationRange;
  35693. }());
  35694. BABYLON.AnimationRange = AnimationRange;
  35695. /**
  35696. * Composed of a frame, and an action function
  35697. */
  35698. var AnimationEvent = (function () {
  35699. function AnimationEvent(frame, action, onlyOnce) {
  35700. this.frame = frame;
  35701. this.action = action;
  35702. this.onlyOnce = onlyOnce;
  35703. this.isDone = false;
  35704. }
  35705. return AnimationEvent;
  35706. }());
  35707. BABYLON.AnimationEvent = AnimationEvent;
  35708. var PathCursor = (function () {
  35709. function PathCursor(path) {
  35710. this.path = path;
  35711. this._onchange = new Array();
  35712. this.value = 0;
  35713. this.animations = new Array();
  35714. }
  35715. PathCursor.prototype.getPoint = function () {
  35716. var point = this.path.getPointAtLengthPosition(this.value);
  35717. return new BABYLON.Vector3(point.x, 0, point.y);
  35718. };
  35719. PathCursor.prototype.moveAhead = function (step) {
  35720. if (step === void 0) { step = 0.002; }
  35721. this.move(step);
  35722. return this;
  35723. };
  35724. PathCursor.prototype.moveBack = function (step) {
  35725. if (step === void 0) { step = 0.002; }
  35726. this.move(-step);
  35727. return this;
  35728. };
  35729. PathCursor.prototype.move = function (step) {
  35730. if (Math.abs(step) > 1) {
  35731. throw "step size should be less than 1.";
  35732. }
  35733. this.value += step;
  35734. this.ensureLimits();
  35735. this.raiseOnChange();
  35736. return this;
  35737. };
  35738. PathCursor.prototype.ensureLimits = function () {
  35739. while (this.value > 1) {
  35740. this.value -= 1;
  35741. }
  35742. while (this.value < 0) {
  35743. this.value += 1;
  35744. }
  35745. return this;
  35746. };
  35747. // used by animation engine
  35748. PathCursor.prototype.markAsDirty = function (propertyName) {
  35749. this.ensureLimits();
  35750. this.raiseOnChange();
  35751. return this;
  35752. };
  35753. PathCursor.prototype.raiseOnChange = function () {
  35754. var _this = this;
  35755. this._onchange.forEach(function (f) { return f(_this); });
  35756. return this;
  35757. };
  35758. PathCursor.prototype.onchange = function (f) {
  35759. this._onchange.push(f);
  35760. return this;
  35761. };
  35762. return PathCursor;
  35763. }());
  35764. BABYLON.PathCursor = PathCursor;
  35765. var Animation = (function () {
  35766. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  35767. this.name = name;
  35768. this.targetProperty = targetProperty;
  35769. this.framePerSecond = framePerSecond;
  35770. this.dataType = dataType;
  35771. this.loopMode = loopMode;
  35772. this.enableBlending = enableBlending;
  35773. this._offsetsCache = {};
  35774. this._highLimitsCache = {};
  35775. this._stopped = false;
  35776. this._blendingFactor = 0;
  35777. // The set of event that will be linked to this animation
  35778. this._events = new Array();
  35779. this.allowMatricesInterpolation = false;
  35780. this.blendingSpeed = 0.01;
  35781. this._ranges = {};
  35782. this.targetPropertyPath = targetProperty.split(".");
  35783. this.dataType = dataType;
  35784. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  35785. }
  35786. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  35787. var dataType = undefined;
  35788. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  35789. dataType = Animation.ANIMATIONTYPE_FLOAT;
  35790. }
  35791. else if (from instanceof BABYLON.Quaternion) {
  35792. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  35793. }
  35794. else if (from instanceof BABYLON.Vector3) {
  35795. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  35796. }
  35797. else if (from instanceof BABYLON.Vector2) {
  35798. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  35799. }
  35800. else if (from instanceof BABYLON.Color3) {
  35801. dataType = Animation.ANIMATIONTYPE_COLOR3;
  35802. }
  35803. else if (from instanceof BABYLON.Size) {
  35804. dataType = Animation.ANIMATIONTYPE_SIZE;
  35805. }
  35806. if (dataType == undefined) {
  35807. return null;
  35808. }
  35809. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  35810. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  35811. animation.setKeys(keys);
  35812. if (easingFunction !== undefined) {
  35813. animation.setEasingFunction(easingFunction);
  35814. }
  35815. return animation;
  35816. };
  35817. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  35818. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  35819. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  35820. };
  35821. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  35822. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  35823. node.animations.push(animation);
  35824. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  35825. };
  35826. // Methods
  35827. /**
  35828. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  35829. */
  35830. Animation.prototype.toString = function (fullDetails) {
  35831. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  35832. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  35833. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  35834. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  35835. if (fullDetails) {
  35836. ret += ", Ranges: {";
  35837. var first = true;
  35838. for (var name in this._ranges) {
  35839. if (first) {
  35840. ret += ", ";
  35841. first = false;
  35842. }
  35843. ret += name;
  35844. }
  35845. ret += "}";
  35846. }
  35847. return ret;
  35848. };
  35849. /**
  35850. * Add an event to this animation.
  35851. */
  35852. Animation.prototype.addEvent = function (event) {
  35853. this._events.push(event);
  35854. };
  35855. /**
  35856. * Remove all events found at the given frame
  35857. * @param frame
  35858. */
  35859. Animation.prototype.removeEvents = function (frame) {
  35860. for (var index = 0; index < this._events.length; index++) {
  35861. if (this._events[index].frame === frame) {
  35862. this._events.splice(index, 1);
  35863. index--;
  35864. }
  35865. }
  35866. };
  35867. Animation.prototype.createRange = function (name, from, to) {
  35868. // check name not already in use; could happen for bones after serialized
  35869. if (!this._ranges[name]) {
  35870. this._ranges[name] = new AnimationRange(name, from, to);
  35871. }
  35872. };
  35873. Animation.prototype.deleteRange = function (name, deleteFrames) {
  35874. if (deleteFrames === void 0) { deleteFrames = true; }
  35875. if (this._ranges[name]) {
  35876. if (deleteFrames) {
  35877. var from = this._ranges[name].from;
  35878. var to = this._ranges[name].to;
  35879. // this loop MUST go high to low for multiple splices to work
  35880. for (var key = this._keys.length - 1; key >= 0; key--) {
  35881. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  35882. this._keys.splice(key, 1);
  35883. }
  35884. }
  35885. }
  35886. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  35887. }
  35888. };
  35889. Animation.prototype.getRange = function (name) {
  35890. return this._ranges[name];
  35891. };
  35892. Animation.prototype.reset = function () {
  35893. this._offsetsCache = {};
  35894. this._highLimitsCache = {};
  35895. this.currentFrame = 0;
  35896. this._blendingFactor = 0;
  35897. this._originalBlendValue = null;
  35898. };
  35899. Animation.prototype.isStopped = function () {
  35900. return this._stopped;
  35901. };
  35902. Animation.prototype.getKeys = function () {
  35903. return this._keys;
  35904. };
  35905. Animation.prototype.getHighestFrame = function () {
  35906. var ret = 0;
  35907. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  35908. if (ret < this._keys[key].frame) {
  35909. ret = this._keys[key].frame;
  35910. }
  35911. }
  35912. return ret;
  35913. };
  35914. Animation.prototype.getEasingFunction = function () {
  35915. return this._easingFunction;
  35916. };
  35917. Animation.prototype.setEasingFunction = function (easingFunction) {
  35918. this._easingFunction = easingFunction;
  35919. };
  35920. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  35921. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  35922. };
  35923. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  35924. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  35925. };
  35926. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  35927. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  35928. };
  35929. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  35930. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  35931. };
  35932. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  35933. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  35934. };
  35935. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  35936. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  35937. };
  35938. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  35939. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  35940. };
  35941. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  35942. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  35943. };
  35944. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  35945. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  35946. };
  35947. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  35948. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  35949. };
  35950. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  35951. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  35952. };
  35953. Animation.prototype.clone = function () {
  35954. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  35955. clone.enableBlending = this.enableBlending;
  35956. clone.blendingSpeed = this.blendingSpeed;
  35957. if (this._keys) {
  35958. clone.setKeys(this._keys);
  35959. }
  35960. if (this._ranges) {
  35961. clone._ranges = {};
  35962. for (var name in this._ranges) {
  35963. clone._ranges[name] = this._ranges[name].clone();
  35964. }
  35965. }
  35966. return clone;
  35967. };
  35968. Animation.prototype.setKeys = function (values) {
  35969. this._keys = values.slice(0);
  35970. this._offsetsCache = {};
  35971. this._highLimitsCache = {};
  35972. };
  35973. Animation.prototype._getKeyValue = function (value) {
  35974. if (typeof value === "function") {
  35975. return value();
  35976. }
  35977. return value;
  35978. };
  35979. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  35980. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  35981. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  35982. }
  35983. this.currentFrame = currentFrame;
  35984. // Try to get a hash to find the right key
  35985. 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));
  35986. if (this._keys[startKeyIndex].frame >= currentFrame) {
  35987. while (startKeyIndex - 1 >= 0 && this._keys[startKeyIndex].frame >= currentFrame) {
  35988. startKeyIndex--;
  35989. }
  35990. }
  35991. for (var key = startKeyIndex; key < this._keys.length; key++) {
  35992. var endKey = this._keys[key + 1];
  35993. if (endKey.frame >= currentFrame) {
  35994. var startKey = this._keys[key];
  35995. var startValue = this._getKeyValue(startKey.value);
  35996. var endValue = this._getKeyValue(endKey.value);
  35997. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  35998. var frameDelta = endKey.frame - startKey.frame;
  35999. // gradient : percent of currentFrame between the frame inf and the frame sup
  36000. var gradient = (currentFrame - startKey.frame) / frameDelta;
  36001. // check for easingFunction and correction of gradient
  36002. if (this._easingFunction != null) {
  36003. gradient = this._easingFunction.ease(gradient);
  36004. }
  36005. switch (this.dataType) {
  36006. // Float
  36007. case Animation.ANIMATIONTYPE_FLOAT:
  36008. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  36009. switch (loopMode) {
  36010. case Animation.ANIMATIONLOOPMODE_CYCLE:
  36011. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  36012. return floatValue;
  36013. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  36014. return offsetValue * repeatCount + floatValue;
  36015. }
  36016. break;
  36017. // Quaternion
  36018. case Animation.ANIMATIONTYPE_QUATERNION:
  36019. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  36020. switch (loopMode) {
  36021. case Animation.ANIMATIONLOOPMODE_CYCLE:
  36022. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  36023. return quatValue;
  36024. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  36025. return quatValue.add(offsetValue.scale(repeatCount));
  36026. }
  36027. return quatValue;
  36028. // Vector3
  36029. case Animation.ANIMATIONTYPE_VECTOR3:
  36030. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  36031. switch (loopMode) {
  36032. case Animation.ANIMATIONLOOPMODE_CYCLE:
  36033. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  36034. return vec3Value;
  36035. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  36036. return vec3Value.add(offsetValue.scale(repeatCount));
  36037. }
  36038. // Vector2
  36039. case Animation.ANIMATIONTYPE_VECTOR2:
  36040. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  36041. switch (loopMode) {
  36042. case Animation.ANIMATIONLOOPMODE_CYCLE:
  36043. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  36044. return vec2Value;
  36045. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  36046. return vec2Value.add(offsetValue.scale(repeatCount));
  36047. }
  36048. // Size
  36049. case Animation.ANIMATIONTYPE_SIZE:
  36050. switch (loopMode) {
  36051. case Animation.ANIMATIONLOOPMODE_CYCLE:
  36052. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  36053. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  36054. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  36055. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  36056. }
  36057. // Color3
  36058. case Animation.ANIMATIONTYPE_COLOR3:
  36059. switch (loopMode) {
  36060. case Animation.ANIMATIONLOOPMODE_CYCLE:
  36061. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  36062. return this.color3InterpolateFunction(startValue, endValue, gradient);
  36063. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  36064. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  36065. }
  36066. // Matrix
  36067. case Animation.ANIMATIONTYPE_MATRIX:
  36068. switch (loopMode) {
  36069. case Animation.ANIMATIONLOOPMODE_CYCLE:
  36070. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  36071. if (this.allowMatricesInterpolation) {
  36072. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  36073. }
  36074. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  36075. return startValue;
  36076. }
  36077. default:
  36078. break;
  36079. }
  36080. break;
  36081. }
  36082. }
  36083. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  36084. };
  36085. Animation.prototype.setValue = function (currentValue, blend) {
  36086. if (blend === void 0) { blend = false; }
  36087. // Set value
  36088. var path;
  36089. var destination;
  36090. if (this.targetPropertyPath.length > 1) {
  36091. var property = this._target[this.targetPropertyPath[0]];
  36092. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  36093. property = property[this.targetPropertyPath[index]];
  36094. }
  36095. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  36096. destination = property;
  36097. }
  36098. else {
  36099. path = this.targetPropertyPath[0];
  36100. destination = this._target;
  36101. }
  36102. // Blending
  36103. if (this.enableBlending && this._blendingFactor <= 1.0) {
  36104. if (!this._originalBlendValue) {
  36105. if (destination[path].clone) {
  36106. this._originalBlendValue = destination[path].clone();
  36107. }
  36108. else {
  36109. this._originalBlendValue = destination[path];
  36110. }
  36111. }
  36112. if (this._originalBlendValue.prototype) {
  36113. if (this._originalBlendValue.prototype.Lerp) {
  36114. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  36115. }
  36116. else {
  36117. destination[path] = currentValue;
  36118. }
  36119. }
  36120. else if (this._originalBlendValue.m) {
  36121. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  36122. }
  36123. else {
  36124. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  36125. }
  36126. this._blendingFactor += this.blendingSpeed;
  36127. }
  36128. else {
  36129. destination[path] = currentValue;
  36130. }
  36131. if (this._target.markAsDirty) {
  36132. this._target.markAsDirty(this.targetProperty);
  36133. }
  36134. };
  36135. Animation.prototype.goToFrame = function (frame) {
  36136. if (frame < this._keys[0].frame) {
  36137. frame = this._keys[0].frame;
  36138. }
  36139. else if (frame > this._keys[this._keys.length - 1].frame) {
  36140. frame = this._keys[this._keys.length - 1].frame;
  36141. }
  36142. var currentValue = this._interpolate(frame, 0, this.loopMode);
  36143. this.setValue(currentValue);
  36144. };
  36145. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  36146. if (blend === void 0) { blend = false; }
  36147. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  36148. this._stopped = true;
  36149. return false;
  36150. }
  36151. var returnValue = true;
  36152. // Adding a start key at frame 0 if missing
  36153. if (this._keys[0].frame !== 0) {
  36154. var newKey = { frame: 0, value: this._keys[0].value };
  36155. this._keys.splice(0, 0, newKey);
  36156. }
  36157. // Check limits
  36158. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  36159. from = this._keys[0].frame;
  36160. }
  36161. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  36162. to = this._keys[this._keys.length - 1].frame;
  36163. }
  36164. //to and from cannot be the same key
  36165. if (from === to) {
  36166. from++;
  36167. }
  36168. // Compute ratio
  36169. var range = to - from;
  36170. var offsetValue;
  36171. // ratio represents the frame delta between from and to
  36172. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  36173. var highLimitValue = 0;
  36174. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  36175. returnValue = false;
  36176. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  36177. }
  36178. else {
  36179. // Get max value if required
  36180. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  36181. var keyOffset = to.toString() + from.toString();
  36182. if (!this._offsetsCache[keyOffset]) {
  36183. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  36184. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  36185. switch (this.dataType) {
  36186. // Float
  36187. case Animation.ANIMATIONTYPE_FLOAT:
  36188. this._offsetsCache[keyOffset] = toValue - fromValue;
  36189. break;
  36190. // Quaternion
  36191. case Animation.ANIMATIONTYPE_QUATERNION:
  36192. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  36193. break;
  36194. // Vector3
  36195. case Animation.ANIMATIONTYPE_VECTOR3:
  36196. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  36197. // Vector2
  36198. case Animation.ANIMATIONTYPE_VECTOR2:
  36199. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  36200. // Size
  36201. case Animation.ANIMATIONTYPE_SIZE:
  36202. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  36203. // Color3
  36204. case Animation.ANIMATIONTYPE_COLOR3:
  36205. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  36206. default:
  36207. break;
  36208. }
  36209. this._highLimitsCache[keyOffset] = toValue;
  36210. }
  36211. highLimitValue = this._highLimitsCache[keyOffset];
  36212. offsetValue = this._offsetsCache[keyOffset];
  36213. }
  36214. }
  36215. if (offsetValue === undefined) {
  36216. switch (this.dataType) {
  36217. // Float
  36218. case Animation.ANIMATIONTYPE_FLOAT:
  36219. offsetValue = 0;
  36220. break;
  36221. // Quaternion
  36222. case Animation.ANIMATIONTYPE_QUATERNION:
  36223. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  36224. break;
  36225. // Vector3
  36226. case Animation.ANIMATIONTYPE_VECTOR3:
  36227. offsetValue = BABYLON.Vector3.Zero();
  36228. break;
  36229. // Vector2
  36230. case Animation.ANIMATIONTYPE_VECTOR2:
  36231. offsetValue = BABYLON.Vector2.Zero();
  36232. break;
  36233. // Size
  36234. case Animation.ANIMATIONTYPE_SIZE:
  36235. offsetValue = BABYLON.Size.Zero();
  36236. break;
  36237. // Color3
  36238. case Animation.ANIMATIONTYPE_COLOR3:
  36239. offsetValue = BABYLON.Color3.Black();
  36240. }
  36241. }
  36242. // Compute value
  36243. var repeatCount = (ratio / range) >> 0;
  36244. var currentFrame = returnValue ? from + ratio % range : to;
  36245. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  36246. // Set value
  36247. this.setValue(currentValue);
  36248. // Check events
  36249. for (var index = 0; index < this._events.length; index++) {
  36250. // Make sure current frame has passed event frame and that event frame is within the current range
  36251. // Also, handle both forward and reverse animations
  36252. if ((range > 0 && currentFrame >= this._events[index].frame && this._events[index].frame >= from) ||
  36253. (range < 0 && currentFrame <= this._events[index].frame && this._events[index].frame <= from)) {
  36254. var event = this._events[index];
  36255. if (!event.isDone) {
  36256. // If event should be done only once, remove it.
  36257. if (event.onlyOnce) {
  36258. this._events.splice(index, 1);
  36259. index--;
  36260. }
  36261. event.isDone = true;
  36262. event.action();
  36263. } // Don't do anything if the event has already be done.
  36264. }
  36265. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  36266. // reset event, the animation is looping
  36267. this._events[index].isDone = false;
  36268. }
  36269. }
  36270. if (!returnValue) {
  36271. this._stopped = true;
  36272. }
  36273. return returnValue;
  36274. };
  36275. Animation.prototype.serialize = function () {
  36276. var serializationObject = {};
  36277. serializationObject.name = this.name;
  36278. serializationObject.property = this.targetProperty;
  36279. serializationObject.framePerSecond = this.framePerSecond;
  36280. serializationObject.dataType = this.dataType;
  36281. serializationObject.loopBehavior = this.loopMode;
  36282. serializationObject.enableBlending = this.enableBlending;
  36283. serializationObject.blendingSpeed = this.blendingSpeed;
  36284. var dataType = this.dataType;
  36285. serializationObject.keys = [];
  36286. var keys = this.getKeys();
  36287. for (var index = 0; index < keys.length; index++) {
  36288. var animationKey = keys[index];
  36289. var key = {};
  36290. key.frame = animationKey.frame;
  36291. switch (dataType) {
  36292. case Animation.ANIMATIONTYPE_FLOAT:
  36293. key.values = [animationKey.value];
  36294. break;
  36295. case Animation.ANIMATIONTYPE_QUATERNION:
  36296. case Animation.ANIMATIONTYPE_MATRIX:
  36297. case Animation.ANIMATIONTYPE_VECTOR3:
  36298. case Animation.ANIMATIONTYPE_COLOR3:
  36299. key.values = animationKey.value.asArray();
  36300. break;
  36301. }
  36302. serializationObject.keys.push(key);
  36303. }
  36304. serializationObject.ranges = [];
  36305. for (var name in this._ranges) {
  36306. var range = {};
  36307. range.name = name;
  36308. range.from = this._ranges[name].from;
  36309. range.to = this._ranges[name].to;
  36310. serializationObject.ranges.push(range);
  36311. }
  36312. return serializationObject;
  36313. };
  36314. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  36315. get: function () {
  36316. return Animation._ANIMATIONTYPE_FLOAT;
  36317. },
  36318. enumerable: true,
  36319. configurable: true
  36320. });
  36321. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  36322. get: function () {
  36323. return Animation._ANIMATIONTYPE_VECTOR3;
  36324. },
  36325. enumerable: true,
  36326. configurable: true
  36327. });
  36328. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  36329. get: function () {
  36330. return Animation._ANIMATIONTYPE_VECTOR2;
  36331. },
  36332. enumerable: true,
  36333. configurable: true
  36334. });
  36335. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  36336. get: function () {
  36337. return Animation._ANIMATIONTYPE_SIZE;
  36338. },
  36339. enumerable: true,
  36340. configurable: true
  36341. });
  36342. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  36343. get: function () {
  36344. return Animation._ANIMATIONTYPE_QUATERNION;
  36345. },
  36346. enumerable: true,
  36347. configurable: true
  36348. });
  36349. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  36350. get: function () {
  36351. return Animation._ANIMATIONTYPE_MATRIX;
  36352. },
  36353. enumerable: true,
  36354. configurable: true
  36355. });
  36356. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  36357. get: function () {
  36358. return Animation._ANIMATIONTYPE_COLOR3;
  36359. },
  36360. enumerable: true,
  36361. configurable: true
  36362. });
  36363. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  36364. get: function () {
  36365. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  36366. },
  36367. enumerable: true,
  36368. configurable: true
  36369. });
  36370. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  36371. get: function () {
  36372. return Animation._ANIMATIONLOOPMODE_CYCLE;
  36373. },
  36374. enumerable: true,
  36375. configurable: true
  36376. });
  36377. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  36378. get: function () {
  36379. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  36380. },
  36381. enumerable: true,
  36382. configurable: true
  36383. });
  36384. Animation.Parse = function (parsedAnimation) {
  36385. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  36386. var dataType = parsedAnimation.dataType;
  36387. var keys = [];
  36388. var data;
  36389. var index;
  36390. if (parsedAnimation.enableBlending) {
  36391. animation.enableBlending = parsedAnimation.enableBlending;
  36392. }
  36393. if (parsedAnimation.blendingSpeed) {
  36394. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  36395. }
  36396. for (index = 0; index < parsedAnimation.keys.length; index++) {
  36397. var key = parsedAnimation.keys[index];
  36398. switch (dataType) {
  36399. case Animation.ANIMATIONTYPE_FLOAT:
  36400. data = key.values[0];
  36401. break;
  36402. case Animation.ANIMATIONTYPE_QUATERNION:
  36403. data = BABYLON.Quaternion.FromArray(key.values);
  36404. break;
  36405. case Animation.ANIMATIONTYPE_MATRIX:
  36406. data = BABYLON.Matrix.FromArray(key.values);
  36407. break;
  36408. case Animation.ANIMATIONTYPE_COLOR3:
  36409. data = BABYLON.Color3.FromArray(key.values);
  36410. break;
  36411. case Animation.ANIMATIONTYPE_VECTOR3:
  36412. default:
  36413. data = BABYLON.Vector3.FromArray(key.values);
  36414. break;
  36415. }
  36416. keys.push({
  36417. frame: key.frame,
  36418. value: data
  36419. });
  36420. }
  36421. animation.setKeys(keys);
  36422. if (parsedAnimation.ranges) {
  36423. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  36424. data = parsedAnimation.ranges[index];
  36425. animation.createRange(data.name, data.from, data.to);
  36426. }
  36427. }
  36428. return animation;
  36429. };
  36430. Animation.AppendSerializedAnimations = function (source, destination) {
  36431. if (source.animations) {
  36432. destination.animations = [];
  36433. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  36434. var animation = source.animations[animationIndex];
  36435. destination.animations.push(animation.serialize());
  36436. }
  36437. }
  36438. };
  36439. return Animation;
  36440. }());
  36441. // Statics
  36442. Animation._ANIMATIONTYPE_FLOAT = 0;
  36443. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  36444. Animation._ANIMATIONTYPE_QUATERNION = 2;
  36445. Animation._ANIMATIONTYPE_MATRIX = 3;
  36446. Animation._ANIMATIONTYPE_COLOR3 = 4;
  36447. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  36448. Animation._ANIMATIONTYPE_SIZE = 6;
  36449. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  36450. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  36451. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  36452. BABYLON.Animation = Animation;
  36453. })(BABYLON || (BABYLON = {}));
  36454. //# sourceMappingURL=babylon.animation.js.map
  36455. var BABYLON;
  36456. (function (BABYLON) {
  36457. var Animatable = (function () {
  36458. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  36459. if (fromFrame === void 0) { fromFrame = 0; }
  36460. if (toFrame === void 0) { toFrame = 100; }
  36461. if (loopAnimation === void 0) { loopAnimation = false; }
  36462. if (speedRatio === void 0) { speedRatio = 1.0; }
  36463. this.target = target;
  36464. this.fromFrame = fromFrame;
  36465. this.toFrame = toFrame;
  36466. this.loopAnimation = loopAnimation;
  36467. this.speedRatio = speedRatio;
  36468. this.onAnimationEnd = onAnimationEnd;
  36469. this._localDelayOffset = null;
  36470. this._pausedDelay = null;
  36471. this._animations = new Array();
  36472. this._paused = false;
  36473. this.animationStarted = false;
  36474. if (animations) {
  36475. this.appendAnimations(target, animations);
  36476. }
  36477. this._scene = scene;
  36478. scene._activeAnimatables.push(this);
  36479. }
  36480. // Methods
  36481. Animatable.prototype.getAnimations = function () {
  36482. return this._animations;
  36483. };
  36484. Animatable.prototype.appendAnimations = function (target, animations) {
  36485. for (var index = 0; index < animations.length; index++) {
  36486. var animation = animations[index];
  36487. animation._target = target;
  36488. this._animations.push(animation);
  36489. }
  36490. };
  36491. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  36492. var animations = this._animations;
  36493. for (var index = 0; index < animations.length; index++) {
  36494. if (animations[index].targetProperty === property) {
  36495. return animations[index];
  36496. }
  36497. }
  36498. return null;
  36499. };
  36500. Animatable.prototype.reset = function () {
  36501. var animations = this._animations;
  36502. for (var index = 0; index < animations.length; index++) {
  36503. animations[index].reset();
  36504. }
  36505. this._localDelayOffset = null;
  36506. this._pausedDelay = null;
  36507. };
  36508. Animatable.prototype.enableBlending = function (blendingSpeed) {
  36509. var animations = this._animations;
  36510. for (var index = 0; index < animations.length; index++) {
  36511. animations[index].enableBlending = true;
  36512. animations[index].blendingSpeed = blendingSpeed;
  36513. }
  36514. };
  36515. Animatable.prototype.disableBlending = function () {
  36516. var animations = this._animations;
  36517. for (var index = 0; index < animations.length; index++) {
  36518. animations[index].enableBlending = false;
  36519. }
  36520. };
  36521. Animatable.prototype.goToFrame = function (frame) {
  36522. var animations = this._animations;
  36523. if (animations[0]) {
  36524. var fps = animations[0].framePerSecond;
  36525. var currentFrame = animations[0].currentFrame;
  36526. var adjustTime = frame - currentFrame;
  36527. var delay = adjustTime * 1000 / fps;
  36528. this._localDelayOffset -= delay;
  36529. }
  36530. for (var index = 0; index < animations.length; index++) {
  36531. animations[index].goToFrame(frame);
  36532. }
  36533. };
  36534. Animatable.prototype.pause = function () {
  36535. if (this._paused) {
  36536. return;
  36537. }
  36538. this._paused = true;
  36539. };
  36540. Animatable.prototype.restart = function () {
  36541. this._paused = false;
  36542. };
  36543. Animatable.prototype.stop = function (animationName) {
  36544. if (animationName) {
  36545. var idx = this._scene._activeAnimatables.indexOf(this);
  36546. if (idx > -1) {
  36547. var animations = this._animations;
  36548. for (var index = animations.length - 1; index >= 0; index--) {
  36549. if (typeof animationName === "string" && animations[index].name != animationName) {
  36550. continue;
  36551. }
  36552. animations[index].reset();
  36553. animations.splice(index, 1);
  36554. }
  36555. if (animations.length == 0) {
  36556. this._scene._activeAnimatables.splice(idx, 1);
  36557. if (this.onAnimationEnd) {
  36558. this.onAnimationEnd();
  36559. }
  36560. }
  36561. }
  36562. }
  36563. else {
  36564. var index = this._scene._activeAnimatables.indexOf(this);
  36565. if (index > -1) {
  36566. this._scene._activeAnimatables.splice(index, 1);
  36567. var animations = this._animations;
  36568. for (var index = 0; index < animations.length; index++) {
  36569. animations[index].reset();
  36570. }
  36571. if (this.onAnimationEnd) {
  36572. this.onAnimationEnd();
  36573. }
  36574. }
  36575. }
  36576. };
  36577. Animatable.prototype._animate = function (delay) {
  36578. if (this._paused) {
  36579. this.animationStarted = false;
  36580. if (this._pausedDelay === null) {
  36581. this._pausedDelay = delay;
  36582. }
  36583. return true;
  36584. }
  36585. if (this._localDelayOffset === null) {
  36586. this._localDelayOffset = delay;
  36587. }
  36588. else if (this._pausedDelay !== null) {
  36589. this._localDelayOffset += delay - this._pausedDelay;
  36590. this._pausedDelay = null;
  36591. }
  36592. // Animating
  36593. var running = false;
  36594. var animations = this._animations;
  36595. var index;
  36596. for (index = 0; index < animations.length; index++) {
  36597. var animation = animations[index];
  36598. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  36599. running = running || isRunning;
  36600. }
  36601. this.animationStarted = running;
  36602. if (!running) {
  36603. // Remove from active animatables
  36604. index = this._scene._activeAnimatables.indexOf(this);
  36605. this._scene._activeAnimatables.splice(index, 1);
  36606. }
  36607. if (!running && this.onAnimationEnd) {
  36608. this.onAnimationEnd();
  36609. this.onAnimationEnd = null;
  36610. }
  36611. return running;
  36612. };
  36613. return Animatable;
  36614. }());
  36615. BABYLON.Animatable = Animatable;
  36616. })(BABYLON || (BABYLON = {}));
  36617. //# sourceMappingURL=babylon.animatable.js.map
  36618. var BABYLON;
  36619. (function (BABYLON) {
  36620. var EasingFunction = (function () {
  36621. function EasingFunction() {
  36622. // Properties
  36623. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  36624. }
  36625. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  36626. get: function () {
  36627. return EasingFunction._EASINGMODE_EASEIN;
  36628. },
  36629. enumerable: true,
  36630. configurable: true
  36631. });
  36632. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  36633. get: function () {
  36634. return EasingFunction._EASINGMODE_EASEOUT;
  36635. },
  36636. enumerable: true,
  36637. configurable: true
  36638. });
  36639. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  36640. get: function () {
  36641. return EasingFunction._EASINGMODE_EASEINOUT;
  36642. },
  36643. enumerable: true,
  36644. configurable: true
  36645. });
  36646. EasingFunction.prototype.setEasingMode = function (easingMode) {
  36647. var n = Math.min(Math.max(easingMode, 0), 2);
  36648. this._easingMode = n;
  36649. };
  36650. EasingFunction.prototype.getEasingMode = function () {
  36651. return this._easingMode;
  36652. };
  36653. EasingFunction.prototype.easeInCore = function (gradient) {
  36654. throw new Error('You must implement this method');
  36655. };
  36656. EasingFunction.prototype.ease = function (gradient) {
  36657. switch (this._easingMode) {
  36658. case EasingFunction.EASINGMODE_EASEIN:
  36659. return this.easeInCore(gradient);
  36660. case EasingFunction.EASINGMODE_EASEOUT:
  36661. return (1 - this.easeInCore(1 - gradient));
  36662. }
  36663. if (gradient >= 0.5) {
  36664. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  36665. }
  36666. return (this.easeInCore(gradient * 2) * 0.5);
  36667. };
  36668. return EasingFunction;
  36669. }());
  36670. //Statics
  36671. EasingFunction._EASINGMODE_EASEIN = 0;
  36672. EasingFunction._EASINGMODE_EASEOUT = 1;
  36673. EasingFunction._EASINGMODE_EASEINOUT = 2;
  36674. BABYLON.EasingFunction = EasingFunction;
  36675. var CircleEase = (function (_super) {
  36676. __extends(CircleEase, _super);
  36677. function CircleEase() {
  36678. return _super !== null && _super.apply(this, arguments) || this;
  36679. }
  36680. CircleEase.prototype.easeInCore = function (gradient) {
  36681. gradient = Math.max(0, Math.min(1, gradient));
  36682. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  36683. };
  36684. return CircleEase;
  36685. }(EasingFunction));
  36686. BABYLON.CircleEase = CircleEase;
  36687. var BackEase = (function (_super) {
  36688. __extends(BackEase, _super);
  36689. function BackEase(amplitude) {
  36690. if (amplitude === void 0) { amplitude = 1; }
  36691. var _this = _super.call(this) || this;
  36692. _this.amplitude = amplitude;
  36693. return _this;
  36694. }
  36695. BackEase.prototype.easeInCore = function (gradient) {
  36696. var num = Math.max(0, this.amplitude);
  36697. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  36698. };
  36699. return BackEase;
  36700. }(EasingFunction));
  36701. BABYLON.BackEase = BackEase;
  36702. var BounceEase = (function (_super) {
  36703. __extends(BounceEase, _super);
  36704. function BounceEase(bounces, bounciness) {
  36705. if (bounces === void 0) { bounces = 3; }
  36706. if (bounciness === void 0) { bounciness = 2; }
  36707. var _this = _super.call(this) || this;
  36708. _this.bounces = bounces;
  36709. _this.bounciness = bounciness;
  36710. return _this;
  36711. }
  36712. BounceEase.prototype.easeInCore = function (gradient) {
  36713. var y = Math.max(0.0, this.bounces);
  36714. var bounciness = this.bounciness;
  36715. if (bounciness <= 1.0) {
  36716. bounciness = 1.001;
  36717. }
  36718. var num9 = Math.pow(bounciness, y);
  36719. var num5 = 1.0 - bounciness;
  36720. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  36721. var num15 = gradient * num4;
  36722. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  36723. var num3 = Math.floor(num65);
  36724. var num13 = num3 + 1.0;
  36725. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  36726. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  36727. var num7 = (num8 + num12) * 0.5;
  36728. var num6 = gradient - num7;
  36729. var num2 = num7 - num8;
  36730. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  36731. };
  36732. return BounceEase;
  36733. }(EasingFunction));
  36734. BABYLON.BounceEase = BounceEase;
  36735. var CubicEase = (function (_super) {
  36736. __extends(CubicEase, _super);
  36737. function CubicEase() {
  36738. return _super !== null && _super.apply(this, arguments) || this;
  36739. }
  36740. CubicEase.prototype.easeInCore = function (gradient) {
  36741. return (gradient * gradient * gradient);
  36742. };
  36743. return CubicEase;
  36744. }(EasingFunction));
  36745. BABYLON.CubicEase = CubicEase;
  36746. var ElasticEase = (function (_super) {
  36747. __extends(ElasticEase, _super);
  36748. function ElasticEase(oscillations, springiness) {
  36749. if (oscillations === void 0) { oscillations = 3; }
  36750. if (springiness === void 0) { springiness = 3; }
  36751. var _this = _super.call(this) || this;
  36752. _this.oscillations = oscillations;
  36753. _this.springiness = springiness;
  36754. return _this;
  36755. }
  36756. ElasticEase.prototype.easeInCore = function (gradient) {
  36757. var num2;
  36758. var num3 = Math.max(0.0, this.oscillations);
  36759. var num = Math.max(0.0, this.springiness);
  36760. if (num == 0) {
  36761. num2 = gradient;
  36762. }
  36763. else {
  36764. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  36765. }
  36766. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  36767. };
  36768. return ElasticEase;
  36769. }(EasingFunction));
  36770. BABYLON.ElasticEase = ElasticEase;
  36771. var ExponentialEase = (function (_super) {
  36772. __extends(ExponentialEase, _super);
  36773. function ExponentialEase(exponent) {
  36774. if (exponent === void 0) { exponent = 2; }
  36775. var _this = _super.call(this) || this;
  36776. _this.exponent = exponent;
  36777. return _this;
  36778. }
  36779. ExponentialEase.prototype.easeInCore = function (gradient) {
  36780. if (this.exponent <= 0) {
  36781. return gradient;
  36782. }
  36783. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  36784. };
  36785. return ExponentialEase;
  36786. }(EasingFunction));
  36787. BABYLON.ExponentialEase = ExponentialEase;
  36788. var PowerEase = (function (_super) {
  36789. __extends(PowerEase, _super);
  36790. function PowerEase(power) {
  36791. if (power === void 0) { power = 2; }
  36792. var _this = _super.call(this) || this;
  36793. _this.power = power;
  36794. return _this;
  36795. }
  36796. PowerEase.prototype.easeInCore = function (gradient) {
  36797. var y = Math.max(0.0, this.power);
  36798. return Math.pow(gradient, y);
  36799. };
  36800. return PowerEase;
  36801. }(EasingFunction));
  36802. BABYLON.PowerEase = PowerEase;
  36803. var QuadraticEase = (function (_super) {
  36804. __extends(QuadraticEase, _super);
  36805. function QuadraticEase() {
  36806. return _super !== null && _super.apply(this, arguments) || this;
  36807. }
  36808. QuadraticEase.prototype.easeInCore = function (gradient) {
  36809. return (gradient * gradient);
  36810. };
  36811. return QuadraticEase;
  36812. }(EasingFunction));
  36813. BABYLON.QuadraticEase = QuadraticEase;
  36814. var QuarticEase = (function (_super) {
  36815. __extends(QuarticEase, _super);
  36816. function QuarticEase() {
  36817. return _super !== null && _super.apply(this, arguments) || this;
  36818. }
  36819. QuarticEase.prototype.easeInCore = function (gradient) {
  36820. return (gradient * gradient * gradient * gradient);
  36821. };
  36822. return QuarticEase;
  36823. }(EasingFunction));
  36824. BABYLON.QuarticEase = QuarticEase;
  36825. var QuinticEase = (function (_super) {
  36826. __extends(QuinticEase, _super);
  36827. function QuinticEase() {
  36828. return _super !== null && _super.apply(this, arguments) || this;
  36829. }
  36830. QuinticEase.prototype.easeInCore = function (gradient) {
  36831. return (gradient * gradient * gradient * gradient * gradient);
  36832. };
  36833. return QuinticEase;
  36834. }(EasingFunction));
  36835. BABYLON.QuinticEase = QuinticEase;
  36836. var SineEase = (function (_super) {
  36837. __extends(SineEase, _super);
  36838. function SineEase() {
  36839. return _super !== null && _super.apply(this, arguments) || this;
  36840. }
  36841. SineEase.prototype.easeInCore = function (gradient) {
  36842. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  36843. };
  36844. return SineEase;
  36845. }(EasingFunction));
  36846. BABYLON.SineEase = SineEase;
  36847. var BezierCurveEase = (function (_super) {
  36848. __extends(BezierCurveEase, _super);
  36849. function BezierCurveEase(x1, y1, x2, y2) {
  36850. if (x1 === void 0) { x1 = 0; }
  36851. if (y1 === void 0) { y1 = 0; }
  36852. if (x2 === void 0) { x2 = 1; }
  36853. if (y2 === void 0) { y2 = 1; }
  36854. var _this = _super.call(this) || this;
  36855. _this.x1 = x1;
  36856. _this.y1 = y1;
  36857. _this.x2 = x2;
  36858. _this.y2 = y2;
  36859. return _this;
  36860. }
  36861. BezierCurveEase.prototype.easeInCore = function (gradient) {
  36862. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  36863. };
  36864. return BezierCurveEase;
  36865. }(EasingFunction));
  36866. BABYLON.BezierCurveEase = BezierCurveEase;
  36867. })(BABYLON || (BABYLON = {}));
  36868. //# sourceMappingURL=babylon.easing.js.map
  36869. var BABYLON;
  36870. (function (BABYLON) {
  36871. var Condition = (function () {
  36872. function Condition(actionManager) {
  36873. this._actionManager = actionManager;
  36874. }
  36875. Condition.prototype.isValid = function () {
  36876. return true;
  36877. };
  36878. Condition.prototype._getProperty = function (propertyPath) {
  36879. return this._actionManager._getProperty(propertyPath);
  36880. };
  36881. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  36882. return this._actionManager._getEffectiveTarget(target, propertyPath);
  36883. };
  36884. Condition.prototype.serialize = function () {
  36885. };
  36886. Condition.prototype._serialize = function (serializedCondition) {
  36887. return {
  36888. type: 2,
  36889. children: [],
  36890. name: serializedCondition.name,
  36891. properties: serializedCondition.properties
  36892. };
  36893. };
  36894. return Condition;
  36895. }());
  36896. BABYLON.Condition = Condition;
  36897. var ValueCondition = (function (_super) {
  36898. __extends(ValueCondition, _super);
  36899. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  36900. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  36901. var _this = _super.call(this, actionManager) || this;
  36902. _this.propertyPath = propertyPath;
  36903. _this.value = value;
  36904. _this.operator = operator;
  36905. _this._target = target;
  36906. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  36907. _this._property = _this._getProperty(_this.propertyPath);
  36908. return _this;
  36909. }
  36910. Object.defineProperty(ValueCondition, "IsEqual", {
  36911. get: function () {
  36912. return ValueCondition._IsEqual;
  36913. },
  36914. enumerable: true,
  36915. configurable: true
  36916. });
  36917. Object.defineProperty(ValueCondition, "IsDifferent", {
  36918. get: function () {
  36919. return ValueCondition._IsDifferent;
  36920. },
  36921. enumerable: true,
  36922. configurable: true
  36923. });
  36924. Object.defineProperty(ValueCondition, "IsGreater", {
  36925. get: function () {
  36926. return ValueCondition._IsGreater;
  36927. },
  36928. enumerable: true,
  36929. configurable: true
  36930. });
  36931. Object.defineProperty(ValueCondition, "IsLesser", {
  36932. get: function () {
  36933. return ValueCondition._IsLesser;
  36934. },
  36935. enumerable: true,
  36936. configurable: true
  36937. });
  36938. // Methods
  36939. ValueCondition.prototype.isValid = function () {
  36940. switch (this.operator) {
  36941. case ValueCondition.IsGreater:
  36942. return this._effectiveTarget[this._property] > this.value;
  36943. case ValueCondition.IsLesser:
  36944. return this._effectiveTarget[this._property] < this.value;
  36945. case ValueCondition.IsEqual:
  36946. case ValueCondition.IsDifferent:
  36947. var check;
  36948. if (this.value.equals) {
  36949. check = this.value.equals(this._effectiveTarget[this._property]);
  36950. }
  36951. else {
  36952. check = this.value === this._effectiveTarget[this._property];
  36953. }
  36954. return this.operator === ValueCondition.IsEqual ? check : !check;
  36955. }
  36956. return false;
  36957. };
  36958. ValueCondition.prototype.serialize = function () {
  36959. return this._serialize({
  36960. name: "ValueCondition",
  36961. properties: [
  36962. BABYLON.Action._GetTargetProperty(this._target),
  36963. { name: "propertyPath", value: this.propertyPath },
  36964. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  36965. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  36966. ]
  36967. });
  36968. };
  36969. ValueCondition.GetOperatorName = function (operator) {
  36970. switch (operator) {
  36971. case ValueCondition._IsEqual: return "IsEqual";
  36972. case ValueCondition._IsDifferent: return "IsDifferent";
  36973. case ValueCondition._IsGreater: return "IsGreater";
  36974. case ValueCondition._IsLesser: return "IsLesser";
  36975. default: return "";
  36976. }
  36977. };
  36978. return ValueCondition;
  36979. }(Condition));
  36980. // Statics
  36981. ValueCondition._IsEqual = 0;
  36982. ValueCondition._IsDifferent = 1;
  36983. ValueCondition._IsGreater = 2;
  36984. ValueCondition._IsLesser = 3;
  36985. BABYLON.ValueCondition = ValueCondition;
  36986. var PredicateCondition = (function (_super) {
  36987. __extends(PredicateCondition, _super);
  36988. function PredicateCondition(actionManager, predicate) {
  36989. var _this = _super.call(this, actionManager) || this;
  36990. _this.predicate = predicate;
  36991. return _this;
  36992. }
  36993. PredicateCondition.prototype.isValid = function () {
  36994. return this.predicate();
  36995. };
  36996. return PredicateCondition;
  36997. }(Condition));
  36998. BABYLON.PredicateCondition = PredicateCondition;
  36999. var StateCondition = (function (_super) {
  37000. __extends(StateCondition, _super);
  37001. function StateCondition(actionManager, target, value) {
  37002. var _this = _super.call(this, actionManager) || this;
  37003. _this.value = value;
  37004. _this._target = target;
  37005. return _this;
  37006. }
  37007. // Methods
  37008. StateCondition.prototype.isValid = function () {
  37009. return this._target.state === this.value;
  37010. };
  37011. StateCondition.prototype.serialize = function () {
  37012. return this._serialize({
  37013. name: "StateCondition",
  37014. properties: [
  37015. BABYLON.Action._GetTargetProperty(this._target),
  37016. { name: "value", value: this.value }
  37017. ]
  37018. });
  37019. };
  37020. return StateCondition;
  37021. }(Condition));
  37022. BABYLON.StateCondition = StateCondition;
  37023. })(BABYLON || (BABYLON = {}));
  37024. //# sourceMappingURL=babylon.condition.js.map
  37025. var BABYLON;
  37026. (function (BABYLON) {
  37027. var Action = (function () {
  37028. function Action(triggerOptions, condition) {
  37029. this.triggerOptions = triggerOptions;
  37030. if (triggerOptions.parameter) {
  37031. this.trigger = triggerOptions.trigger;
  37032. this._triggerParameter = triggerOptions.parameter;
  37033. }
  37034. else {
  37035. this.trigger = triggerOptions;
  37036. }
  37037. this._nextActiveAction = this;
  37038. this._condition = condition;
  37039. }
  37040. // Methods
  37041. Action.prototype._prepare = function () {
  37042. };
  37043. Action.prototype.getTriggerParameter = function () {
  37044. return this._triggerParameter;
  37045. };
  37046. Action.prototype._executeCurrent = function (evt) {
  37047. if (this._nextActiveAction._condition) {
  37048. var condition = this._nextActiveAction._condition;
  37049. var currentRenderId = this._actionManager.getScene().getRenderId();
  37050. // We cache the current evaluation for the current frame
  37051. if (condition._evaluationId === currentRenderId) {
  37052. if (!condition._currentResult) {
  37053. return;
  37054. }
  37055. }
  37056. else {
  37057. condition._evaluationId = currentRenderId;
  37058. if (!condition.isValid()) {
  37059. condition._currentResult = false;
  37060. return;
  37061. }
  37062. condition._currentResult = true;
  37063. }
  37064. }
  37065. this._nextActiveAction.execute(evt);
  37066. this.skipToNextActiveAction();
  37067. };
  37068. Action.prototype.execute = function (evt) {
  37069. };
  37070. Action.prototype.skipToNextActiveAction = function () {
  37071. if (this._nextActiveAction._child) {
  37072. if (!this._nextActiveAction._child._actionManager) {
  37073. this._nextActiveAction._child._actionManager = this._actionManager;
  37074. }
  37075. this._nextActiveAction = this._nextActiveAction._child;
  37076. }
  37077. else {
  37078. this._nextActiveAction = this;
  37079. }
  37080. };
  37081. Action.prototype.then = function (action) {
  37082. this._child = action;
  37083. action._actionManager = this._actionManager;
  37084. action._prepare();
  37085. return action;
  37086. };
  37087. Action.prototype._getProperty = function (propertyPath) {
  37088. return this._actionManager._getProperty(propertyPath);
  37089. };
  37090. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  37091. return this._actionManager._getEffectiveTarget(target, propertyPath);
  37092. };
  37093. Action.prototype.serialize = function (parent) {
  37094. };
  37095. // Called by BABYLON.Action objects in serialize(...). Internal use
  37096. Action.prototype._serialize = function (serializedAction, parent) {
  37097. var serializationObject = {
  37098. type: 1,
  37099. children: [],
  37100. name: serializedAction.name,
  37101. properties: serializedAction.properties || []
  37102. };
  37103. // Serialize child
  37104. if (this._child) {
  37105. this._child.serialize(serializationObject);
  37106. }
  37107. // Check if "this" has a condition
  37108. if (this._condition) {
  37109. var serializedCondition = this._condition.serialize();
  37110. serializedCondition.children.push(serializationObject);
  37111. if (parent) {
  37112. parent.children.push(serializedCondition);
  37113. }
  37114. return serializedCondition;
  37115. }
  37116. if (parent) {
  37117. parent.children.push(serializationObject);
  37118. }
  37119. return serializationObject;
  37120. };
  37121. return Action;
  37122. }());
  37123. Action._SerializeValueAsString = function (value) {
  37124. if (typeof value === "number") {
  37125. return value.toString();
  37126. }
  37127. if (typeof value === "boolean") {
  37128. return value ? "true" : "false";
  37129. }
  37130. if (value instanceof BABYLON.Vector2) {
  37131. return value.x + ", " + value.y;
  37132. }
  37133. if (value instanceof BABYLON.Vector3) {
  37134. return value.x + ", " + value.y + ", " + value.z;
  37135. }
  37136. if (value instanceof BABYLON.Color3) {
  37137. return value.r + ", " + value.g + ", " + value.b;
  37138. }
  37139. if (value instanceof BABYLON.Color4) {
  37140. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  37141. }
  37142. return value; // string
  37143. };
  37144. Action._GetTargetProperty = function (target) {
  37145. return {
  37146. name: "target",
  37147. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  37148. : target instanceof BABYLON.Light ? "LightProperties"
  37149. : target instanceof BABYLON.Camera ? "CameraProperties"
  37150. : "SceneProperties",
  37151. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  37152. };
  37153. };
  37154. BABYLON.Action = Action;
  37155. })(BABYLON || (BABYLON = {}));
  37156. //# sourceMappingURL=babylon.action.js.map
  37157. var BABYLON;
  37158. (function (BABYLON) {
  37159. /**
  37160. * ActionEvent is the event beint sent when an action is triggered.
  37161. */
  37162. var ActionEvent = (function () {
  37163. /**
  37164. * @param source The mesh or sprite that triggered the action.
  37165. * @param pointerX The X mouse cursor position at the time of the event
  37166. * @param pointerY The Y mouse cursor position at the time of the event
  37167. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  37168. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  37169. */
  37170. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  37171. this.source = source;
  37172. this.pointerX = pointerX;
  37173. this.pointerY = pointerY;
  37174. this.meshUnderPointer = meshUnderPointer;
  37175. this.sourceEvent = sourceEvent;
  37176. this.additionalData = additionalData;
  37177. }
  37178. /**
  37179. * Helper function to auto-create an ActionEvent from a source mesh.
  37180. * @param source The source mesh that triggered the event
  37181. * @param evt {Event} The original (browser) event
  37182. */
  37183. ActionEvent.CreateNew = function (source, evt, additionalData) {
  37184. var scene = source.getScene();
  37185. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  37186. };
  37187. /**
  37188. * Helper function to auto-create an ActionEvent from a source mesh.
  37189. * @param source The source sprite that triggered the event
  37190. * @param scene Scene associated with the sprite
  37191. * @param evt {Event} The original (browser) event
  37192. */
  37193. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  37194. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  37195. };
  37196. /**
  37197. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  37198. * @param scene the scene where the event occurred
  37199. * @param evt {Event} The original (browser) event
  37200. */
  37201. ActionEvent.CreateNewFromScene = function (scene, evt) {
  37202. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  37203. };
  37204. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  37205. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  37206. };
  37207. return ActionEvent;
  37208. }());
  37209. BABYLON.ActionEvent = ActionEvent;
  37210. /**
  37211. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  37212. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  37213. */
  37214. var ActionManager = (function () {
  37215. function ActionManager(scene) {
  37216. // Members
  37217. this.actions = new Array();
  37218. this.hoverCursor = '';
  37219. this._scene = scene;
  37220. scene._actionManagers.push(this);
  37221. }
  37222. Object.defineProperty(ActionManager, "NothingTrigger", {
  37223. get: function () {
  37224. return ActionManager._NothingTrigger;
  37225. },
  37226. enumerable: true,
  37227. configurable: true
  37228. });
  37229. Object.defineProperty(ActionManager, "OnPickTrigger", {
  37230. get: function () {
  37231. return ActionManager._OnPickTrigger;
  37232. },
  37233. enumerable: true,
  37234. configurable: true
  37235. });
  37236. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  37237. get: function () {
  37238. return ActionManager._OnLeftPickTrigger;
  37239. },
  37240. enumerable: true,
  37241. configurable: true
  37242. });
  37243. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  37244. get: function () {
  37245. return ActionManager._OnRightPickTrigger;
  37246. },
  37247. enumerable: true,
  37248. configurable: true
  37249. });
  37250. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  37251. get: function () {
  37252. return ActionManager._OnCenterPickTrigger;
  37253. },
  37254. enumerable: true,
  37255. configurable: true
  37256. });
  37257. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  37258. get: function () {
  37259. return ActionManager._OnPickDownTrigger;
  37260. },
  37261. enumerable: true,
  37262. configurable: true
  37263. });
  37264. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  37265. get: function () {
  37266. return ActionManager._OnDoublePickTrigger;
  37267. },
  37268. enumerable: true,
  37269. configurable: true
  37270. });
  37271. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  37272. get: function () {
  37273. return ActionManager._OnPickUpTrigger;
  37274. },
  37275. enumerable: true,
  37276. configurable: true
  37277. });
  37278. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  37279. /// This trigger will only be raised if you also declared a OnPickDown
  37280. get: function () {
  37281. return ActionManager._OnPickOutTrigger;
  37282. },
  37283. enumerable: true,
  37284. configurable: true
  37285. });
  37286. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  37287. get: function () {
  37288. return ActionManager._OnLongPressTrigger;
  37289. },
  37290. enumerable: true,
  37291. configurable: true
  37292. });
  37293. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  37294. get: function () {
  37295. return ActionManager._OnPointerOverTrigger;
  37296. },
  37297. enumerable: true,
  37298. configurable: true
  37299. });
  37300. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  37301. get: function () {
  37302. return ActionManager._OnPointerOutTrigger;
  37303. },
  37304. enumerable: true,
  37305. configurable: true
  37306. });
  37307. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  37308. get: function () {
  37309. return ActionManager._OnEveryFrameTrigger;
  37310. },
  37311. enumerable: true,
  37312. configurable: true
  37313. });
  37314. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  37315. get: function () {
  37316. return ActionManager._OnIntersectionEnterTrigger;
  37317. },
  37318. enumerable: true,
  37319. configurable: true
  37320. });
  37321. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  37322. get: function () {
  37323. return ActionManager._OnIntersectionExitTrigger;
  37324. },
  37325. enumerable: true,
  37326. configurable: true
  37327. });
  37328. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  37329. get: function () {
  37330. return ActionManager._OnKeyDownTrigger;
  37331. },
  37332. enumerable: true,
  37333. configurable: true
  37334. });
  37335. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  37336. get: function () {
  37337. return ActionManager._OnKeyUpTrigger;
  37338. },
  37339. enumerable: true,
  37340. configurable: true
  37341. });
  37342. // Methods
  37343. ActionManager.prototype.dispose = function () {
  37344. var index = this._scene._actionManagers.indexOf(this);
  37345. for (var i = 0; i < this.actions.length; i++) {
  37346. var action = this.actions[i];
  37347. ActionManager.Triggers[action.trigger]--;
  37348. if (ActionManager.Triggers[action.trigger] === 0) {
  37349. delete ActionManager.Triggers[action.trigger];
  37350. }
  37351. }
  37352. if (index > -1) {
  37353. this._scene._actionManagers.splice(index, 1);
  37354. }
  37355. };
  37356. ActionManager.prototype.getScene = function () {
  37357. return this._scene;
  37358. };
  37359. /**
  37360. * Does this action manager handles actions of any of the given triggers
  37361. * @param {number[]} triggers - the triggers to be tested
  37362. * @return {boolean} whether one (or more) of the triggers is handeled
  37363. */
  37364. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  37365. for (var index = 0; index < this.actions.length; index++) {
  37366. var action = this.actions[index];
  37367. if (triggers.indexOf(action.trigger) > -1) {
  37368. return true;
  37369. }
  37370. }
  37371. return false;
  37372. };
  37373. /**
  37374. * Does this action manager handles actions of a given trigger
  37375. * @param {number} trigger - the trigger to be tested
  37376. * @return {boolean} whether the trigger is handeled
  37377. */
  37378. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  37379. for (var index = 0; index < this.actions.length; index++) {
  37380. var action = this.actions[index];
  37381. if (action.trigger === trigger) {
  37382. return true;
  37383. }
  37384. }
  37385. return false;
  37386. };
  37387. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  37388. /**
  37389. * Does this action manager has pointer triggers
  37390. * @return {boolean} whether or not it has pointer triggers
  37391. */
  37392. get: function () {
  37393. for (var index = 0; index < this.actions.length; index++) {
  37394. var action = this.actions[index];
  37395. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  37396. return true;
  37397. }
  37398. }
  37399. return false;
  37400. },
  37401. enumerable: true,
  37402. configurable: true
  37403. });
  37404. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  37405. /**
  37406. * Does this action manager has pick triggers
  37407. * @return {boolean} whether or not it has pick triggers
  37408. */
  37409. get: function () {
  37410. for (var index = 0; index < this.actions.length; index++) {
  37411. var action = this.actions[index];
  37412. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  37413. return true;
  37414. }
  37415. }
  37416. return false;
  37417. },
  37418. enumerable: true,
  37419. configurable: true
  37420. });
  37421. Object.defineProperty(ActionManager, "HasTriggers", {
  37422. /**
  37423. * Does exist one action manager with at least one trigger
  37424. * @return {boolean} whether or not it exists one action manager with one trigger
  37425. **/
  37426. get: function () {
  37427. for (var t in ActionManager.Triggers) {
  37428. if (ActionManager.Triggers.hasOwnProperty(t)) {
  37429. return true;
  37430. }
  37431. }
  37432. return false;
  37433. },
  37434. enumerable: true,
  37435. configurable: true
  37436. });
  37437. Object.defineProperty(ActionManager, "HasPickTriggers", {
  37438. /**
  37439. * Does exist one action manager with at least one pick trigger
  37440. * @return {boolean} whether or not it exists one action manager with one pick trigger
  37441. **/
  37442. get: function () {
  37443. for (var t in ActionManager.Triggers) {
  37444. if (ActionManager.Triggers.hasOwnProperty(t)) {
  37445. var t_int = parseInt(t);
  37446. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  37447. return true;
  37448. }
  37449. }
  37450. }
  37451. return false;
  37452. },
  37453. enumerable: true,
  37454. configurable: true
  37455. });
  37456. /**
  37457. * Does exist one action manager that handles actions of a given trigger
  37458. * @param {number} trigger - the trigger to be tested
  37459. * @return {boolean} whether the trigger is handeled by at least one action manager
  37460. **/
  37461. ActionManager.HasSpecificTrigger = function (trigger) {
  37462. for (var t in ActionManager.Triggers) {
  37463. if (ActionManager.Triggers.hasOwnProperty(t)) {
  37464. var t_int = parseInt(t);
  37465. if (t_int === trigger) {
  37466. return true;
  37467. }
  37468. }
  37469. }
  37470. return false;
  37471. };
  37472. /**
  37473. * Registers an action to this action manager
  37474. * @param {BABYLON.Action} action - the action to be registered
  37475. * @return {BABYLON.Action} the action amended (prepared) after registration
  37476. */
  37477. ActionManager.prototype.registerAction = function (action) {
  37478. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  37479. if (this.getScene().actionManager !== this) {
  37480. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  37481. return null;
  37482. }
  37483. }
  37484. this.actions.push(action);
  37485. if (ActionManager.Triggers[action.trigger]) {
  37486. ActionManager.Triggers[action.trigger]++;
  37487. }
  37488. else {
  37489. ActionManager.Triggers[action.trigger] = 1;
  37490. }
  37491. action._actionManager = this;
  37492. action._prepare();
  37493. return action;
  37494. };
  37495. /**
  37496. * Process a specific trigger
  37497. * @param {number} trigger - the trigger to process
  37498. * @param evt {BABYLON.ActionEvent} the event details to be processed
  37499. */
  37500. ActionManager.prototype.processTrigger = function (trigger, evt) {
  37501. for (var index = 0; index < this.actions.length; index++) {
  37502. var action = this.actions[index];
  37503. if (action.trigger === trigger) {
  37504. if (trigger === ActionManager.OnKeyUpTrigger
  37505. || trigger === ActionManager.OnKeyDownTrigger) {
  37506. var parameter = action.getTriggerParameter();
  37507. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  37508. if (!parameter.toLowerCase) {
  37509. continue;
  37510. }
  37511. var lowerCase = parameter.toLowerCase();
  37512. if (lowerCase !== evt.sourceEvent.key) {
  37513. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  37514. var actualkey = String.fromCharCode(unicode).toLowerCase();
  37515. if (actualkey !== lowerCase) {
  37516. continue;
  37517. }
  37518. }
  37519. }
  37520. }
  37521. action._executeCurrent(evt);
  37522. }
  37523. }
  37524. };
  37525. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  37526. var properties = propertyPath.split(".");
  37527. for (var index = 0; index < properties.length - 1; index++) {
  37528. target = target[properties[index]];
  37529. }
  37530. return target;
  37531. };
  37532. ActionManager.prototype._getProperty = function (propertyPath) {
  37533. var properties = propertyPath.split(".");
  37534. return properties[properties.length - 1];
  37535. };
  37536. ActionManager.prototype.serialize = function (name) {
  37537. var root = {
  37538. children: [],
  37539. name: name,
  37540. type: 3,
  37541. properties: [] // Empty for root but required
  37542. };
  37543. for (var i = 0; i < this.actions.length; i++) {
  37544. var triggerObject = {
  37545. type: 0,
  37546. children: [],
  37547. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  37548. properties: []
  37549. };
  37550. var triggerOptions = this.actions[i].triggerOptions;
  37551. if (triggerOptions && typeof triggerOptions !== "number") {
  37552. if (triggerOptions.parameter instanceof BABYLON.Node) {
  37553. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  37554. }
  37555. else {
  37556. var parameter = {};
  37557. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  37558. if (triggerOptions.parameter.mesh) {
  37559. parameter._meshId = triggerOptions.parameter.mesh.id;
  37560. }
  37561. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  37562. }
  37563. }
  37564. // Serialize child action, recursively
  37565. this.actions[i].serialize(triggerObject);
  37566. // Add serialized trigger
  37567. root.children.push(triggerObject);
  37568. }
  37569. return root;
  37570. };
  37571. ActionManager.Parse = function (parsedActions, object, scene) {
  37572. var actionManager = new BABYLON.ActionManager(scene);
  37573. if (object === null)
  37574. scene.actionManager = actionManager;
  37575. else
  37576. object.actionManager = actionManager;
  37577. // instanciate a new object
  37578. var instanciate = function (name, params) {
  37579. var newInstance = Object.create(BABYLON[name].prototype);
  37580. newInstance.constructor.apply(newInstance, params);
  37581. return newInstance;
  37582. };
  37583. var parseParameter = function (name, value, target, propertyPath) {
  37584. if (propertyPath === null) {
  37585. // String, boolean or float
  37586. var floatValue = parseFloat(value);
  37587. if (value === "true" || value === "false")
  37588. return value === "true";
  37589. else
  37590. return isNaN(floatValue) ? value : floatValue;
  37591. }
  37592. var effectiveTarget = propertyPath.split(".");
  37593. var values = value.split(",");
  37594. // Get effective Target
  37595. for (var i = 0; i < effectiveTarget.length; i++) {
  37596. target = target[effectiveTarget[i]];
  37597. }
  37598. // Return appropriate value with its type
  37599. if (typeof (target) === "boolean")
  37600. return values[0] === "true";
  37601. if (typeof (target) === "string")
  37602. return values[0];
  37603. // Parameters with multiple values such as Vector3 etc.
  37604. var split = new Array();
  37605. for (var i = 0; i < values.length; i++)
  37606. split.push(parseFloat(values[i]));
  37607. if (target instanceof BABYLON.Vector3)
  37608. return BABYLON.Vector3.FromArray(split);
  37609. if (target instanceof BABYLON.Vector4)
  37610. return BABYLON.Vector4.FromArray(split);
  37611. if (target instanceof BABYLON.Color3)
  37612. return BABYLON.Color3.FromArray(split);
  37613. if (target instanceof BABYLON.Color4)
  37614. return BABYLON.Color4.FromArray(split);
  37615. return parseFloat(values[0]);
  37616. };
  37617. // traverse graph per trigger
  37618. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  37619. if (combineArray === void 0) { combineArray = null; }
  37620. if (parsedAction.detached)
  37621. return;
  37622. var parameters = new Array();
  37623. var target = null;
  37624. var propertyPath = null;
  37625. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  37626. // Parameters
  37627. if (parsedAction.type === 2)
  37628. parameters.push(actionManager);
  37629. else
  37630. parameters.push(trigger);
  37631. if (combine) {
  37632. var actions = new Array();
  37633. for (var j = 0; j < parsedAction.combine.length; j++) {
  37634. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  37635. }
  37636. parameters.push(actions);
  37637. }
  37638. else {
  37639. for (var i = 0; i < parsedAction.properties.length; i++) {
  37640. var value = parsedAction.properties[i].value;
  37641. var name = parsedAction.properties[i].name;
  37642. var targetType = parsedAction.properties[i].targetType;
  37643. if (name === "target")
  37644. if (targetType !== null && targetType === "SceneProperties")
  37645. value = target = scene;
  37646. else
  37647. value = target = scene.getNodeByName(value);
  37648. else if (name === "parent")
  37649. value = scene.getNodeByName(value);
  37650. else if (name === "sound")
  37651. value = scene.getSoundByName(value);
  37652. else if (name !== "propertyPath") {
  37653. if (parsedAction.type === 2 && name === "operator")
  37654. value = BABYLON.ValueCondition[value];
  37655. else
  37656. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  37657. }
  37658. else {
  37659. propertyPath = value;
  37660. }
  37661. parameters.push(value);
  37662. }
  37663. }
  37664. if (combineArray === null) {
  37665. parameters.push(condition);
  37666. }
  37667. else {
  37668. parameters.push(null);
  37669. }
  37670. // If interpolate value action
  37671. if (parsedAction.name === "InterpolateValueAction") {
  37672. var param = parameters[parameters.length - 2];
  37673. parameters[parameters.length - 1] = param;
  37674. parameters[parameters.length - 2] = condition;
  37675. }
  37676. // Action or condition(s) and not CombineAction
  37677. var newAction = instanciate(parsedAction.name, parameters);
  37678. if (newAction instanceof BABYLON.Condition && condition !== null) {
  37679. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  37680. if (action)
  37681. action.then(nothing);
  37682. else
  37683. actionManager.registerAction(nothing);
  37684. action = nothing;
  37685. }
  37686. if (combineArray === null) {
  37687. if (newAction instanceof BABYLON.Condition) {
  37688. condition = newAction;
  37689. newAction = action;
  37690. }
  37691. else {
  37692. condition = null;
  37693. if (action)
  37694. action.then(newAction);
  37695. else
  37696. actionManager.registerAction(newAction);
  37697. }
  37698. }
  37699. else {
  37700. combineArray.push(newAction);
  37701. }
  37702. for (var i = 0; i < parsedAction.children.length; i++)
  37703. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  37704. };
  37705. // triggers
  37706. for (var i = 0; i < parsedActions.children.length; i++) {
  37707. var triggerParams;
  37708. var trigger = parsedActions.children[i];
  37709. if (trigger.properties.length > 0) {
  37710. var param = trigger.properties[0].value;
  37711. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  37712. if (value._meshId) {
  37713. value.mesh = scene.getMeshByID(value._meshId);
  37714. }
  37715. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  37716. }
  37717. else
  37718. triggerParams = BABYLON.ActionManager[trigger.name];
  37719. for (var j = 0; j < trigger.children.length; j++) {
  37720. if (!trigger.detached)
  37721. traverse(trigger.children[j], triggerParams, null, null);
  37722. }
  37723. }
  37724. };
  37725. ActionManager.GetTriggerName = function (trigger) {
  37726. switch (trigger) {
  37727. case 0: return "NothingTrigger";
  37728. case 1: return "OnPickTrigger";
  37729. case 2: return "OnLeftPickTrigger";
  37730. case 3: return "OnRightPickTrigger";
  37731. case 4: return "OnCenterPickTrigger";
  37732. case 5: return "OnPickDownTrigger";
  37733. case 6: return "OnPickUpTrigger";
  37734. case 7: return "OnLongPressTrigger";
  37735. case 8: return "OnPointerOverTrigger";
  37736. case 9: return "OnPointerOutTrigger";
  37737. case 10: return "OnEveryFrameTrigger";
  37738. case 11: return "OnIntersectionEnterTrigger";
  37739. case 12: return "OnIntersectionExitTrigger";
  37740. case 13: return "OnKeyDownTrigger";
  37741. case 14: return "OnKeyUpTrigger";
  37742. case 15: return "OnPickOutTrigger";
  37743. default: return "";
  37744. }
  37745. };
  37746. return ActionManager;
  37747. }());
  37748. // Statics
  37749. ActionManager._NothingTrigger = 0;
  37750. ActionManager._OnPickTrigger = 1;
  37751. ActionManager._OnLeftPickTrigger = 2;
  37752. ActionManager._OnRightPickTrigger = 3;
  37753. ActionManager._OnCenterPickTrigger = 4;
  37754. ActionManager._OnPickDownTrigger = 5;
  37755. ActionManager._OnDoublePickTrigger = 6;
  37756. ActionManager._OnPickUpTrigger = 7;
  37757. ActionManager._OnLongPressTrigger = 8;
  37758. ActionManager._OnPointerOverTrigger = 9;
  37759. ActionManager._OnPointerOutTrigger = 10;
  37760. ActionManager._OnEveryFrameTrigger = 11;
  37761. ActionManager._OnIntersectionEnterTrigger = 12;
  37762. ActionManager._OnIntersectionExitTrigger = 13;
  37763. ActionManager._OnKeyDownTrigger = 14;
  37764. ActionManager._OnKeyUpTrigger = 15;
  37765. ActionManager._OnPickOutTrigger = 16;
  37766. ActionManager.Triggers = {};
  37767. BABYLON.ActionManager = ActionManager;
  37768. })(BABYLON || (BABYLON = {}));
  37769. //# sourceMappingURL=babylon.actionManager.js.map
  37770. var BABYLON;
  37771. (function (BABYLON) {
  37772. var InterpolateValueAction = (function (_super) {
  37773. __extends(InterpolateValueAction, _super);
  37774. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  37775. if (duration === void 0) { duration = 1000; }
  37776. var _this = _super.call(this, triggerOptions, condition) || this;
  37777. _this.propertyPath = propertyPath;
  37778. _this.value = value;
  37779. _this.duration = duration;
  37780. _this.stopOtherAnimations = stopOtherAnimations;
  37781. _this.onInterpolationDone = onInterpolationDone;
  37782. _this._target = _this._effectiveTarget = target;
  37783. return _this;
  37784. }
  37785. InterpolateValueAction.prototype._prepare = function () {
  37786. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  37787. this._property = this._getProperty(this.propertyPath);
  37788. };
  37789. InterpolateValueAction.prototype.execute = function () {
  37790. var scene = this._actionManager.getScene();
  37791. var keys = [
  37792. {
  37793. frame: 0,
  37794. value: this._effectiveTarget[this._property]
  37795. }, {
  37796. frame: 100,
  37797. value: this.value
  37798. }
  37799. ];
  37800. var dataType;
  37801. if (typeof this.value === "number") {
  37802. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  37803. }
  37804. else if (this.value instanceof BABYLON.Color3) {
  37805. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  37806. }
  37807. else if (this.value instanceof BABYLON.Vector3) {
  37808. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  37809. }
  37810. else if (this.value instanceof BABYLON.Matrix) {
  37811. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  37812. }
  37813. else if (this.value instanceof BABYLON.Quaternion) {
  37814. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  37815. }
  37816. else {
  37817. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  37818. return;
  37819. }
  37820. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  37821. animation.setKeys(keys);
  37822. if (this.stopOtherAnimations) {
  37823. scene.stopAnimation(this._effectiveTarget);
  37824. }
  37825. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  37826. };
  37827. InterpolateValueAction.prototype.serialize = function (parent) {
  37828. return _super.prototype._serialize.call(this, {
  37829. name: "InterpolateValueAction",
  37830. properties: [
  37831. BABYLON.Action._GetTargetProperty(this._target),
  37832. { name: "propertyPath", value: this.propertyPath },
  37833. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  37834. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  37835. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  37836. ]
  37837. }, parent);
  37838. };
  37839. return InterpolateValueAction;
  37840. }(BABYLON.Action));
  37841. BABYLON.InterpolateValueAction = InterpolateValueAction;
  37842. })(BABYLON || (BABYLON = {}));
  37843. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  37844. var BABYLON;
  37845. (function (BABYLON) {
  37846. var SwitchBooleanAction = (function (_super) {
  37847. __extends(SwitchBooleanAction, _super);
  37848. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  37849. var _this = _super.call(this, triggerOptions, condition) || this;
  37850. _this.propertyPath = propertyPath;
  37851. _this._target = _this._effectiveTarget = target;
  37852. return _this;
  37853. }
  37854. SwitchBooleanAction.prototype._prepare = function () {
  37855. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  37856. this._property = this._getProperty(this.propertyPath);
  37857. };
  37858. SwitchBooleanAction.prototype.execute = function () {
  37859. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  37860. };
  37861. SwitchBooleanAction.prototype.serialize = function (parent) {
  37862. return _super.prototype._serialize.call(this, {
  37863. name: "SwitchBooleanAction",
  37864. properties: [
  37865. BABYLON.Action._GetTargetProperty(this._target),
  37866. { name: "propertyPath", value: this.propertyPath }
  37867. ]
  37868. }, parent);
  37869. };
  37870. return SwitchBooleanAction;
  37871. }(BABYLON.Action));
  37872. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  37873. var SetStateAction = (function (_super) {
  37874. __extends(SetStateAction, _super);
  37875. function SetStateAction(triggerOptions, target, value, condition) {
  37876. var _this = _super.call(this, triggerOptions, condition) || this;
  37877. _this.value = value;
  37878. _this._target = target;
  37879. return _this;
  37880. }
  37881. SetStateAction.prototype.execute = function () {
  37882. this._target.state = this.value;
  37883. };
  37884. SetStateAction.prototype.serialize = function (parent) {
  37885. return _super.prototype._serialize.call(this, {
  37886. name: "SetStateAction",
  37887. properties: [
  37888. BABYLON.Action._GetTargetProperty(this._target),
  37889. { name: "value", value: this.value }
  37890. ]
  37891. }, parent);
  37892. };
  37893. return SetStateAction;
  37894. }(BABYLON.Action));
  37895. BABYLON.SetStateAction = SetStateAction;
  37896. var SetValueAction = (function (_super) {
  37897. __extends(SetValueAction, _super);
  37898. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  37899. var _this = _super.call(this, triggerOptions, condition) || this;
  37900. _this.propertyPath = propertyPath;
  37901. _this.value = value;
  37902. _this._target = _this._effectiveTarget = target;
  37903. return _this;
  37904. }
  37905. SetValueAction.prototype._prepare = function () {
  37906. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  37907. this._property = this._getProperty(this.propertyPath);
  37908. };
  37909. SetValueAction.prototype.execute = function () {
  37910. this._effectiveTarget[this._property] = this.value;
  37911. if (this._target.markAsDirty) {
  37912. this._target.markAsDirty(this._property);
  37913. }
  37914. };
  37915. SetValueAction.prototype.serialize = function (parent) {
  37916. return _super.prototype._serialize.call(this, {
  37917. name: "SetValueAction",
  37918. properties: [
  37919. BABYLON.Action._GetTargetProperty(this._target),
  37920. { name: "propertyPath", value: this.propertyPath },
  37921. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  37922. ]
  37923. }, parent);
  37924. };
  37925. return SetValueAction;
  37926. }(BABYLON.Action));
  37927. BABYLON.SetValueAction = SetValueAction;
  37928. var IncrementValueAction = (function (_super) {
  37929. __extends(IncrementValueAction, _super);
  37930. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  37931. var _this = _super.call(this, triggerOptions, condition) || this;
  37932. _this.propertyPath = propertyPath;
  37933. _this.value = value;
  37934. _this._target = _this._effectiveTarget = target;
  37935. return _this;
  37936. }
  37937. IncrementValueAction.prototype._prepare = function () {
  37938. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  37939. this._property = this._getProperty(this.propertyPath);
  37940. if (typeof this._effectiveTarget[this._property] !== "number") {
  37941. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  37942. }
  37943. };
  37944. IncrementValueAction.prototype.execute = function () {
  37945. this._effectiveTarget[this._property] += this.value;
  37946. if (this._target.markAsDirty) {
  37947. this._target.markAsDirty(this._property);
  37948. }
  37949. };
  37950. IncrementValueAction.prototype.serialize = function (parent) {
  37951. return _super.prototype._serialize.call(this, {
  37952. name: "IncrementValueAction",
  37953. properties: [
  37954. BABYLON.Action._GetTargetProperty(this._target),
  37955. { name: "propertyPath", value: this.propertyPath },
  37956. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  37957. ]
  37958. }, parent);
  37959. };
  37960. return IncrementValueAction;
  37961. }(BABYLON.Action));
  37962. BABYLON.IncrementValueAction = IncrementValueAction;
  37963. var PlayAnimationAction = (function (_super) {
  37964. __extends(PlayAnimationAction, _super);
  37965. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  37966. var _this = _super.call(this, triggerOptions, condition) || this;
  37967. _this.from = from;
  37968. _this.to = to;
  37969. _this.loop = loop;
  37970. _this._target = target;
  37971. return _this;
  37972. }
  37973. PlayAnimationAction.prototype._prepare = function () {
  37974. };
  37975. PlayAnimationAction.prototype.execute = function () {
  37976. var scene = this._actionManager.getScene();
  37977. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  37978. };
  37979. PlayAnimationAction.prototype.serialize = function (parent) {
  37980. return _super.prototype._serialize.call(this, {
  37981. name: "PlayAnimationAction",
  37982. properties: [
  37983. BABYLON.Action._GetTargetProperty(this._target),
  37984. { name: "from", value: String(this.from) },
  37985. { name: "to", value: String(this.to) },
  37986. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  37987. ]
  37988. }, parent);
  37989. };
  37990. return PlayAnimationAction;
  37991. }(BABYLON.Action));
  37992. BABYLON.PlayAnimationAction = PlayAnimationAction;
  37993. var StopAnimationAction = (function (_super) {
  37994. __extends(StopAnimationAction, _super);
  37995. function StopAnimationAction(triggerOptions, target, condition) {
  37996. var _this = _super.call(this, triggerOptions, condition) || this;
  37997. _this._target = target;
  37998. return _this;
  37999. }
  38000. StopAnimationAction.prototype._prepare = function () {
  38001. };
  38002. StopAnimationAction.prototype.execute = function () {
  38003. var scene = this._actionManager.getScene();
  38004. scene.stopAnimation(this._target);
  38005. };
  38006. StopAnimationAction.prototype.serialize = function (parent) {
  38007. return _super.prototype._serialize.call(this, {
  38008. name: "StopAnimationAction",
  38009. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  38010. }, parent);
  38011. };
  38012. return StopAnimationAction;
  38013. }(BABYLON.Action));
  38014. BABYLON.StopAnimationAction = StopAnimationAction;
  38015. var DoNothingAction = (function (_super) {
  38016. __extends(DoNothingAction, _super);
  38017. function DoNothingAction(triggerOptions, condition) {
  38018. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  38019. return _super.call(this, triggerOptions, condition) || this;
  38020. }
  38021. DoNothingAction.prototype.execute = function () {
  38022. };
  38023. DoNothingAction.prototype.serialize = function (parent) {
  38024. return _super.prototype._serialize.call(this, {
  38025. name: "DoNothingAction",
  38026. properties: []
  38027. }, parent);
  38028. };
  38029. return DoNothingAction;
  38030. }(BABYLON.Action));
  38031. BABYLON.DoNothingAction = DoNothingAction;
  38032. var CombineAction = (function (_super) {
  38033. __extends(CombineAction, _super);
  38034. function CombineAction(triggerOptions, children, condition) {
  38035. var _this = _super.call(this, triggerOptions, condition) || this;
  38036. _this.children = children;
  38037. return _this;
  38038. }
  38039. CombineAction.prototype._prepare = function () {
  38040. for (var index = 0; index < this.children.length; index++) {
  38041. this.children[index]._actionManager = this._actionManager;
  38042. this.children[index]._prepare();
  38043. }
  38044. };
  38045. CombineAction.prototype.execute = function (evt) {
  38046. for (var index = 0; index < this.children.length; index++) {
  38047. this.children[index].execute(evt);
  38048. }
  38049. };
  38050. CombineAction.prototype.serialize = function (parent) {
  38051. var serializationObject = _super.prototype._serialize.call(this, {
  38052. name: "CombineAction",
  38053. properties: [],
  38054. combine: []
  38055. }, parent);
  38056. for (var i = 0; i < this.children.length; i++) {
  38057. serializationObject.combine.push(this.children[i].serialize(null));
  38058. }
  38059. return serializationObject;
  38060. };
  38061. return CombineAction;
  38062. }(BABYLON.Action));
  38063. BABYLON.CombineAction = CombineAction;
  38064. var ExecuteCodeAction = (function (_super) {
  38065. __extends(ExecuteCodeAction, _super);
  38066. function ExecuteCodeAction(triggerOptions, func, condition) {
  38067. var _this = _super.call(this, triggerOptions, condition) || this;
  38068. _this.func = func;
  38069. return _this;
  38070. }
  38071. ExecuteCodeAction.prototype.execute = function (evt) {
  38072. this.func(evt);
  38073. };
  38074. return ExecuteCodeAction;
  38075. }(BABYLON.Action));
  38076. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  38077. var SetParentAction = (function (_super) {
  38078. __extends(SetParentAction, _super);
  38079. function SetParentAction(triggerOptions, target, parent, condition) {
  38080. var _this = _super.call(this, triggerOptions, condition) || this;
  38081. _this._target = target;
  38082. _this._parent = parent;
  38083. return _this;
  38084. }
  38085. SetParentAction.prototype._prepare = function () {
  38086. };
  38087. SetParentAction.prototype.execute = function () {
  38088. if (this._target.parent === this._parent) {
  38089. return;
  38090. }
  38091. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  38092. invertParentWorldMatrix.invert();
  38093. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  38094. this._target.parent = this._parent;
  38095. };
  38096. SetParentAction.prototype.serialize = function (parent) {
  38097. return _super.prototype._serialize.call(this, {
  38098. name: "SetParentAction",
  38099. properties: [
  38100. BABYLON.Action._GetTargetProperty(this._target),
  38101. BABYLON.Action._GetTargetProperty(this._parent),
  38102. ]
  38103. }, parent);
  38104. };
  38105. return SetParentAction;
  38106. }(BABYLON.Action));
  38107. BABYLON.SetParentAction = SetParentAction;
  38108. var PlaySoundAction = (function (_super) {
  38109. __extends(PlaySoundAction, _super);
  38110. function PlaySoundAction(triggerOptions, sound, condition) {
  38111. var _this = _super.call(this, triggerOptions, condition) || this;
  38112. _this._sound = sound;
  38113. return _this;
  38114. }
  38115. PlaySoundAction.prototype._prepare = function () {
  38116. };
  38117. PlaySoundAction.prototype.execute = function () {
  38118. if (this._sound !== undefined)
  38119. this._sound.play();
  38120. };
  38121. PlaySoundAction.prototype.serialize = function (parent) {
  38122. return _super.prototype._serialize.call(this, {
  38123. name: "PlaySoundAction",
  38124. properties: [{ name: "sound", value: this._sound.name }]
  38125. }, parent);
  38126. };
  38127. return PlaySoundAction;
  38128. }(BABYLON.Action));
  38129. BABYLON.PlaySoundAction = PlaySoundAction;
  38130. var StopSoundAction = (function (_super) {
  38131. __extends(StopSoundAction, _super);
  38132. function StopSoundAction(triggerOptions, sound, condition) {
  38133. var _this = _super.call(this, triggerOptions, condition) || this;
  38134. _this._sound = sound;
  38135. return _this;
  38136. }
  38137. StopSoundAction.prototype._prepare = function () {
  38138. };
  38139. StopSoundAction.prototype.execute = function () {
  38140. if (this._sound !== undefined)
  38141. this._sound.stop();
  38142. };
  38143. StopSoundAction.prototype.serialize = function (parent) {
  38144. return _super.prototype._serialize.call(this, {
  38145. name: "StopSoundAction",
  38146. properties: [{ name: "sound", value: this._sound.name }]
  38147. }, parent);
  38148. };
  38149. return StopSoundAction;
  38150. }(BABYLON.Action));
  38151. BABYLON.StopSoundAction = StopSoundAction;
  38152. })(BABYLON || (BABYLON = {}));
  38153. //# sourceMappingURL=babylon.directActions.js.map
  38154. var BABYLON;
  38155. (function (BABYLON) {
  38156. var SpriteManager = (function () {
  38157. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  38158. if (epsilon === void 0) { epsilon = 0.01; }
  38159. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38160. this.name = name;
  38161. this.sprites = new Array();
  38162. this.renderingGroupId = 0;
  38163. this.layerMask = 0x0FFFFFFF;
  38164. this.fogEnabled = true;
  38165. this.isPickable = false;
  38166. /**
  38167. * An event triggered when the manager is disposed.
  38168. * @type {BABYLON.Observable}
  38169. */
  38170. this.onDisposeObservable = new BABYLON.Observable();
  38171. this._vertexBuffers = {};
  38172. this._capacity = capacity;
  38173. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  38174. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38175. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38176. if (cellSize.width && cellSize.height) {
  38177. this.cellWidth = cellSize.width;
  38178. this.cellHeight = cellSize.height;
  38179. }
  38180. else if (cellSize !== undefined) {
  38181. this.cellWidth = cellSize;
  38182. this.cellHeight = cellSize;
  38183. }
  38184. else {
  38185. return;
  38186. }
  38187. this._epsilon = epsilon;
  38188. this._scene = scene;
  38189. this._scene.spriteManagers.push(this);
  38190. var indices = [];
  38191. var index = 0;
  38192. for (var count = 0; count < capacity; count++) {
  38193. indices.push(index);
  38194. indices.push(index + 1);
  38195. indices.push(index + 2);
  38196. indices.push(index);
  38197. indices.push(index + 2);
  38198. indices.push(index + 3);
  38199. index += 4;
  38200. }
  38201. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  38202. // VBO
  38203. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  38204. this._vertexData = new Float32Array(capacity * 16 * 4);
  38205. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  38206. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  38207. var options = this._buffer.createVertexBuffer("options", 4, 4);
  38208. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  38209. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  38210. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  38211. this._vertexBuffers["options"] = options;
  38212. this._vertexBuffers["cellInfo"] = cellInfo;
  38213. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  38214. // Effects
  38215. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  38216. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  38217. }
  38218. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  38219. set: function (callback) {
  38220. if (this._onDisposeObserver) {
  38221. this.onDisposeObservable.remove(this._onDisposeObserver);
  38222. }
  38223. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  38224. },
  38225. enumerable: true,
  38226. configurable: true
  38227. });
  38228. Object.defineProperty(SpriteManager.prototype, "texture", {
  38229. get: function () {
  38230. return this._spriteTexture;
  38231. },
  38232. set: function (value) {
  38233. this._spriteTexture = value;
  38234. },
  38235. enumerable: true,
  38236. configurable: true
  38237. });
  38238. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  38239. var arrayOffset = index * 16;
  38240. if (offsetX === 0)
  38241. offsetX = this._epsilon;
  38242. else if (offsetX === 1)
  38243. offsetX = 1 - this._epsilon;
  38244. if (offsetY === 0)
  38245. offsetY = this._epsilon;
  38246. else if (offsetY === 1)
  38247. offsetY = 1 - this._epsilon;
  38248. this._vertexData[arrayOffset] = sprite.position.x;
  38249. this._vertexData[arrayOffset + 1] = sprite.position.y;
  38250. this._vertexData[arrayOffset + 2] = sprite.position.z;
  38251. this._vertexData[arrayOffset + 3] = sprite.angle;
  38252. this._vertexData[arrayOffset + 4] = sprite.width;
  38253. this._vertexData[arrayOffset + 5] = sprite.height;
  38254. this._vertexData[arrayOffset + 6] = offsetX;
  38255. this._vertexData[arrayOffset + 7] = offsetY;
  38256. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  38257. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  38258. var offset = (sprite.cellIndex / rowSize) >> 0;
  38259. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  38260. this._vertexData[arrayOffset + 11] = offset;
  38261. // Color
  38262. this._vertexData[arrayOffset + 12] = sprite.color.r;
  38263. this._vertexData[arrayOffset + 13] = sprite.color.g;
  38264. this._vertexData[arrayOffset + 14] = sprite.color.b;
  38265. this._vertexData[arrayOffset + 15] = sprite.color.a;
  38266. };
  38267. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  38268. var count = Math.min(this._capacity, this.sprites.length);
  38269. var min = BABYLON.Vector3.Zero();
  38270. var max = BABYLON.Vector3.Zero();
  38271. var distance = Number.MAX_VALUE;
  38272. var currentSprite;
  38273. var cameraSpacePosition = BABYLON.Vector3.Zero();
  38274. var cameraView = camera.getViewMatrix();
  38275. for (var index = 0; index < count; index++) {
  38276. var sprite = this.sprites[index];
  38277. if (!sprite) {
  38278. continue;
  38279. }
  38280. if (predicate) {
  38281. if (!predicate(sprite)) {
  38282. continue;
  38283. }
  38284. }
  38285. else if (!sprite.isPickable) {
  38286. continue;
  38287. }
  38288. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  38289. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  38290. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  38291. if (ray.intersectsBoxMinMax(min, max)) {
  38292. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  38293. if (distance > currentDistance) {
  38294. distance = currentDistance;
  38295. currentSprite = sprite;
  38296. if (fastCheck) {
  38297. break;
  38298. }
  38299. }
  38300. }
  38301. }
  38302. if (currentSprite) {
  38303. var result = new BABYLON.PickingInfo();
  38304. result.hit = true;
  38305. result.pickedSprite = currentSprite;
  38306. result.distance = distance;
  38307. return result;
  38308. }
  38309. return null;
  38310. };
  38311. SpriteManager.prototype.render = function () {
  38312. // Check
  38313. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  38314. return;
  38315. var engine = this._scene.getEngine();
  38316. var baseSize = this._spriteTexture.getBaseSize();
  38317. // Sprites
  38318. var deltaTime = engine.getDeltaTime();
  38319. var max = Math.min(this._capacity, this.sprites.length);
  38320. var rowSize = baseSize.width / this.cellWidth;
  38321. var offset = 0;
  38322. for (var index = 0; index < max; index++) {
  38323. var sprite = this.sprites[index];
  38324. if (!sprite) {
  38325. continue;
  38326. }
  38327. sprite._animate(deltaTime);
  38328. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  38329. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  38330. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  38331. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  38332. }
  38333. this._buffer.update(this._vertexData);
  38334. // Render
  38335. var effect = this._effectBase;
  38336. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  38337. effect = this._effectFog;
  38338. }
  38339. engine.enableEffect(effect);
  38340. var viewMatrix = this._scene.getViewMatrix();
  38341. effect.setTexture("diffuseSampler", this._spriteTexture);
  38342. effect.setMatrix("view", viewMatrix);
  38343. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  38344. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  38345. // Fog
  38346. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  38347. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  38348. effect.setColor3("vFogColor", this._scene.fogColor);
  38349. }
  38350. // VBOs
  38351. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  38352. // Draw order
  38353. engine.setDepthFunctionToLessOrEqual();
  38354. effect.setBool("alphaTest", true);
  38355. engine.setColorWrite(false);
  38356. engine.draw(true, 0, max * 6);
  38357. engine.setColorWrite(true);
  38358. effect.setBool("alphaTest", false);
  38359. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  38360. engine.draw(true, 0, max * 6);
  38361. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  38362. };
  38363. SpriteManager.prototype.dispose = function () {
  38364. if (this._buffer) {
  38365. this._buffer.dispose();
  38366. this._buffer = null;
  38367. }
  38368. if (this._indexBuffer) {
  38369. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  38370. this._indexBuffer = null;
  38371. }
  38372. if (this._spriteTexture) {
  38373. this._spriteTexture.dispose();
  38374. this._spriteTexture = null;
  38375. }
  38376. // Remove from scene
  38377. var index = this._scene.spriteManagers.indexOf(this);
  38378. this._scene.spriteManagers.splice(index, 1);
  38379. // Callback
  38380. this.onDisposeObservable.notifyObservers(this);
  38381. this.onDisposeObservable.clear();
  38382. };
  38383. return SpriteManager;
  38384. }());
  38385. BABYLON.SpriteManager = SpriteManager;
  38386. })(BABYLON || (BABYLON = {}));
  38387. //# sourceMappingURL=babylon.spriteManager.js.map
  38388. var BABYLON;
  38389. (function (BABYLON) {
  38390. var Sprite = (function () {
  38391. function Sprite(name, manager) {
  38392. this.name = name;
  38393. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  38394. this.width = 1.0;
  38395. this.height = 1.0;
  38396. this.angle = 0;
  38397. this.cellIndex = 0;
  38398. this.invertU = 0;
  38399. this.invertV = 0;
  38400. this.animations = new Array();
  38401. this.isPickable = false;
  38402. this._animationStarted = false;
  38403. this._loopAnimation = false;
  38404. this._fromIndex = 0;
  38405. this._toIndex = 0;
  38406. this._delay = 0;
  38407. this._direction = 1;
  38408. this._frameCount = 0;
  38409. this._time = 0;
  38410. this._manager = manager;
  38411. this._manager.sprites.push(this);
  38412. this.position = BABYLON.Vector3.Zero();
  38413. }
  38414. Object.defineProperty(Sprite.prototype, "size", {
  38415. get: function () {
  38416. return this.width;
  38417. },
  38418. set: function (value) {
  38419. this.width = value;
  38420. this.height = value;
  38421. },
  38422. enumerable: true,
  38423. configurable: true
  38424. });
  38425. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  38426. this._fromIndex = from;
  38427. this._toIndex = to;
  38428. this._loopAnimation = loop;
  38429. this._delay = delay;
  38430. this._animationStarted = true;
  38431. this._direction = from < to ? 1 : -1;
  38432. this.cellIndex = from;
  38433. this._time = 0;
  38434. this._onAnimationEnd = onAnimationEnd;
  38435. };
  38436. Sprite.prototype.stopAnimation = function () {
  38437. this._animationStarted = false;
  38438. };
  38439. Sprite.prototype._animate = function (deltaTime) {
  38440. if (!this._animationStarted)
  38441. return;
  38442. this._time += deltaTime;
  38443. if (this._time > this._delay) {
  38444. this._time = this._time % this._delay;
  38445. this.cellIndex += this._direction;
  38446. if (this.cellIndex === this._toIndex) {
  38447. if (this._loopAnimation) {
  38448. this.cellIndex = this._fromIndex;
  38449. }
  38450. else {
  38451. this._animationStarted = false;
  38452. if (this._onAnimationEnd) {
  38453. this._onAnimationEnd();
  38454. }
  38455. if (this.disposeWhenFinishedAnimating) {
  38456. this.dispose();
  38457. }
  38458. }
  38459. }
  38460. }
  38461. };
  38462. Sprite.prototype.dispose = function () {
  38463. for (var i = 0; i < this._manager.sprites.length; i++) {
  38464. if (this._manager.sprites[i] == this) {
  38465. this._manager.sprites.splice(i, 1);
  38466. }
  38467. }
  38468. };
  38469. return Sprite;
  38470. }());
  38471. BABYLON.Sprite = Sprite;
  38472. })(BABYLON || (BABYLON = {}));
  38473. //# sourceMappingURL=babylon.sprite.js.map
  38474. var BABYLON;
  38475. (function (BABYLON) {
  38476. var IntersectionInfo = (function () {
  38477. function IntersectionInfo(bu, bv, distance) {
  38478. this.bu = bu;
  38479. this.bv = bv;
  38480. this.distance = distance;
  38481. this.faceId = 0;
  38482. this.subMeshId = 0;
  38483. }
  38484. return IntersectionInfo;
  38485. }());
  38486. BABYLON.IntersectionInfo = IntersectionInfo;
  38487. var PickingInfo = (function () {
  38488. function PickingInfo() {
  38489. this.hit = false;
  38490. this.distance = 0;
  38491. this.pickedPoint = null;
  38492. this.pickedMesh = null;
  38493. this.bu = 0;
  38494. this.bv = 0;
  38495. this.faceId = -1;
  38496. this.subMeshId = 0;
  38497. this.pickedSprite = null;
  38498. }
  38499. // Methods
  38500. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  38501. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  38502. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  38503. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38504. return null;
  38505. }
  38506. var indices = this.pickedMesh.getIndices();
  38507. var result;
  38508. if (useVerticesNormals) {
  38509. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38510. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  38511. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  38512. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  38513. normal0 = normal0.scale(this.bu);
  38514. normal1 = normal1.scale(this.bv);
  38515. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  38516. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  38517. }
  38518. else {
  38519. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38520. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  38521. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  38522. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  38523. var p1p2 = vertex1.subtract(vertex2);
  38524. var p3p2 = vertex3.subtract(vertex2);
  38525. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  38526. }
  38527. if (useWorldCoordinates) {
  38528. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  38529. }
  38530. return BABYLON.Vector3.Normalize(result);
  38531. };
  38532. PickingInfo.prototype.getTextureCoordinates = function () {
  38533. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38534. return null;
  38535. }
  38536. var indices = this.pickedMesh.getIndices();
  38537. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38538. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  38539. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  38540. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  38541. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  38542. uv1 = uv1.scale(this.bu);
  38543. uv2 = uv2.scale(this.bv);
  38544. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  38545. };
  38546. return PickingInfo;
  38547. }());
  38548. BABYLON.PickingInfo = PickingInfo;
  38549. })(BABYLON || (BABYLON = {}));
  38550. //# sourceMappingURL=babylon.pickingInfo.js.map
  38551. var BABYLON;
  38552. (function (BABYLON) {
  38553. var Ray = (function () {
  38554. function Ray(origin, direction, length) {
  38555. if (length === void 0) { length = Number.MAX_VALUE; }
  38556. this.origin = origin;
  38557. this.direction = direction;
  38558. this.length = length;
  38559. }
  38560. // Methods
  38561. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  38562. var d = 0.0;
  38563. var maxValue = Number.MAX_VALUE;
  38564. var inv;
  38565. var min;
  38566. var max;
  38567. var temp;
  38568. if (Math.abs(this.direction.x) < 0.0000001) {
  38569. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  38570. return false;
  38571. }
  38572. }
  38573. else {
  38574. inv = 1.0 / this.direction.x;
  38575. min = (minimum.x - this.origin.x) * inv;
  38576. max = (maximum.x - this.origin.x) * inv;
  38577. if (max === -Infinity) {
  38578. max = Infinity;
  38579. }
  38580. if (min > max) {
  38581. temp = min;
  38582. min = max;
  38583. max = temp;
  38584. }
  38585. d = Math.max(min, d);
  38586. maxValue = Math.min(max, maxValue);
  38587. if (d > maxValue) {
  38588. return false;
  38589. }
  38590. }
  38591. if (Math.abs(this.direction.y) < 0.0000001) {
  38592. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  38593. return false;
  38594. }
  38595. }
  38596. else {
  38597. inv = 1.0 / this.direction.y;
  38598. min = (minimum.y - this.origin.y) * inv;
  38599. max = (maximum.y - this.origin.y) * inv;
  38600. if (max === -Infinity) {
  38601. max = Infinity;
  38602. }
  38603. if (min > max) {
  38604. temp = min;
  38605. min = max;
  38606. max = temp;
  38607. }
  38608. d = Math.max(min, d);
  38609. maxValue = Math.min(max, maxValue);
  38610. if (d > maxValue) {
  38611. return false;
  38612. }
  38613. }
  38614. if (Math.abs(this.direction.z) < 0.0000001) {
  38615. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  38616. return false;
  38617. }
  38618. }
  38619. else {
  38620. inv = 1.0 / this.direction.z;
  38621. min = (minimum.z - this.origin.z) * inv;
  38622. max = (maximum.z - this.origin.z) * inv;
  38623. if (max === -Infinity) {
  38624. max = Infinity;
  38625. }
  38626. if (min > max) {
  38627. temp = min;
  38628. min = max;
  38629. max = temp;
  38630. }
  38631. d = Math.max(min, d);
  38632. maxValue = Math.min(max, maxValue);
  38633. if (d > maxValue) {
  38634. return false;
  38635. }
  38636. }
  38637. return true;
  38638. };
  38639. Ray.prototype.intersectsBox = function (box) {
  38640. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  38641. };
  38642. Ray.prototype.intersectsSphere = function (sphere) {
  38643. var x = sphere.center.x - this.origin.x;
  38644. var y = sphere.center.y - this.origin.y;
  38645. var z = sphere.center.z - this.origin.z;
  38646. var pyth = (x * x) + (y * y) + (z * z);
  38647. var rr = sphere.radius * sphere.radius;
  38648. if (pyth <= rr) {
  38649. return true;
  38650. }
  38651. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  38652. if (dot < 0.0) {
  38653. return false;
  38654. }
  38655. var temp = pyth - (dot * dot);
  38656. return temp <= rr;
  38657. };
  38658. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  38659. if (!this._edge1) {
  38660. this._edge1 = BABYLON.Vector3.Zero();
  38661. this._edge2 = BABYLON.Vector3.Zero();
  38662. this._pvec = BABYLON.Vector3.Zero();
  38663. this._tvec = BABYLON.Vector3.Zero();
  38664. this._qvec = BABYLON.Vector3.Zero();
  38665. }
  38666. vertex1.subtractToRef(vertex0, this._edge1);
  38667. vertex2.subtractToRef(vertex0, this._edge2);
  38668. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  38669. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  38670. if (det === 0) {
  38671. return null;
  38672. }
  38673. var invdet = 1 / det;
  38674. this.origin.subtractToRef(vertex0, this._tvec);
  38675. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  38676. if (bu < 0 || bu > 1.0) {
  38677. return null;
  38678. }
  38679. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  38680. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  38681. if (bv < 0 || bu + bv > 1.0) {
  38682. return null;
  38683. }
  38684. //check if the distance is longer than the predefined length.
  38685. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  38686. if (distance > this.length) {
  38687. return null;
  38688. }
  38689. return new BABYLON.IntersectionInfo(bu, bv, distance);
  38690. };
  38691. Ray.prototype.intersectsPlane = function (plane) {
  38692. var distance;
  38693. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  38694. if (Math.abs(result1) < 9.99999997475243E-07) {
  38695. return null;
  38696. }
  38697. else {
  38698. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  38699. distance = (-plane.d - result2) / result1;
  38700. if (distance < 0.0) {
  38701. if (distance < -9.99999997475243E-07) {
  38702. return null;
  38703. }
  38704. else {
  38705. return 0;
  38706. }
  38707. }
  38708. return distance;
  38709. }
  38710. };
  38711. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  38712. var tm = BABYLON.Tmp.Matrix[0];
  38713. mesh.getWorldMatrix().invertToRef(tm);
  38714. if (this._tmpRay) {
  38715. Ray.TransformToRef(this, tm, this._tmpRay);
  38716. }
  38717. else {
  38718. this._tmpRay = Ray.Transform(this, tm);
  38719. }
  38720. return mesh.intersects(this._tmpRay, fastCheck);
  38721. };
  38722. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  38723. if (results) {
  38724. results.length = 0;
  38725. }
  38726. else {
  38727. results = [];
  38728. }
  38729. for (var i = 0; i < meshes.length; i++) {
  38730. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  38731. if (pickInfo.hit) {
  38732. results.push(pickInfo);
  38733. }
  38734. }
  38735. results.sort(this._comparePickingInfo);
  38736. return results;
  38737. };
  38738. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  38739. if (pickingInfoA.distance < pickingInfoB.distance) {
  38740. return -1;
  38741. }
  38742. else if (pickingInfoA.distance > pickingInfoB.distance) {
  38743. return 1;
  38744. }
  38745. else {
  38746. return 0;
  38747. }
  38748. };
  38749. /**
  38750. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  38751. * @param sega the first point of the segment to test the intersection against
  38752. * @param segb the second point of the segment to test the intersection against
  38753. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  38754. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  38755. */
  38756. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  38757. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  38758. var u = segb.subtract(sega);
  38759. var v = rsegb.subtract(this.origin);
  38760. var w = sega.subtract(this.origin);
  38761. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  38762. var b = BABYLON.Vector3.Dot(u, v);
  38763. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  38764. var d = BABYLON.Vector3.Dot(u, w);
  38765. var e = BABYLON.Vector3.Dot(v, w);
  38766. var D = a * c - b * b; // always >= 0
  38767. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  38768. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  38769. // compute the line parameters of the two closest points
  38770. if (D < Ray.smallnum) {
  38771. sN = 0.0; // force using point P0 on segment S1
  38772. sD = 1.0; // to prevent possible division by 0.0 later
  38773. tN = e;
  38774. tD = c;
  38775. }
  38776. else {
  38777. sN = (b * e - c * d);
  38778. tN = (a * e - b * d);
  38779. if (sN < 0.0) {
  38780. sN = 0.0;
  38781. tN = e;
  38782. tD = c;
  38783. }
  38784. else if (sN > sD) {
  38785. sN = sD;
  38786. tN = e + b;
  38787. tD = c;
  38788. }
  38789. }
  38790. if (tN < 0.0) {
  38791. tN = 0.0;
  38792. // recompute sc for this edge
  38793. if (-d < 0.0) {
  38794. sN = 0.0;
  38795. }
  38796. else if (-d > a)
  38797. sN = sD;
  38798. else {
  38799. sN = -d;
  38800. sD = a;
  38801. }
  38802. }
  38803. else if (tN > tD) {
  38804. tN = tD;
  38805. // recompute sc for this edge
  38806. if ((-d + b) < 0.0) {
  38807. sN = 0;
  38808. }
  38809. else if ((-d + b) > a) {
  38810. sN = sD;
  38811. }
  38812. else {
  38813. sN = (-d + b);
  38814. sD = a;
  38815. }
  38816. }
  38817. // finally do the division to get sc and tc
  38818. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  38819. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  38820. // get the difference of the two closest points
  38821. var qtc = v.multiplyByFloats(tc, tc, tc);
  38822. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  38823. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  38824. if (isIntersected) {
  38825. return qtc.length();
  38826. }
  38827. return -1;
  38828. };
  38829. // Statics
  38830. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  38831. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  38832. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  38833. var direction = end.subtract(start);
  38834. direction.normalize();
  38835. return new Ray(start, direction);
  38836. };
  38837. /**
  38838. * 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
  38839. * transformed to the given world matrix.
  38840. * @param origin The origin point
  38841. * @param end The end point
  38842. * @param world a matrix to transform the ray to. Default is the identity matrix.
  38843. */
  38844. Ray.CreateNewFromTo = function (origin, end, world) {
  38845. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  38846. var direction = end.subtract(origin);
  38847. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  38848. direction.normalize();
  38849. return Ray.Transform(new Ray(origin, direction, length), world);
  38850. };
  38851. Ray.Transform = function (ray, matrix) {
  38852. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  38853. Ray.TransformToRef(ray, matrix, result);
  38854. return result;
  38855. };
  38856. Ray.TransformToRef = function (ray, matrix, result) {
  38857. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  38858. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  38859. result.length = ray.length;
  38860. var dir = result.direction;
  38861. var len = dir.length();
  38862. if (!(len === 0 || len === 1)) {
  38863. var num = 1.0 / len;
  38864. dir.x *= num;
  38865. dir.y *= num;
  38866. dir.z *= num;
  38867. result.length *= len;
  38868. }
  38869. };
  38870. return Ray;
  38871. }());
  38872. Ray.smallnum = 0.00000001;
  38873. Ray.rayl = 10e8;
  38874. BABYLON.Ray = Ray;
  38875. })(BABYLON || (BABYLON = {}));
  38876. //# sourceMappingURL=babylon.ray.js.map
  38877. var BABYLON;
  38878. (function (BABYLON) {
  38879. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  38880. if (boxMin.x > sphereCenter.x + sphereRadius)
  38881. return false;
  38882. if (sphereCenter.x - sphereRadius > boxMax.x)
  38883. return false;
  38884. if (boxMin.y > sphereCenter.y + sphereRadius)
  38885. return false;
  38886. if (sphereCenter.y - sphereRadius > boxMax.y)
  38887. return false;
  38888. if (boxMin.z > sphereCenter.z + sphereRadius)
  38889. return false;
  38890. if (sphereCenter.z - sphereRadius > boxMax.z)
  38891. return false;
  38892. return true;
  38893. };
  38894. var getLowestRoot = (function () {
  38895. var result = { root: 0, found: false };
  38896. return function (a, b, c, maxR) {
  38897. result.root = 0;
  38898. result.found = false;
  38899. var determinant = b * b - 4.0 * a * c;
  38900. if (determinant < 0)
  38901. return result;
  38902. var sqrtD = Math.sqrt(determinant);
  38903. var r1 = (-b - sqrtD) / (2.0 * a);
  38904. var r2 = (-b + sqrtD) / (2.0 * a);
  38905. if (r1 > r2) {
  38906. var temp = r2;
  38907. r2 = r1;
  38908. r1 = temp;
  38909. }
  38910. if (r1 > 0 && r1 < maxR) {
  38911. result.root = r1;
  38912. result.found = true;
  38913. return result;
  38914. }
  38915. if (r2 > 0 && r2 < maxR) {
  38916. result.root = r2;
  38917. result.found = true;
  38918. return result;
  38919. }
  38920. return result;
  38921. };
  38922. })();
  38923. var Collider = (function () {
  38924. function Collider() {
  38925. this.radius = BABYLON.Vector3.One();
  38926. this.retry = 0;
  38927. this.basePointWorld = BABYLON.Vector3.Zero();
  38928. this.velocityWorld = BABYLON.Vector3.Zero();
  38929. this.normalizedVelocity = BABYLON.Vector3.Zero();
  38930. this._collisionPoint = BABYLON.Vector3.Zero();
  38931. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  38932. this._tempVector = BABYLON.Vector3.Zero();
  38933. this._tempVector2 = BABYLON.Vector3.Zero();
  38934. this._tempVector3 = BABYLON.Vector3.Zero();
  38935. this._tempVector4 = BABYLON.Vector3.Zero();
  38936. this._edge = BABYLON.Vector3.Zero();
  38937. this._baseToVertex = BABYLON.Vector3.Zero();
  38938. this._destinationPoint = BABYLON.Vector3.Zero();
  38939. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  38940. this._displacementVector = BABYLON.Vector3.Zero();
  38941. this._collisionMask = -1;
  38942. }
  38943. Object.defineProperty(Collider.prototype, "collisionMask", {
  38944. get: function () {
  38945. return this._collisionMask;
  38946. },
  38947. set: function (mask) {
  38948. this._collisionMask = !isNaN(mask) ? mask : -1;
  38949. },
  38950. enumerable: true,
  38951. configurable: true
  38952. });
  38953. // Methods
  38954. Collider.prototype._initialize = function (source, dir, e) {
  38955. this.velocity = dir;
  38956. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  38957. this.basePoint = source;
  38958. source.multiplyToRef(this.radius, this.basePointWorld);
  38959. dir.multiplyToRef(this.radius, this.velocityWorld);
  38960. this.velocityWorldLength = this.velocityWorld.length();
  38961. this.epsilon = e;
  38962. this.collisionFound = false;
  38963. };
  38964. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  38965. pa.subtractToRef(point, this._tempVector);
  38966. pb.subtractToRef(point, this._tempVector2);
  38967. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  38968. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  38969. if (d < 0)
  38970. return false;
  38971. pc.subtractToRef(point, this._tempVector3);
  38972. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  38973. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  38974. if (d < 0)
  38975. return false;
  38976. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  38977. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  38978. return d >= 0;
  38979. };
  38980. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  38981. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  38982. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  38983. if (distance > this.velocityWorldLength + max + sphereRadius) {
  38984. return false;
  38985. }
  38986. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  38987. return false;
  38988. return true;
  38989. };
  38990. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  38991. var t0;
  38992. var embeddedInPlane = false;
  38993. //defensive programming, actually not needed.
  38994. if (!trianglePlaneArray) {
  38995. trianglePlaneArray = [];
  38996. }
  38997. if (!trianglePlaneArray[faceIndex]) {
  38998. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  38999. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  39000. }
  39001. var trianglePlane = trianglePlaneArray[faceIndex];
  39002. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  39003. return;
  39004. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  39005. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  39006. if (normalDotVelocity == 0) {
  39007. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  39008. return;
  39009. embeddedInPlane = true;
  39010. t0 = 0;
  39011. }
  39012. else {
  39013. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  39014. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  39015. if (t0 > t1) {
  39016. var temp = t1;
  39017. t1 = t0;
  39018. t0 = temp;
  39019. }
  39020. if (t0 > 1.0 || t1 < 0.0)
  39021. return;
  39022. if (t0 < 0)
  39023. t0 = 0;
  39024. if (t0 > 1.0)
  39025. t0 = 1.0;
  39026. }
  39027. this._collisionPoint.copyFromFloats(0, 0, 0);
  39028. var found = false;
  39029. var t = 1.0;
  39030. if (!embeddedInPlane) {
  39031. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  39032. this.velocity.scaleToRef(t0, this._tempVector);
  39033. this._planeIntersectionPoint.addInPlace(this._tempVector);
  39034. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  39035. found = true;
  39036. t = t0;
  39037. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  39038. }
  39039. }
  39040. if (!found) {
  39041. var velocitySquaredLength = this.velocity.lengthSquared();
  39042. var a = velocitySquaredLength;
  39043. this.basePoint.subtractToRef(p1, this._tempVector);
  39044. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  39045. var c = this._tempVector.lengthSquared() - 1.0;
  39046. var lowestRoot = getLowestRoot(a, b, c, t);
  39047. if (lowestRoot.found) {
  39048. t = lowestRoot.root;
  39049. found = true;
  39050. this._collisionPoint.copyFrom(p1);
  39051. }
  39052. this.basePoint.subtractToRef(p2, this._tempVector);
  39053. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  39054. c = this._tempVector.lengthSquared() - 1.0;
  39055. lowestRoot = getLowestRoot(a, b, c, t);
  39056. if (lowestRoot.found) {
  39057. t = lowestRoot.root;
  39058. found = true;
  39059. this._collisionPoint.copyFrom(p2);
  39060. }
  39061. this.basePoint.subtractToRef(p3, this._tempVector);
  39062. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  39063. c = this._tempVector.lengthSquared() - 1.0;
  39064. lowestRoot = getLowestRoot(a, b, c, t);
  39065. if (lowestRoot.found) {
  39066. t = lowestRoot.root;
  39067. found = true;
  39068. this._collisionPoint.copyFrom(p3);
  39069. }
  39070. p2.subtractToRef(p1, this._edge);
  39071. p1.subtractToRef(this.basePoint, this._baseToVertex);
  39072. var edgeSquaredLength = this._edge.lengthSquared();
  39073. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  39074. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  39075. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  39076. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  39077. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  39078. lowestRoot = getLowestRoot(a, b, c, t);
  39079. if (lowestRoot.found) {
  39080. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  39081. if (f >= 0.0 && f <= 1.0) {
  39082. t = lowestRoot.root;
  39083. found = true;
  39084. this._edge.scaleInPlace(f);
  39085. p1.addToRef(this._edge, this._collisionPoint);
  39086. }
  39087. }
  39088. p3.subtractToRef(p2, this._edge);
  39089. p2.subtractToRef(this.basePoint, this._baseToVertex);
  39090. edgeSquaredLength = this._edge.lengthSquared();
  39091. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  39092. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  39093. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  39094. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  39095. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  39096. lowestRoot = getLowestRoot(a, b, c, t);
  39097. if (lowestRoot.found) {
  39098. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  39099. if (f >= 0.0 && f <= 1.0) {
  39100. t = lowestRoot.root;
  39101. found = true;
  39102. this._edge.scaleInPlace(f);
  39103. p2.addToRef(this._edge, this._collisionPoint);
  39104. }
  39105. }
  39106. p1.subtractToRef(p3, this._edge);
  39107. p3.subtractToRef(this.basePoint, this._baseToVertex);
  39108. edgeSquaredLength = this._edge.lengthSquared();
  39109. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  39110. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  39111. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  39112. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  39113. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  39114. lowestRoot = getLowestRoot(a, b, c, t);
  39115. if (lowestRoot.found) {
  39116. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  39117. if (f >= 0.0 && f <= 1.0) {
  39118. t = lowestRoot.root;
  39119. found = true;
  39120. this._edge.scaleInPlace(f);
  39121. p3.addToRef(this._edge, this._collisionPoint);
  39122. }
  39123. }
  39124. }
  39125. if (found) {
  39126. var distToCollision = t * this.velocity.length();
  39127. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  39128. if (!this.intersectionPoint) {
  39129. this.intersectionPoint = this._collisionPoint.clone();
  39130. }
  39131. else {
  39132. this.intersectionPoint.copyFrom(this._collisionPoint);
  39133. }
  39134. this.nearestDistance = distToCollision;
  39135. this.collisionFound = true;
  39136. }
  39137. }
  39138. };
  39139. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  39140. for (var i = indexStart; i < indexEnd; i += 3) {
  39141. var p1 = pts[indices[i] - decal];
  39142. var p2 = pts[indices[i + 1] - decal];
  39143. var p3 = pts[indices[i + 2] - decal];
  39144. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  39145. }
  39146. };
  39147. Collider.prototype._getResponse = function (pos, vel) {
  39148. pos.addToRef(vel, this._destinationPoint);
  39149. vel.scaleInPlace((this.nearestDistance / vel.length()));
  39150. this.basePoint.addToRef(vel, pos);
  39151. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  39152. this._slidePlaneNormal.normalize();
  39153. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  39154. pos.addInPlace(this._displacementVector);
  39155. this.intersectionPoint.addInPlace(this._displacementVector);
  39156. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  39157. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  39158. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  39159. };
  39160. return Collider;
  39161. }());
  39162. BABYLON.Collider = Collider;
  39163. })(BABYLON || (BABYLON = {}));
  39164. //# sourceMappingURL=babylon.collider.js.map
  39165. var BABYLON;
  39166. (function (BABYLON) {
  39167. //WebWorker code will be inserted to this variable.
  39168. BABYLON.CollisionWorker = "";
  39169. var WorkerTaskType;
  39170. (function (WorkerTaskType) {
  39171. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  39172. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  39173. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  39174. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  39175. var WorkerReplyType;
  39176. (function (WorkerReplyType) {
  39177. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  39178. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  39179. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  39180. var CollisionCoordinatorWorker = (function () {
  39181. function CollisionCoordinatorWorker() {
  39182. var _this = this;
  39183. this._scaledPosition = BABYLON.Vector3.Zero();
  39184. this._scaledVelocity = BABYLON.Vector3.Zero();
  39185. this.onMeshUpdated = function (mesh) {
  39186. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  39187. };
  39188. this.onGeometryUpdated = function (geometry) {
  39189. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  39190. };
  39191. this._afterRender = function () {
  39192. if (!_this._init)
  39193. return;
  39194. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  39195. return;
  39196. }
  39197. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  39198. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  39199. if (_this._runningUpdated > 4) {
  39200. return;
  39201. }
  39202. ++_this._runningUpdated;
  39203. var payload = {
  39204. updatedMeshes: _this._addUpdateMeshesList,
  39205. updatedGeometries: _this._addUpdateGeometriesList,
  39206. removedGeometries: _this._toRemoveGeometryArray,
  39207. removedMeshes: _this._toRemoveMeshesArray
  39208. };
  39209. var message = {
  39210. payload: payload,
  39211. taskType: WorkerTaskType.UPDATE
  39212. };
  39213. var serializable = [];
  39214. for (var id in payload.updatedGeometries) {
  39215. if (payload.updatedGeometries.hasOwnProperty(id)) {
  39216. //prepare transferables
  39217. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  39218. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  39219. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  39220. }
  39221. }
  39222. _this._worker.postMessage(message, serializable);
  39223. _this._addUpdateMeshesList = {};
  39224. _this._addUpdateGeometriesList = {};
  39225. _this._toRemoveGeometryArray = [];
  39226. _this._toRemoveMeshesArray = [];
  39227. };
  39228. this._onMessageFromWorker = function (e) {
  39229. var returnData = e.data;
  39230. if (returnData.error != WorkerReplyType.SUCCESS) {
  39231. //TODO what errors can be returned from the worker?
  39232. BABYLON.Tools.Warn("error returned from worker!");
  39233. return;
  39234. }
  39235. switch (returnData.taskType) {
  39236. case WorkerTaskType.INIT:
  39237. _this._init = true;
  39238. //Update the worked with ALL of the scene's current state
  39239. _this._scene.meshes.forEach(function (mesh) {
  39240. _this.onMeshAdded(mesh);
  39241. });
  39242. _this._scene.getGeometries().forEach(function (geometry) {
  39243. _this.onGeometryAdded(geometry);
  39244. });
  39245. break;
  39246. case WorkerTaskType.UPDATE:
  39247. _this._runningUpdated--;
  39248. break;
  39249. case WorkerTaskType.COLLIDE:
  39250. _this._runningCollisionTask = false;
  39251. var returnPayload = returnData.payload;
  39252. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  39253. return;
  39254. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  39255. //cleanup
  39256. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  39257. break;
  39258. }
  39259. };
  39260. this._collisionsCallbackArray = [];
  39261. this._init = false;
  39262. this._runningUpdated = 0;
  39263. this._runningCollisionTask = false;
  39264. this._addUpdateMeshesList = {};
  39265. this._addUpdateGeometriesList = {};
  39266. this._toRemoveGeometryArray = [];
  39267. this._toRemoveMeshesArray = [];
  39268. }
  39269. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  39270. if (!this._init)
  39271. return;
  39272. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  39273. return;
  39274. position.divideToRef(collider.radius, this._scaledPosition);
  39275. velocity.divideToRef(collider.radius, this._scaledVelocity);
  39276. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  39277. var payload = {
  39278. collider: {
  39279. position: this._scaledPosition.asArray(),
  39280. velocity: this._scaledVelocity.asArray(),
  39281. radius: collider.radius.asArray()
  39282. },
  39283. collisionId: collisionIndex,
  39284. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  39285. maximumRetry: maximumRetry
  39286. };
  39287. var message = {
  39288. payload: payload,
  39289. taskType: WorkerTaskType.COLLIDE
  39290. };
  39291. this._worker.postMessage(message);
  39292. };
  39293. CollisionCoordinatorWorker.prototype.init = function (scene) {
  39294. this._scene = scene;
  39295. this._scene.registerAfterRender(this._afterRender);
  39296. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  39297. this._worker = new Worker(workerUrl);
  39298. this._worker.onmessage = this._onMessageFromWorker;
  39299. var message = {
  39300. payload: {},
  39301. taskType: WorkerTaskType.INIT
  39302. };
  39303. this._worker.postMessage(message);
  39304. };
  39305. CollisionCoordinatorWorker.prototype.destroy = function () {
  39306. this._scene.unregisterAfterRender(this._afterRender);
  39307. this._worker.terminate();
  39308. };
  39309. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  39310. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  39311. this.onMeshUpdated(mesh);
  39312. };
  39313. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  39314. this._toRemoveMeshesArray.push(mesh.uniqueId);
  39315. };
  39316. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  39317. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  39318. geometry.onGeometryUpdated = this.onGeometryUpdated;
  39319. this.onGeometryUpdated(geometry);
  39320. };
  39321. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  39322. this._toRemoveGeometryArray.push(geometry.id);
  39323. };
  39324. return CollisionCoordinatorWorker;
  39325. }());
  39326. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  39327. var submeshes = [];
  39328. if (mesh.subMeshes) {
  39329. submeshes = mesh.subMeshes.map(function (sm, idx) {
  39330. return {
  39331. position: idx,
  39332. verticesStart: sm.verticesStart,
  39333. verticesCount: sm.verticesCount,
  39334. indexStart: sm.indexStart,
  39335. indexCount: sm.indexCount,
  39336. hasMaterial: !!sm.getMaterial(),
  39337. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  39338. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  39339. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  39340. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  39341. };
  39342. });
  39343. }
  39344. var geometryId = null;
  39345. if (mesh instanceof BABYLON.Mesh) {
  39346. geometryId = mesh.geometry ? mesh.geometry.id : null;
  39347. }
  39348. else if (mesh instanceof BABYLON.InstancedMesh) {
  39349. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  39350. }
  39351. return {
  39352. uniqueId: mesh.uniqueId,
  39353. id: mesh.id,
  39354. name: mesh.name,
  39355. geometryId: geometryId,
  39356. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  39357. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  39358. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  39359. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  39360. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  39361. subMeshes: submeshes,
  39362. checkCollisions: mesh.checkCollisions
  39363. };
  39364. };
  39365. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  39366. return {
  39367. id: geometry.id,
  39368. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  39369. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  39370. indices: new Uint32Array(geometry.getIndices() || []),
  39371. };
  39372. };
  39373. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  39374. var CollisionCoordinatorLegacy = (function () {
  39375. function CollisionCoordinatorLegacy() {
  39376. this._scaledPosition = BABYLON.Vector3.Zero();
  39377. this._scaledVelocity = BABYLON.Vector3.Zero();
  39378. this._finalPosition = BABYLON.Vector3.Zero();
  39379. }
  39380. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  39381. position.divideToRef(collider.radius, this._scaledPosition);
  39382. velocity.divideToRef(collider.radius, this._scaledVelocity);
  39383. collider.collidedMesh = null;
  39384. collider.retry = 0;
  39385. collider.initialVelocity = this._scaledVelocity;
  39386. collider.initialPosition = this._scaledPosition;
  39387. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  39388. this._finalPosition.multiplyInPlace(collider.radius);
  39389. //run the callback
  39390. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  39391. };
  39392. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  39393. this._scene = scene;
  39394. };
  39395. CollisionCoordinatorLegacy.prototype.destroy = function () {
  39396. //Legacy need no destruction method.
  39397. };
  39398. //No update in legacy mode
  39399. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  39400. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  39401. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  39402. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  39403. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  39404. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  39405. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  39406. if (excludedMesh === void 0) { excludedMesh = null; }
  39407. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  39408. if (collider.retry >= maximumRetry) {
  39409. finalPosition.copyFrom(position);
  39410. return;
  39411. }
  39412. // Check if this is a mesh else camera or -1
  39413. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  39414. collider._initialize(position, velocity, closeDistance);
  39415. // Check all meshes
  39416. for (var index = 0; index < this._scene.meshes.length; index++) {
  39417. var mesh = this._scene.meshes[index];
  39418. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  39419. mesh._checkCollision(collider);
  39420. }
  39421. }
  39422. if (!collider.collisionFound) {
  39423. position.addToRef(velocity, finalPosition);
  39424. return;
  39425. }
  39426. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  39427. collider._getResponse(position, velocity);
  39428. }
  39429. if (velocity.length() <= closeDistance) {
  39430. finalPosition.copyFrom(position);
  39431. return;
  39432. }
  39433. collider.retry++;
  39434. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  39435. };
  39436. return CollisionCoordinatorLegacy;
  39437. }());
  39438. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  39439. })(BABYLON || (BABYLON = {}));
  39440. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  39441. var BABYLON;
  39442. (function (BABYLON) {
  39443. var Particle = (function () {
  39444. function Particle() {
  39445. this.position = BABYLON.Vector3.Zero();
  39446. this.direction = BABYLON.Vector3.Zero();
  39447. this.color = new BABYLON.Color4(0, 0, 0, 0);
  39448. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  39449. this.lifeTime = 1.0;
  39450. this.age = 0;
  39451. this.size = 0;
  39452. this.angle = 0;
  39453. this.angularSpeed = 0;
  39454. }
  39455. Particle.prototype.copyTo = function (other) {
  39456. other.position.copyFrom(this.position);
  39457. other.direction.copyFrom(this.direction);
  39458. other.color.copyFrom(this.color);
  39459. other.colorStep.copyFrom(this.colorStep);
  39460. other.lifeTime = this.lifeTime;
  39461. other.age = this.age;
  39462. other.size = this.size;
  39463. other.angle = this.angle;
  39464. other.angularSpeed = this.angularSpeed;
  39465. };
  39466. return Particle;
  39467. }());
  39468. BABYLON.Particle = Particle;
  39469. })(BABYLON || (BABYLON = {}));
  39470. //# sourceMappingURL=babylon.particle.js.map
  39471. var BABYLON;
  39472. (function (BABYLON) {
  39473. var randomNumber = function (min, max) {
  39474. if (min === max) {
  39475. return (min);
  39476. }
  39477. var random = Math.random();
  39478. return ((random * (max - min)) + min);
  39479. };
  39480. var ParticleSystem = (function () {
  39481. function ParticleSystem(name, capacity, scene, customEffect) {
  39482. var _this = this;
  39483. this.name = name;
  39484. // Members
  39485. this.animations = [];
  39486. this.renderingGroupId = 0;
  39487. this.emitter = null;
  39488. this.emitRate = 10;
  39489. this.manualEmitCount = -1;
  39490. this.updateSpeed = 0.01;
  39491. this.targetStopDuration = 0;
  39492. this.disposeOnStop = false;
  39493. this.minEmitPower = 1;
  39494. this.maxEmitPower = 1;
  39495. this.minLifeTime = 1;
  39496. this.maxLifeTime = 1;
  39497. this.minSize = 1;
  39498. this.maxSize = 1;
  39499. this.minAngularSpeed = 0;
  39500. this.maxAngularSpeed = 0;
  39501. this.layerMask = 0x0FFFFFFF;
  39502. this.customShader = null;
  39503. this.preventAutoStart = false;
  39504. /**
  39505. * An event triggered when the system is disposed.
  39506. * @type {BABYLON.Observable}
  39507. */
  39508. this.onDisposeObservable = new BABYLON.Observable();
  39509. this.onAnimationEnd = null;
  39510. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  39511. this.forceDepthWrite = false;
  39512. this.gravity = BABYLON.Vector3.Zero();
  39513. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  39514. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  39515. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  39516. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  39517. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  39518. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  39519. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  39520. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  39521. this.particles = new Array();
  39522. this._stockParticles = new Array();
  39523. this._newPartsExcess = 0;
  39524. this._vertexBuffers = {};
  39525. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  39526. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  39527. this._scaledDirection = BABYLON.Vector3.Zero();
  39528. this._scaledGravity = BABYLON.Vector3.Zero();
  39529. this._currentRenderId = -1;
  39530. this._started = false;
  39531. this._stopped = false;
  39532. this._actualFrame = 0;
  39533. this.id = name;
  39534. this._capacity = capacity;
  39535. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  39536. this._customEffect = customEffect;
  39537. scene.particleSystems.push(this);
  39538. var indices = [];
  39539. var index = 0;
  39540. for (var count = 0; count < capacity; count++) {
  39541. indices.push(index);
  39542. indices.push(index + 1);
  39543. indices.push(index + 2);
  39544. indices.push(index);
  39545. indices.push(index + 2);
  39546. indices.push(index + 3);
  39547. index += 4;
  39548. }
  39549. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  39550. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  39551. this._vertexData = new Float32Array(capacity * 11 * 4);
  39552. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  39553. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  39554. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  39555. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  39556. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  39557. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  39558. this._vertexBuffers["options"] = options;
  39559. // Default behaviors
  39560. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  39561. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  39562. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  39563. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  39564. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  39565. };
  39566. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  39567. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  39568. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  39569. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  39570. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  39571. };
  39572. this.updateFunction = function (particles) {
  39573. for (var index = 0; index < particles.length; index++) {
  39574. var particle = particles[index];
  39575. particle.age += _this._scaledUpdateSpeed;
  39576. if (particle.age >= particle.lifeTime) {
  39577. _this.recycleParticle(particle);
  39578. index--;
  39579. continue;
  39580. }
  39581. else {
  39582. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  39583. particle.color.addInPlace(_this._scaledColorStep);
  39584. if (particle.color.a < 0)
  39585. particle.color.a = 0;
  39586. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  39587. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  39588. particle.position.addInPlace(_this._scaledDirection);
  39589. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  39590. particle.direction.addInPlace(_this._scaledGravity);
  39591. }
  39592. }
  39593. };
  39594. }
  39595. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  39596. set: function (callback) {
  39597. if (this._onDisposeObserver) {
  39598. this.onDisposeObservable.remove(this._onDisposeObserver);
  39599. }
  39600. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  39601. },
  39602. enumerable: true,
  39603. configurable: true
  39604. });
  39605. ParticleSystem.prototype.recycleParticle = function (particle) {
  39606. var lastParticle = this.particles.pop();
  39607. if (lastParticle !== particle) {
  39608. lastParticle.copyTo(particle);
  39609. this._stockParticles.push(lastParticle);
  39610. }
  39611. };
  39612. ParticleSystem.prototype.getCapacity = function () {
  39613. return this._capacity;
  39614. };
  39615. ParticleSystem.prototype.isAlive = function () {
  39616. return this._alive;
  39617. };
  39618. ParticleSystem.prototype.isStarted = function () {
  39619. return this._started;
  39620. };
  39621. ParticleSystem.prototype.start = function () {
  39622. this._started = true;
  39623. this._stopped = false;
  39624. this._actualFrame = 0;
  39625. };
  39626. ParticleSystem.prototype.stop = function () {
  39627. this._stopped = true;
  39628. };
  39629. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  39630. var offset = index * 11;
  39631. this._vertexData[offset] = particle.position.x;
  39632. this._vertexData[offset + 1] = particle.position.y;
  39633. this._vertexData[offset + 2] = particle.position.z;
  39634. this._vertexData[offset + 3] = particle.color.r;
  39635. this._vertexData[offset + 4] = particle.color.g;
  39636. this._vertexData[offset + 5] = particle.color.b;
  39637. this._vertexData[offset + 6] = particle.color.a;
  39638. this._vertexData[offset + 7] = particle.angle;
  39639. this._vertexData[offset + 8] = particle.size;
  39640. this._vertexData[offset + 9] = offsetX;
  39641. this._vertexData[offset + 10] = offsetY;
  39642. };
  39643. ParticleSystem.prototype._update = function (newParticles) {
  39644. // Update current
  39645. this._alive = this.particles.length > 0;
  39646. this.updateFunction(this.particles);
  39647. // Add new ones
  39648. var worldMatrix;
  39649. if (this.emitter.position) {
  39650. var emitterMesh = this.emitter;
  39651. worldMatrix = emitterMesh.getWorldMatrix();
  39652. }
  39653. else {
  39654. var emitterPosition = this.emitter;
  39655. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  39656. }
  39657. var particle;
  39658. for (var index = 0; index < newParticles; index++) {
  39659. if (this.particles.length === this._capacity) {
  39660. break;
  39661. }
  39662. if (this._stockParticles.length !== 0) {
  39663. particle = this._stockParticles.pop();
  39664. particle.age = 0;
  39665. }
  39666. else {
  39667. particle = new BABYLON.Particle();
  39668. }
  39669. this.particles.push(particle);
  39670. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  39671. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  39672. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  39673. particle.size = randomNumber(this.minSize, this.maxSize);
  39674. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  39675. this.startPositionFunction(worldMatrix, particle.position, particle);
  39676. var step = randomNumber(0, 1.0);
  39677. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  39678. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  39679. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  39680. }
  39681. };
  39682. ParticleSystem.prototype._getEffect = function () {
  39683. if (this._customEffect) {
  39684. return this._customEffect;
  39685. }
  39686. ;
  39687. var defines = [];
  39688. if (this._scene.clipPlane) {
  39689. defines.push("#define CLIPPLANE");
  39690. }
  39691. // Effect
  39692. var join = defines.join("\n");
  39693. if (this._cachedDefines !== join) {
  39694. this._cachedDefines = join;
  39695. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  39696. }
  39697. return this._effect;
  39698. };
  39699. ParticleSystem.prototype.animate = function () {
  39700. if (!this._started)
  39701. return;
  39702. var effect = this._getEffect();
  39703. // Check
  39704. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  39705. return;
  39706. if (this._currentRenderId === this._scene.getRenderId()) {
  39707. return;
  39708. }
  39709. this._currentRenderId = this._scene.getRenderId();
  39710. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  39711. // determine the number of particles we need to create
  39712. var newParticles;
  39713. if (this.manualEmitCount > -1) {
  39714. newParticles = this.manualEmitCount;
  39715. this._newPartsExcess = 0;
  39716. this.manualEmitCount = 0;
  39717. }
  39718. else {
  39719. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  39720. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  39721. }
  39722. if (this._newPartsExcess > 1.0) {
  39723. newParticles += this._newPartsExcess >> 0;
  39724. this._newPartsExcess -= this._newPartsExcess >> 0;
  39725. }
  39726. this._alive = false;
  39727. if (!this._stopped) {
  39728. this._actualFrame += this._scaledUpdateSpeed;
  39729. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  39730. this.stop();
  39731. }
  39732. else {
  39733. newParticles = 0;
  39734. }
  39735. this._update(newParticles);
  39736. // Stopped?
  39737. if (this._stopped) {
  39738. if (!this._alive) {
  39739. this._started = false;
  39740. if (this.onAnimationEnd) {
  39741. this.onAnimationEnd();
  39742. }
  39743. if (this.disposeOnStop) {
  39744. this._scene._toBeDisposed.push(this);
  39745. }
  39746. }
  39747. }
  39748. // Update VBO
  39749. var offset = 0;
  39750. for (var index = 0; index < this.particles.length; index++) {
  39751. var particle = this.particles[index];
  39752. this._appendParticleVertex(offset++, particle, 0, 0);
  39753. this._appendParticleVertex(offset++, particle, 1, 0);
  39754. this._appendParticleVertex(offset++, particle, 1, 1);
  39755. this._appendParticleVertex(offset++, particle, 0, 1);
  39756. }
  39757. this._vertexBuffer.update(this._vertexData);
  39758. };
  39759. ParticleSystem.prototype.render = function () {
  39760. var effect = this._getEffect();
  39761. // Check
  39762. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  39763. return 0;
  39764. var engine = this._scene.getEngine();
  39765. // Render
  39766. engine.enableEffect(effect);
  39767. engine.setState(false);
  39768. var viewMatrix = this._scene.getViewMatrix();
  39769. effect.setTexture("diffuseSampler", this.particleTexture);
  39770. effect.setMatrix("view", viewMatrix);
  39771. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  39772. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  39773. if (this._scene.clipPlane) {
  39774. var clipPlane = this._scene.clipPlane;
  39775. var invView = viewMatrix.clone();
  39776. invView.invert();
  39777. effect.setMatrix("invView", invView);
  39778. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  39779. }
  39780. // VBOs
  39781. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  39782. // Draw order
  39783. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  39784. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  39785. }
  39786. else {
  39787. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  39788. }
  39789. if (this.forceDepthWrite) {
  39790. engine.setDepthWrite(true);
  39791. }
  39792. engine.draw(true, 0, this.particles.length * 6);
  39793. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  39794. return this.particles.length;
  39795. };
  39796. ParticleSystem.prototype.dispose = function () {
  39797. if (this._vertexBuffer) {
  39798. this._vertexBuffer.dispose();
  39799. this._vertexBuffer = null;
  39800. }
  39801. if (this._indexBuffer) {
  39802. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  39803. this._indexBuffer = null;
  39804. }
  39805. if (this.particleTexture) {
  39806. this.particleTexture.dispose();
  39807. this.particleTexture = null;
  39808. }
  39809. // Remove from scene
  39810. var index = this._scene.particleSystems.indexOf(this);
  39811. if (index > -1) {
  39812. this._scene.particleSystems.splice(index, 1);
  39813. }
  39814. // Callback
  39815. this.onDisposeObservable.notifyObservers(this);
  39816. this.onDisposeObservable.clear();
  39817. };
  39818. // Clone
  39819. ParticleSystem.prototype.clone = function (name, newEmitter) {
  39820. var custom = null;
  39821. var program = null;
  39822. if (this.customShader != null) {
  39823. program = this.customShader;
  39824. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  39825. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  39826. }
  39827. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  39828. result.customShader = program;
  39829. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  39830. if (newEmitter === undefined) {
  39831. newEmitter = this.emitter;
  39832. }
  39833. result.emitter = newEmitter;
  39834. if (this.particleTexture) {
  39835. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  39836. }
  39837. if (!this.preventAutoStart) {
  39838. result.start();
  39839. }
  39840. return result;
  39841. };
  39842. ParticleSystem.prototype.serialize = function () {
  39843. var serializationObject = {};
  39844. serializationObject.name = this.name;
  39845. serializationObject.id = this.id;
  39846. // Emitter
  39847. if (this.emitter.position) {
  39848. var emitterMesh = this.emitter;
  39849. serializationObject.emitterId = emitterMesh.id;
  39850. }
  39851. else {
  39852. var emitterPosition = this.emitter;
  39853. serializationObject.emitter = emitterPosition.asArray();
  39854. }
  39855. serializationObject.capacity = this.getCapacity();
  39856. if (this.particleTexture) {
  39857. serializationObject.textureName = this.particleTexture.name;
  39858. }
  39859. // Animations
  39860. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  39861. // Particle system
  39862. serializationObject.minAngularSpeed = this.minAngularSpeed;
  39863. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  39864. serializationObject.minSize = this.minSize;
  39865. serializationObject.maxSize = this.maxSize;
  39866. serializationObject.minEmitPower = this.minEmitPower;
  39867. serializationObject.maxEmitPower = this.maxEmitPower;
  39868. serializationObject.minLifeTime = this.minLifeTime;
  39869. serializationObject.maxLifeTime = this.maxLifeTime;
  39870. serializationObject.emitRate = this.emitRate;
  39871. serializationObject.minEmitBox = this.minEmitBox.asArray();
  39872. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  39873. serializationObject.gravity = this.gravity.asArray();
  39874. serializationObject.direction1 = this.direction1.asArray();
  39875. serializationObject.direction2 = this.direction2.asArray();
  39876. serializationObject.color1 = this.color1.asArray();
  39877. serializationObject.color2 = this.color2.asArray();
  39878. serializationObject.colorDead = this.colorDead.asArray();
  39879. serializationObject.updateSpeed = this.updateSpeed;
  39880. serializationObject.targetStopDuration = this.targetStopDuration;
  39881. serializationObject.textureMask = this.textureMask.asArray();
  39882. serializationObject.blendMode = this.blendMode;
  39883. serializationObject.customShader = this.customShader;
  39884. serializationObject.preventAutoStart = this.preventAutoStart;
  39885. return serializationObject;
  39886. };
  39887. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  39888. var name = parsedParticleSystem.name;
  39889. var custom = null;
  39890. var program = null;
  39891. if (parsedParticleSystem.customShader) {
  39892. program = parsedParticleSystem.customShader;
  39893. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  39894. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  39895. }
  39896. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  39897. particleSystem.customShader = program;
  39898. if (parsedParticleSystem.id) {
  39899. particleSystem.id = parsedParticleSystem.id;
  39900. }
  39901. // Auto start
  39902. if (parsedParticleSystem.preventAutoStart) {
  39903. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  39904. }
  39905. // Texture
  39906. if (parsedParticleSystem.textureName) {
  39907. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  39908. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  39909. }
  39910. // Emitter
  39911. if (parsedParticleSystem.emitterId) {
  39912. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  39913. }
  39914. else {
  39915. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  39916. }
  39917. // Animations
  39918. if (parsedParticleSystem.animations) {
  39919. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  39920. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  39921. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  39922. }
  39923. }
  39924. if (parsedParticleSystem.autoAnimate) {
  39925. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  39926. }
  39927. // Particle system
  39928. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  39929. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  39930. particleSystem.minSize = parsedParticleSystem.minSize;
  39931. particleSystem.maxSize = parsedParticleSystem.maxSize;
  39932. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  39933. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  39934. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  39935. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  39936. particleSystem.emitRate = parsedParticleSystem.emitRate;
  39937. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  39938. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  39939. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  39940. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  39941. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  39942. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  39943. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  39944. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  39945. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  39946. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  39947. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  39948. particleSystem.blendMode = parsedParticleSystem.blendMode;
  39949. if (!particleSystem.preventAutoStart) {
  39950. particleSystem.start();
  39951. }
  39952. return particleSystem;
  39953. };
  39954. return ParticleSystem;
  39955. }());
  39956. // Statics
  39957. ParticleSystem.BLENDMODE_ONEONE = 0;
  39958. ParticleSystem.BLENDMODE_STANDARD = 1;
  39959. BABYLON.ParticleSystem = ParticleSystem;
  39960. })(BABYLON || (BABYLON = {}));
  39961. //# sourceMappingURL=babylon.particleSystem.js.map
  39962. var BABYLON;
  39963. (function (BABYLON) {
  39964. var SolidParticle = (function () {
  39965. /**
  39966. * Creates a Solid Particle object.
  39967. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  39968. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  39969. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  39970. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  39971. * `shapeId` (integer) is the model shape identifier in the SPS.
  39972. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  39973. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  39974. */
  39975. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  39976. this.idx = 0; // particle global index
  39977. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  39978. this.position = BABYLON.Vector3.Zero(); // position
  39979. this.rotation = BABYLON.Vector3.Zero(); // rotation
  39980. this.scaling = BABYLON.Vector3.One(); // scaling
  39981. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  39982. this.velocity = BABYLON.Vector3.Zero(); // velocity
  39983. this.alive = true; // alive
  39984. this.isVisible = true; // visibility
  39985. this._pos = 0; // index of this particle in the global "positions" array
  39986. this.shapeId = 0; // model shape id
  39987. this.idxInShape = 0; // index of the particle in its shape id
  39988. this.idx = particleIndex;
  39989. this._pos = positionIndex;
  39990. this._model = model;
  39991. this.shapeId = shapeId;
  39992. this.idxInShape = idxInShape;
  39993. this._sps = sps;
  39994. if (modelBoundingInfo) {
  39995. this._modelBoundingInfo = modelBoundingInfo;
  39996. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  39997. }
  39998. }
  39999. Object.defineProperty(SolidParticle.prototype, "scale", {
  40000. /**
  40001. * legacy support, changed scale to scaling
  40002. */
  40003. get: function () {
  40004. return this.scaling;
  40005. },
  40006. set: function (scale) {
  40007. this.scaling = scale;
  40008. },
  40009. enumerable: true,
  40010. configurable: true
  40011. });
  40012. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  40013. /**
  40014. * legacy support, changed quaternion to rotationQuaternion
  40015. */
  40016. get: function () {
  40017. return this.rotationQuaternion;
  40018. },
  40019. set: function (q) {
  40020. this.rotationQuaternion = q;
  40021. },
  40022. enumerable: true,
  40023. configurable: true
  40024. });
  40025. /**
  40026. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  40027. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  40028. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  40029. */
  40030. SolidParticle.prototype.intersectsMesh = function (target) {
  40031. if (!this._boundingInfo || !target._boundingInfo) {
  40032. return false;
  40033. }
  40034. if (this._sps._bSphereOnly) {
  40035. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  40036. }
  40037. return this._boundingInfo.intersects(target._boundingInfo, false);
  40038. };
  40039. return SolidParticle;
  40040. }());
  40041. BABYLON.SolidParticle = SolidParticle;
  40042. var ModelShape = (function () {
  40043. /**
  40044. * 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.
  40045. * SPS internal tool, don't use it manually.
  40046. */
  40047. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  40048. this.shapeID = id;
  40049. this._shape = shape;
  40050. this._shapeUV = shapeUV;
  40051. this._positionFunction = posFunction;
  40052. this._vertexFunction = vtxFunction;
  40053. }
  40054. return ModelShape;
  40055. }());
  40056. BABYLON.ModelShape = ModelShape;
  40057. })(BABYLON || (BABYLON = {}));
  40058. //# sourceMappingURL=babylon.solidParticle.js.map
  40059. var BABYLON;
  40060. (function (BABYLON) {
  40061. /**
  40062. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  40063. */
  40064. var SolidParticleSystem = (function () {
  40065. /**
  40066. * Creates a SPS (Solid Particle System) object.
  40067. * `name` (String) is the SPS name, this will be the underlying mesh name.
  40068. * `scene` (Scene) is the scene in which the SPS is added.
  40069. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  40070. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  40071. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  40072. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  40073. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  40074. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  40075. */
  40076. function SolidParticleSystem(name, scene, options) {
  40077. // public members
  40078. /**
  40079. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  40080. * Example : var p = SPS.particles[i];
  40081. */
  40082. this.particles = new Array();
  40083. /**
  40084. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  40085. */
  40086. this.nbParticles = 0;
  40087. /**
  40088. * If the particles must ever face the camera (default false). Useful for planar particles.
  40089. */
  40090. this.billboard = false;
  40091. /**
  40092. * Recompute normals when adding a shape
  40093. */
  40094. this.recomputeNormals = true;
  40095. /**
  40096. * This a counter ofr your own usage. It's not set by any SPS functions.
  40097. */
  40098. this.counter = 0;
  40099. /**
  40100. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  40101. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  40102. */
  40103. this.vars = {};
  40104. this._positions = new Array();
  40105. this._indices = new Array();
  40106. this._normals = new Array();
  40107. this._colors = new Array();
  40108. this._uvs = new Array();
  40109. this._index = 0; // indices index
  40110. this._updatable = true;
  40111. this._pickable = false;
  40112. this._isVisibilityBoxLocked = false;
  40113. this._alwaysVisible = false;
  40114. this._shapeCounter = 0;
  40115. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  40116. this._color = new BABYLON.Color4(0, 0, 0, 0);
  40117. this._computeParticleColor = true;
  40118. this._computeParticleTexture = true;
  40119. this._computeParticleRotation = true;
  40120. this._computeParticleVertex = false;
  40121. this._computeBoundingBox = false;
  40122. this._cam_axisZ = BABYLON.Vector3.Zero();
  40123. this._cam_axisY = BABYLON.Vector3.Zero();
  40124. this._cam_axisX = BABYLON.Vector3.Zero();
  40125. this._axisX = BABYLON.Axis.X;
  40126. this._axisY = BABYLON.Axis.Y;
  40127. this._axisZ = BABYLON.Axis.Z;
  40128. this._camDir = BABYLON.Vector3.Zero();
  40129. this._rotMatrix = new BABYLON.Matrix();
  40130. this._invertMatrix = new BABYLON.Matrix();
  40131. this._rotated = BABYLON.Vector3.Zero();
  40132. this._quaternion = new BABYLON.Quaternion();
  40133. this._vertex = BABYLON.Vector3.Zero();
  40134. this._normal = BABYLON.Vector3.Zero();
  40135. this._yaw = 0.0;
  40136. this._pitch = 0.0;
  40137. this._roll = 0.0;
  40138. this._halfroll = 0.0;
  40139. this._halfpitch = 0.0;
  40140. this._halfyaw = 0.0;
  40141. this._sinRoll = 0.0;
  40142. this._cosRoll = 0.0;
  40143. this._sinPitch = 0.0;
  40144. this._cosPitch = 0.0;
  40145. this._sinYaw = 0.0;
  40146. this._cosYaw = 0.0;
  40147. this._w = 0.0;
  40148. this._mustUnrotateFixedNormals = false;
  40149. this._minimum = BABYLON.Tmp.Vector3[0];
  40150. this._maximum = BABYLON.Tmp.Vector3[1];
  40151. this._scale = BABYLON.Tmp.Vector3[2];
  40152. this._translation = BABYLON.Tmp.Vector3[3];
  40153. this._minBbox = BABYLON.Tmp.Vector3[4];
  40154. this._maxBbox = BABYLON.Tmp.Vector3[5];
  40155. this._particlesIntersect = false;
  40156. this._bSphereOnly = false;
  40157. this._bSphereRadiusFactor = 1.0;
  40158. this.name = name;
  40159. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  40160. this._camera = scene.activeCamera;
  40161. this._pickable = options ? options.isPickable : false;
  40162. this._particlesIntersect = options ? options.particleIntersection : false;
  40163. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  40164. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  40165. if (options && options.updatable) {
  40166. this._updatable = options.updatable;
  40167. }
  40168. else {
  40169. this._updatable = true;
  40170. }
  40171. if (this._pickable) {
  40172. this.pickedParticles = [];
  40173. }
  40174. }
  40175. /**
  40176. * Builds the SPS underlying mesh. Returns a standard Mesh.
  40177. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  40178. */
  40179. SolidParticleSystem.prototype.buildMesh = function () {
  40180. if (this.nbParticles === 0) {
  40181. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  40182. this.addShape(triangle, 1);
  40183. triangle.dispose();
  40184. }
  40185. this._positions32 = new Float32Array(this._positions);
  40186. this._uvs32 = new Float32Array(this._uvs);
  40187. this._colors32 = new Float32Array(this._colors);
  40188. if (this.recomputeNormals) {
  40189. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  40190. }
  40191. this._normals32 = new Float32Array(this._normals);
  40192. this._fixedNormal32 = new Float32Array(this._normals);
  40193. if (this._mustUnrotateFixedNormals) {
  40194. this._unrotateFixedNormals();
  40195. }
  40196. var vertexData = new BABYLON.VertexData();
  40197. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  40198. vertexData.indices = this._indices;
  40199. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  40200. if (this._uvs32) {
  40201. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  40202. ;
  40203. }
  40204. if (this._colors32) {
  40205. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  40206. }
  40207. var mesh = new BABYLON.Mesh(this.name, this._scene);
  40208. vertexData.applyToMesh(mesh, this._updatable);
  40209. this.mesh = mesh;
  40210. this.mesh.isPickable = this._pickable;
  40211. // free memory
  40212. this._positions = null;
  40213. this._normals = null;
  40214. this._uvs = null;
  40215. this._colors = null;
  40216. if (!this._updatable) {
  40217. this.particles.length = 0;
  40218. }
  40219. return mesh;
  40220. };
  40221. /**
  40222. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  40223. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  40224. * Thus the particles generated from `digest()` have their property `position` set yet.
  40225. * `mesh` ( Mesh ) is the mesh to be digested
  40226. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  40227. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  40228. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  40229. */
  40230. SolidParticleSystem.prototype.digest = function (mesh, options) {
  40231. var size = (options && options.facetNb) || 1;
  40232. var number = (options && options.number);
  40233. var delta = (options && options.delta) || 0;
  40234. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40235. var meshInd = mesh.getIndices();
  40236. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  40237. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  40238. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  40239. var f = 0; // facet counter
  40240. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  40241. // compute size from number
  40242. if (number) {
  40243. number = (number > totalFacets) ? totalFacets : number;
  40244. size = Math.round(totalFacets / number);
  40245. delta = 0;
  40246. }
  40247. else {
  40248. size = (size > totalFacets) ? totalFacets : size;
  40249. }
  40250. var facetPos = []; // submesh positions
  40251. var facetInd = []; // submesh indices
  40252. var facetUV = []; // submesh UV
  40253. var facetCol = []; // submesh colors
  40254. var barycenter = BABYLON.Tmp.Vector3[0];
  40255. var rand;
  40256. var sizeO = size;
  40257. while (f < totalFacets) {
  40258. size = sizeO + Math.floor((1 + delta) * Math.random());
  40259. if (f > totalFacets - size) {
  40260. size = totalFacets - f;
  40261. }
  40262. // reset temp arrays
  40263. facetPos.length = 0;
  40264. facetInd.length = 0;
  40265. facetUV.length = 0;
  40266. facetCol.length = 0;
  40267. // iterate over "size" facets
  40268. var fi = 0;
  40269. for (var j = f * 3; j < (f + size) * 3; j++) {
  40270. facetInd.push(fi);
  40271. var i = meshInd[j];
  40272. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  40273. if (meshUV) {
  40274. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  40275. }
  40276. if (meshCol) {
  40277. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  40278. }
  40279. fi++;
  40280. }
  40281. // create a model shape for each single particle
  40282. var idx = this.nbParticles;
  40283. var shape = this._posToShape(facetPos);
  40284. var shapeUV = this._uvsToShapeUV(facetUV);
  40285. // compute the barycenter of the shape
  40286. var v;
  40287. for (v = 0; v < shape.length; v++) {
  40288. barycenter.addInPlace(shape[v]);
  40289. }
  40290. barycenter.scaleInPlace(1 / shape.length);
  40291. // shift the shape from its barycenter to the origin
  40292. for (v = 0; v < shape.length; v++) {
  40293. shape[v].subtractInPlace(barycenter);
  40294. }
  40295. var bInfo;
  40296. if (this._particlesIntersect) {
  40297. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  40298. }
  40299. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  40300. // add the particle in the SPS
  40301. var currentPos = this._positions.length;
  40302. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  40303. this._addParticle(idx, currentPos, modelShape, this._shapeCounter, 0, bInfo);
  40304. // initialize the particle position
  40305. this.particles[this.nbParticles].position.addInPlace(barycenter);
  40306. this._index += shape.length;
  40307. idx++;
  40308. this.nbParticles++;
  40309. this._shapeCounter++;
  40310. f += size;
  40311. }
  40312. return this;
  40313. };
  40314. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  40315. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  40316. var index = 0;
  40317. var idx = 0;
  40318. for (var p = 0; p < this.particles.length; p++) {
  40319. this._particle = this.particles[p];
  40320. this._shape = this._particle._model._shape;
  40321. if (this._particle.rotationQuaternion) {
  40322. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  40323. }
  40324. else {
  40325. this._yaw = this._particle.rotation.y;
  40326. this._pitch = this._particle.rotation.x;
  40327. this._roll = this._particle.rotation.z;
  40328. this._quaternionRotationYPR();
  40329. }
  40330. this._quaternionToRotationMatrix();
  40331. this._rotMatrix.invertToRef(this._invertMatrix);
  40332. for (var pt = 0; pt < this._shape.length; pt++) {
  40333. idx = index + pt * 3;
  40334. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  40335. this._fixedNormal32[idx] = this._normal.x;
  40336. this._fixedNormal32[idx + 1] = this._normal.y;
  40337. this._fixedNormal32[idx + 2] = this._normal.z;
  40338. }
  40339. index = idx + 3;
  40340. }
  40341. };
  40342. //reset copy
  40343. SolidParticleSystem.prototype._resetCopy = function () {
  40344. this._copy.position.x = 0;
  40345. this._copy.position.y = 0;
  40346. this._copy.position.z = 0;
  40347. this._copy.rotation.x = 0;
  40348. this._copy.rotation.y = 0;
  40349. this._copy.rotation.z = 0;
  40350. this._copy.rotationQuaternion = null;
  40351. this._copy.scaling.x = 1;
  40352. this._copy.scaling.y = 1;
  40353. this._copy.scaling.z = 1;
  40354. this._copy.uvs.x = 0;
  40355. this._copy.uvs.y = 0;
  40356. this._copy.uvs.z = 1;
  40357. this._copy.uvs.w = 1;
  40358. this._copy.color = null;
  40359. };
  40360. // _meshBuilder : inserts the shape model in the global SPS mesh
  40361. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  40362. var i;
  40363. var u = 0;
  40364. var c = 0;
  40365. var n = 0;
  40366. this._resetCopy();
  40367. if (options && options.positionFunction) {
  40368. options.positionFunction(this._copy, idx, idxInShape);
  40369. this._mustUnrotateFixedNormals = true;
  40370. }
  40371. if (this._copy.rotationQuaternion) {
  40372. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  40373. }
  40374. else {
  40375. this._yaw = this._copy.rotation.y;
  40376. this._pitch = this._copy.rotation.x;
  40377. this._roll = this._copy.rotation.z;
  40378. this._quaternionRotationYPR();
  40379. }
  40380. this._quaternionToRotationMatrix();
  40381. for (i = 0; i < shape.length; i++) {
  40382. this._vertex.x = shape[i].x;
  40383. this._vertex.y = shape[i].y;
  40384. this._vertex.z = shape[i].z;
  40385. if (options && options.vertexFunction) {
  40386. options.vertexFunction(this._copy, this._vertex, i);
  40387. }
  40388. this._vertex.x *= this._copy.scaling.x;
  40389. this._vertex.y *= this._copy.scaling.y;
  40390. this._vertex.z *= this._copy.scaling.z;
  40391. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  40392. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  40393. if (meshUV) {
  40394. 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);
  40395. u += 2;
  40396. }
  40397. if (this._copy.color) {
  40398. this._color = this._copy.color;
  40399. }
  40400. else if (meshCol && meshCol[c] !== undefined) {
  40401. this._color.r = meshCol[c];
  40402. this._color.g = meshCol[c + 1];
  40403. this._color.b = meshCol[c + 2];
  40404. this._color.a = meshCol[c + 3];
  40405. }
  40406. else {
  40407. this._color.r = 1;
  40408. this._color.g = 1;
  40409. this._color.b = 1;
  40410. this._color.a = 1;
  40411. }
  40412. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  40413. c += 4;
  40414. if (!this.recomputeNormals && meshNor) {
  40415. this._normal.x = meshNor[n];
  40416. this._normal.y = meshNor[n + 1];
  40417. this._normal.z = meshNor[n + 2];
  40418. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  40419. normals.push(this._normal.x, this._normal.y, this._normal.z);
  40420. n += 3;
  40421. }
  40422. }
  40423. for (i = 0; i < meshInd.length; i++) {
  40424. indices.push(p + meshInd[i]);
  40425. }
  40426. if (this._pickable) {
  40427. var nbfaces = meshInd.length / 3;
  40428. for (i = 0; i < nbfaces; i++) {
  40429. this.pickedParticles.push({ idx: idx, faceId: i });
  40430. }
  40431. }
  40432. return this._copy;
  40433. };
  40434. // returns a shape array from positions array
  40435. SolidParticleSystem.prototype._posToShape = function (positions) {
  40436. var shape = [];
  40437. for (var i = 0; i < positions.length; i += 3) {
  40438. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  40439. }
  40440. return shape;
  40441. };
  40442. // returns a shapeUV array from a Vector4 uvs
  40443. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  40444. var shapeUV = [];
  40445. if (uvs) {
  40446. for (var i = 0; i < uvs.length; i++)
  40447. shapeUV.push(uvs[i]);
  40448. }
  40449. return shapeUV;
  40450. };
  40451. // adds a new particle object in the particles array
  40452. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  40453. var sp = new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo);
  40454. this.particles.push(sp);
  40455. return sp;
  40456. };
  40457. /**
  40458. * Adds some particles to the SPS from the model shape. Returns the shape id.
  40459. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  40460. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  40461. * `nb` (positive integer) the number of particles to be created from this model
  40462. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  40463. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  40464. */
  40465. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  40466. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40467. var meshInd = mesh.getIndices();
  40468. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  40469. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  40470. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  40471. var bbInfo;
  40472. if (this._particlesIntersect) {
  40473. bbInfo = mesh.getBoundingInfo();
  40474. }
  40475. var shape = this._posToShape(meshPos);
  40476. var shapeUV = this._uvsToShapeUV(meshUV);
  40477. var posfunc = options ? options.positionFunction : null;
  40478. var vtxfunc = options ? options.vertexFunction : null;
  40479. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  40480. // particles
  40481. var sp;
  40482. var currentCopy;
  40483. var idx = this.nbParticles;
  40484. for (var i = 0; i < nb; i++) {
  40485. var currentPos = this._positions.length;
  40486. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  40487. if (this._updatable) {
  40488. sp = this._addParticle(idx, currentPos, modelShape, this._shapeCounter, i, bbInfo);
  40489. sp.position.copyFrom(currentCopy.position);
  40490. sp.rotation.copyFrom(currentCopy.rotation);
  40491. if (currentCopy.rotationQuaternion) {
  40492. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  40493. }
  40494. if (currentCopy.color) {
  40495. sp.color.copyFrom(currentCopy.color);
  40496. }
  40497. sp.scaling.copyFrom(currentCopy.scaling);
  40498. sp.uvs.copyFrom(currentCopy.uvs);
  40499. }
  40500. this._index += shape.length;
  40501. idx++;
  40502. }
  40503. this.nbParticles += nb;
  40504. this._shapeCounter++;
  40505. return this._shapeCounter - 1;
  40506. };
  40507. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  40508. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  40509. this._resetCopy();
  40510. if (particle._model._positionFunction) {
  40511. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  40512. }
  40513. if (this._copy.rotationQuaternion) {
  40514. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  40515. }
  40516. else {
  40517. this._yaw = this._copy.rotation.y;
  40518. this._pitch = this._copy.rotation.x;
  40519. this._roll = this._copy.rotation.z;
  40520. this._quaternionRotationYPR();
  40521. }
  40522. this._quaternionToRotationMatrix();
  40523. this._shape = particle._model._shape;
  40524. for (var pt = 0; pt < this._shape.length; pt++) {
  40525. this._vertex.x = this._shape[pt].x;
  40526. this._vertex.y = this._shape[pt].y;
  40527. this._vertex.z = this._shape[pt].z;
  40528. if (particle._model._vertexFunction) {
  40529. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  40530. }
  40531. this._vertex.x *= this._copy.scaling.x;
  40532. this._vertex.y *= this._copy.scaling.y;
  40533. this._vertex.z *= this._copy.scaling.z;
  40534. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  40535. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  40536. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  40537. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  40538. }
  40539. particle.position.x = 0.0;
  40540. particle.position.y = 0.0;
  40541. particle.position.z = 0.0;
  40542. particle.rotation.x = 0.0;
  40543. particle.rotation.y = 0.0;
  40544. particle.rotation.z = 0.0;
  40545. particle.rotationQuaternion = null;
  40546. particle.scaling.x = 1.0;
  40547. particle.scaling.y = 1.0;
  40548. particle.scaling.z = 1.0;
  40549. };
  40550. /**
  40551. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  40552. * Returns the SPS.
  40553. */
  40554. SolidParticleSystem.prototype.rebuildMesh = function () {
  40555. for (var p = 0; p < this.particles.length; p++) {
  40556. this._rebuildParticle(this.particles[p]);
  40557. }
  40558. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  40559. return this;
  40560. };
  40561. /**
  40562. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  40563. * This method calls `updateParticle()` for each particle of the SPS.
  40564. * For an animated SPS, it is usually called within the render loop.
  40565. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  40566. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  40567. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  40568. * Returns the SPS.
  40569. */
  40570. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  40571. if (start === void 0) { start = 0; }
  40572. if (end === void 0) { end = this.nbParticles - 1; }
  40573. if (update === void 0) { update = true; }
  40574. if (!this._updatable) {
  40575. return;
  40576. }
  40577. // custom beforeUpdate
  40578. this.beforeUpdateParticles(start, end, update);
  40579. this._cam_axisX.x = 1.0;
  40580. this._cam_axisX.y = 0.0;
  40581. this._cam_axisX.z = 0.0;
  40582. this._cam_axisY.x = 0.0;
  40583. this._cam_axisY.y = 1.0;
  40584. this._cam_axisY.z = 0.0;
  40585. this._cam_axisZ.x = 0.0;
  40586. this._cam_axisZ.y = 0.0;
  40587. this._cam_axisZ.z = 1.0;
  40588. // if the particles will always face the camera
  40589. if (this.billboard) {
  40590. this.mesh.computeWorldMatrix(true);
  40591. // compute the camera position and un-rotate it by the current mesh rotation
  40592. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  40593. this._quaternionToRotationMatrix();
  40594. this._rotMatrix.invertToRef(this._invertMatrix);
  40595. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  40596. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  40597. this._cam_axisZ.normalize();
  40598. // same for camera up vector extracted from the cam view matrix
  40599. var view = this._camera.getViewMatrix(true);
  40600. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  40601. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  40602. this._cam_axisY.normalize();
  40603. this._cam_axisX.normalize();
  40604. }
  40605. }
  40606. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  40607. var idx = 0; // current position index in the global array positions32
  40608. var index = 0; // position start index in the global array positions32 of the current particle
  40609. var colidx = 0; // current color index in the global array colors32
  40610. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  40611. var uvidx = 0; // current uv index in the global array uvs32
  40612. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  40613. var pt = 0; // current index in the particle model shape
  40614. if (this.mesh.isFacetDataEnabled) {
  40615. this._computeBoundingBox = true;
  40616. }
  40617. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  40618. if (this._computeBoundingBox) {
  40619. if (start == 0 && end == this.nbParticles - 1) {
  40620. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  40621. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  40622. }
  40623. else {
  40624. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  40625. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  40626. }
  40627. }
  40628. // particle loop
  40629. index = this.particles[start]._pos;
  40630. var vpos = (index / 3) | 0;
  40631. colorIndex = vpos * 4;
  40632. uvIndex = vpos * 2;
  40633. for (var p = start; p <= end; p++) {
  40634. this._particle = this.particles[p];
  40635. this._shape = this._particle._model._shape;
  40636. this._shapeUV = this._particle._model._shapeUV;
  40637. // call to custom user function to update the particle properties
  40638. this.updateParticle(this._particle);
  40639. if (this._particle.isVisible) {
  40640. // particle rotation matrix
  40641. if (this.billboard) {
  40642. this._particle.rotation.x = 0.0;
  40643. this._particle.rotation.y = 0.0;
  40644. }
  40645. if (this._computeParticleRotation || this.billboard) {
  40646. if (this._particle.rotationQuaternion) {
  40647. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  40648. }
  40649. else {
  40650. this._yaw = this._particle.rotation.y;
  40651. this._pitch = this._particle.rotation.x;
  40652. this._roll = this._particle.rotation.z;
  40653. this._quaternionRotationYPR();
  40654. }
  40655. this._quaternionToRotationMatrix();
  40656. }
  40657. // particle vertex loop
  40658. for (pt = 0; pt < this._shape.length; pt++) {
  40659. idx = index + pt * 3;
  40660. colidx = colorIndex + pt * 4;
  40661. uvidx = uvIndex + pt * 2;
  40662. this._vertex.x = this._shape[pt].x;
  40663. this._vertex.y = this._shape[pt].y;
  40664. this._vertex.z = this._shape[pt].z;
  40665. if (this._computeParticleVertex) {
  40666. this.updateParticleVertex(this._particle, this._vertex, pt);
  40667. }
  40668. // positions
  40669. this._vertex.x *= this._particle.scaling.x;
  40670. this._vertex.y *= this._particle.scaling.y;
  40671. this._vertex.z *= this._particle.scaling.z;
  40672. 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];
  40673. 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;
  40674. 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;
  40675. 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;
  40676. 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;
  40677. 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;
  40678. 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;
  40679. if (this._computeBoundingBox) {
  40680. if (this._positions32[idx] < this._minimum.x) {
  40681. this._minimum.x = this._positions32[idx];
  40682. }
  40683. if (this._positions32[idx] > this._maximum.x) {
  40684. this._maximum.x = this._positions32[idx];
  40685. }
  40686. if (this._positions32[idx + 1] < this._minimum.y) {
  40687. this._minimum.y = this._positions32[idx + 1];
  40688. }
  40689. if (this._positions32[idx + 1] > this._maximum.y) {
  40690. this._maximum.y = this._positions32[idx + 1];
  40691. }
  40692. if (this._positions32[idx + 2] < this._minimum.z) {
  40693. this._minimum.z = this._positions32[idx + 2];
  40694. }
  40695. if (this._positions32[idx + 2] > this._maximum.z) {
  40696. this._maximum.z = this._positions32[idx + 2];
  40697. }
  40698. }
  40699. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  40700. if (!this._computeParticleVertex) {
  40701. this._normal.x = this._fixedNormal32[idx];
  40702. this._normal.y = this._fixedNormal32[idx + 1];
  40703. this._normal.z = this._fixedNormal32[idx + 2];
  40704. 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]);
  40705. 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]);
  40706. 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]);
  40707. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  40708. 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;
  40709. 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;
  40710. }
  40711. if (this._computeParticleColor) {
  40712. this._colors32[colidx] = this._particle.color.r;
  40713. this._colors32[colidx + 1] = this._particle.color.g;
  40714. this._colors32[colidx + 2] = this._particle.color.b;
  40715. this._colors32[colidx + 3] = this._particle.color.a;
  40716. }
  40717. if (this._computeParticleTexture) {
  40718. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  40719. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  40720. }
  40721. }
  40722. }
  40723. else {
  40724. for (pt = 0; pt < this._shape.length; pt++) {
  40725. idx = index + pt * 3;
  40726. colidx = colorIndex + pt * 4;
  40727. uvidx = uvIndex + pt * 2;
  40728. this._positions32[idx] = this._camera.globalPosition.x;
  40729. this._positions32[idx + 1] = this._camera.globalPosition.y;
  40730. this._positions32[idx + 2] = this._camera.globalPosition.z;
  40731. this._normals32[idx] = 0.0;
  40732. this._normals32[idx + 1] = 0.0;
  40733. this._normals32[idx + 2] = 0.0;
  40734. if (this._computeParticleColor) {
  40735. this._colors32[colidx] = this._particle.color.r;
  40736. this._colors32[colidx + 1] = this._particle.color.g;
  40737. this._colors32[colidx + 2] = this._particle.color.b;
  40738. this._colors32[colidx + 3] = this._particle.color.a;
  40739. }
  40740. if (this._computeParticleTexture) {
  40741. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  40742. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  40743. }
  40744. }
  40745. }
  40746. // if the particle intersections must be computed : update the bbInfo
  40747. if (this._particlesIntersect) {
  40748. var bInfo = this._particle._boundingInfo;
  40749. var bBox = bInfo.boundingBox;
  40750. var bSphere = bInfo.boundingSphere;
  40751. if (!this._bSphereOnly) {
  40752. // place, scale and rotate the particle bbox within the SPS local system, then update it
  40753. for (var b = 0; b < bBox.vectors.length; b++) {
  40754. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  40755. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  40756. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  40757. 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];
  40758. 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;
  40759. 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;
  40760. 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;
  40761. 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;
  40762. 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;
  40763. 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;
  40764. }
  40765. bBox._update(this.mesh._worldMatrix);
  40766. }
  40767. // place and scale the particle bouding sphere in the SPS local system, then update it
  40768. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  40769. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  40770. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  40771. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  40772. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  40773. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  40774. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  40775. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  40776. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  40777. 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));
  40778. bSphere._update(this.mesh._worldMatrix);
  40779. }
  40780. // increment indexes for the next particle
  40781. index = idx + 3;
  40782. colorIndex = colidx + 4;
  40783. uvIndex = uvidx + 2;
  40784. }
  40785. // if the VBO must be updated
  40786. if (update) {
  40787. if (this._computeParticleColor) {
  40788. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  40789. }
  40790. if (this._computeParticleTexture) {
  40791. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  40792. }
  40793. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  40794. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  40795. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  40796. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  40797. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  40798. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  40799. for (var i = 0; i < this._normals32.length; i++) {
  40800. this._fixedNormal32[i] = this._normals32[i];
  40801. }
  40802. }
  40803. if (!this.mesh.areNormalsFrozen) {
  40804. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  40805. }
  40806. }
  40807. }
  40808. if (this._computeBoundingBox) {
  40809. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  40810. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  40811. }
  40812. this.afterUpdateParticles(start, end, update);
  40813. return this;
  40814. };
  40815. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  40816. this._halfroll = this._roll * 0.5;
  40817. this._halfpitch = this._pitch * 0.5;
  40818. this._halfyaw = this._yaw * 0.5;
  40819. this._sinRoll = Math.sin(this._halfroll);
  40820. this._cosRoll = Math.cos(this._halfroll);
  40821. this._sinPitch = Math.sin(this._halfpitch);
  40822. this._cosPitch = Math.cos(this._halfpitch);
  40823. this._sinYaw = Math.sin(this._halfyaw);
  40824. this._cosYaw = Math.cos(this._halfyaw);
  40825. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  40826. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  40827. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  40828. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  40829. };
  40830. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  40831. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  40832. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  40833. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  40834. this._rotMatrix.m[3] = 0;
  40835. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  40836. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  40837. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  40838. this._rotMatrix.m[7] = 0;
  40839. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  40840. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  40841. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  40842. this._rotMatrix.m[11] = 0;
  40843. this._rotMatrix.m[12] = 0;
  40844. this._rotMatrix.m[13] = 0;
  40845. this._rotMatrix.m[14] = 0;
  40846. this._rotMatrix.m[15] = 1.0;
  40847. };
  40848. /**
  40849. * Disposes the SPS.
  40850. * Returns nothing.
  40851. */
  40852. SolidParticleSystem.prototype.dispose = function () {
  40853. this.mesh.dispose();
  40854. this.vars = null;
  40855. // drop references to internal big arrays for the GC
  40856. this._positions = null;
  40857. this._indices = null;
  40858. this._normals = null;
  40859. this._uvs = null;
  40860. this._colors = null;
  40861. this._positions32 = null;
  40862. this._normals32 = null;
  40863. this._fixedNormal32 = null;
  40864. this._uvs32 = null;
  40865. this._colors32 = null;
  40866. this.pickedParticles = null;
  40867. };
  40868. /**
  40869. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  40870. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  40871. * Returns the SPS.
  40872. */
  40873. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  40874. if (!this._isVisibilityBoxLocked) {
  40875. this.mesh.refreshBoundingInfo();
  40876. }
  40877. return this;
  40878. };
  40879. /**
  40880. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  40881. * @param size the size (float) of the visibility box
  40882. * note : this doesn't lock the SPS mesh bounding box.
  40883. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  40884. */
  40885. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  40886. var vis = size / 2;
  40887. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  40888. };
  40889. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  40890. // getter and setter
  40891. get: function () {
  40892. return this._alwaysVisible;
  40893. },
  40894. /**
  40895. * Sets the SPS as always visible or not
  40896. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  40897. */
  40898. set: function (val) {
  40899. this._alwaysVisible = val;
  40900. this.mesh.alwaysSelectAsActiveMesh = val;
  40901. },
  40902. enumerable: true,
  40903. configurable: true
  40904. });
  40905. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  40906. get: function () {
  40907. return this._isVisibilityBoxLocked;
  40908. },
  40909. /**
  40910. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  40911. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  40912. */
  40913. set: function (val) {
  40914. this._isVisibilityBoxLocked = val;
  40915. this.mesh.getBoundingInfo().isLocked = val;
  40916. },
  40917. enumerable: true,
  40918. configurable: true
  40919. });
  40920. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  40921. // getters
  40922. get: function () {
  40923. return this._computeParticleRotation;
  40924. },
  40925. // Optimizer setters
  40926. /**
  40927. * Tells to `setParticles()` to compute the particle rotations or not.
  40928. * Default value : true. The SPS is faster when it's set to false.
  40929. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  40930. */
  40931. set: function (val) {
  40932. this._computeParticleRotation = val;
  40933. },
  40934. enumerable: true,
  40935. configurable: true
  40936. });
  40937. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  40938. get: function () {
  40939. return this._computeParticleColor;
  40940. },
  40941. /**
  40942. * Tells to `setParticles()` to compute the particle colors or not.
  40943. * Default value : true. The SPS is faster when it's set to false.
  40944. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  40945. */
  40946. set: function (val) {
  40947. this._computeParticleColor = val;
  40948. },
  40949. enumerable: true,
  40950. configurable: true
  40951. });
  40952. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  40953. get: function () {
  40954. return this._computeParticleTexture;
  40955. },
  40956. /**
  40957. * Tells to `setParticles()` to compute the particle textures or not.
  40958. * Default value : true. The SPS is faster when it's set to false.
  40959. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  40960. */
  40961. set: function (val) {
  40962. this._computeParticleTexture = val;
  40963. },
  40964. enumerable: true,
  40965. configurable: true
  40966. });
  40967. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  40968. get: function () {
  40969. return this._computeParticleVertex;
  40970. },
  40971. /**
  40972. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  40973. * Default value : false. The SPS is faster when it's set to false.
  40974. * Note : the particle custom vertex positions aren't stored values.
  40975. */
  40976. set: function (val) {
  40977. this._computeParticleVertex = val;
  40978. },
  40979. enumerable: true,
  40980. configurable: true
  40981. });
  40982. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  40983. get: function () {
  40984. return this._computeBoundingBox;
  40985. },
  40986. /**
  40987. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  40988. */
  40989. set: function (val) {
  40990. this._computeBoundingBox = val;
  40991. },
  40992. enumerable: true,
  40993. configurable: true
  40994. });
  40995. // =======================================================================
  40996. // Particle behavior logic
  40997. // these following methods may be overwritten by the user to fit his needs
  40998. /**
  40999. * This function does nothing. It may be overwritten to set all the particle first values.
  41000. * The SPS doesn't call this function, you may have to call it by your own.
  41001. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  41002. */
  41003. SolidParticleSystem.prototype.initParticles = function () {
  41004. };
  41005. /**
  41006. * This function does nothing. It may be overwritten to recycle a particle.
  41007. * The SPS doesn't call this function, you may have to call it by your own.
  41008. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  41009. */
  41010. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  41011. return particle;
  41012. };
  41013. /**
  41014. * Updates a particle : this function should be overwritten by the user.
  41015. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  41016. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  41017. * ex : just set a particle position or velocity and recycle conditions
  41018. */
  41019. SolidParticleSystem.prototype.updateParticle = function (particle) {
  41020. return particle;
  41021. };
  41022. /**
  41023. * Updates a vertex of a particle : it can be overwritten by the user.
  41024. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  41025. * @param particle the current particle
  41026. * @param vertex the current index of the current particle
  41027. * @param pt the index of the current vertex in the particle shape
  41028. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  41029. * ex : just set a vertex particle position
  41030. */
  41031. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  41032. return vertex;
  41033. };
  41034. /**
  41035. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  41036. * This does nothing and may be overwritten by the user.
  41037. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  41038. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  41039. * @param update the boolean update value actually passed to setParticles()
  41040. */
  41041. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  41042. };
  41043. /**
  41044. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  41045. * This will be passed three parameters.
  41046. * This does nothing and may be overwritten by the user.
  41047. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  41048. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  41049. * @param update the boolean update value actually passed to setParticles()
  41050. */
  41051. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  41052. };
  41053. return SolidParticleSystem;
  41054. }());
  41055. BABYLON.SolidParticleSystem = SolidParticleSystem;
  41056. })(BABYLON || (BABYLON = {}));
  41057. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  41058. /// <reference path="babylon.mesh.ts" />
  41059. var BABYLON;
  41060. (function (BABYLON) {
  41061. var GroundMesh = (function (_super) {
  41062. __extends(GroundMesh, _super);
  41063. function GroundMesh(name, scene) {
  41064. var _this = _super.call(this, name, scene) || this;
  41065. _this.generateOctree = false;
  41066. _this._worldInverse = new BABYLON.Matrix();
  41067. return _this;
  41068. }
  41069. GroundMesh.prototype.getClassName = function () {
  41070. return "GroundMesh";
  41071. };
  41072. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  41073. get: function () {
  41074. return Math.min(this._subdivisionsX, this._subdivisionsY);
  41075. },
  41076. enumerable: true,
  41077. configurable: true
  41078. });
  41079. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  41080. get: function () {
  41081. return this._subdivisionsX;
  41082. },
  41083. enumerable: true,
  41084. configurable: true
  41085. });
  41086. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  41087. get: function () {
  41088. return this._subdivisionsY;
  41089. },
  41090. enumerable: true,
  41091. configurable: true
  41092. });
  41093. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  41094. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  41095. this._subdivisionsX = chunksCount;
  41096. this._subdivisionsY = chunksCount;
  41097. this.subdivide(chunksCount);
  41098. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  41099. };
  41100. /**
  41101. * Returns a height (y) value in the Worl system :
  41102. * the ground altitude at the coordinates (x, z) expressed in the World system.
  41103. * Returns the ground y position if (x, z) are outside the ground surface.
  41104. */
  41105. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  41106. var world = this.getWorldMatrix();
  41107. var invMat = BABYLON.Tmp.Matrix[5];
  41108. world.invertToRef(invMat);
  41109. var tmpVect = BABYLON.Tmp.Vector3[8];
  41110. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  41111. x = tmpVect.x;
  41112. z = tmpVect.z;
  41113. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  41114. return this.position.y;
  41115. }
  41116. if (!this._heightQuads || this._heightQuads.length == 0) {
  41117. this._initHeightQuads();
  41118. this._computeHeightQuads();
  41119. }
  41120. var facet = this._getFacetAt(x, z);
  41121. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  41122. // return y in the World system
  41123. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  41124. return tmpVect.y;
  41125. };
  41126. /**
  41127. * Returns a normalized vector (Vector3) orthogonal to the ground
  41128. * at the ground coordinates (x, z) expressed in the World system.
  41129. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  41130. */
  41131. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  41132. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  41133. this.getNormalAtCoordinatesToRef(x, z, normal);
  41134. return normal;
  41135. };
  41136. /**
  41137. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  41138. * at the ground coordinates (x, z) expressed in the World system.
  41139. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  41140. * Returns the GroundMesh.
  41141. */
  41142. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  41143. var world = this.getWorldMatrix();
  41144. var tmpMat = BABYLON.Tmp.Matrix[5];
  41145. world.invertToRef(tmpMat);
  41146. var tmpVect = BABYLON.Tmp.Vector3[8];
  41147. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  41148. x = tmpVect.x;
  41149. z = tmpVect.z;
  41150. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  41151. return this;
  41152. }
  41153. if (!this._heightQuads || this._heightQuads.length == 0) {
  41154. this._initHeightQuads();
  41155. this._computeHeightQuads();
  41156. }
  41157. var facet = this._getFacetAt(x, z);
  41158. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  41159. return this;
  41160. };
  41161. /**
  41162. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  41163. * if the ground has been updated.
  41164. * This can be used in the render loop.
  41165. * Returns the GroundMesh.
  41166. */
  41167. GroundMesh.prototype.updateCoordinateHeights = function () {
  41168. if (!this._heightQuads || this._heightQuads.length == 0) {
  41169. this._initHeightQuads();
  41170. }
  41171. this._computeHeightQuads();
  41172. return this;
  41173. };
  41174. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  41175. GroundMesh.prototype._getFacetAt = function (x, z) {
  41176. // retrieve col and row from x, z coordinates in the ground local system
  41177. var subdivisionsX = this._subdivisionsX;
  41178. var subdivisionsY = this._subdivisionsY;
  41179. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  41180. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  41181. var quad = this._heightQuads[row * this._subdivisionsX + col];
  41182. var facet;
  41183. if (z < quad.slope.x * x + quad.slope.y) {
  41184. facet = quad.facet1;
  41185. }
  41186. else {
  41187. facet = quad.facet2;
  41188. }
  41189. return facet;
  41190. };
  41191. // Creates and populates the heightMap array with "facet" elements :
  41192. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  41193. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  41194. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  41195. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  41196. // Returns the GroundMesh.
  41197. GroundMesh.prototype._initHeightQuads = function () {
  41198. var subdivisionsX = this._subdivisionsX;
  41199. var subdivisionsY = this._subdivisionsY;
  41200. this._heightQuads = new Array();
  41201. for (var row = 0; row < subdivisionsY; row++) {
  41202. for (var col = 0; col < subdivisionsX; col++) {
  41203. 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) };
  41204. this._heightQuads[row * subdivisionsX + col] = quad;
  41205. }
  41206. }
  41207. return this;
  41208. };
  41209. // Compute each quad element values and update the the heightMap array :
  41210. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  41211. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  41212. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  41213. // Returns the GroundMesh.
  41214. GroundMesh.prototype._computeHeightQuads = function () {
  41215. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41216. var v1 = BABYLON.Tmp.Vector3[3];
  41217. var v2 = BABYLON.Tmp.Vector3[2];
  41218. var v3 = BABYLON.Tmp.Vector3[1];
  41219. var v4 = BABYLON.Tmp.Vector3[0];
  41220. var v1v2 = BABYLON.Tmp.Vector3[4];
  41221. var v1v3 = BABYLON.Tmp.Vector3[5];
  41222. var v1v4 = BABYLON.Tmp.Vector3[6];
  41223. var norm1 = BABYLON.Tmp.Vector3[7];
  41224. var norm2 = BABYLON.Tmp.Vector3[8];
  41225. var i = 0;
  41226. var j = 0;
  41227. var k = 0;
  41228. var cd = 0; // 2D slope coefficient : z = cd * x + h
  41229. var h = 0;
  41230. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  41231. var d2 = 0;
  41232. var subdivisionsX = this._subdivisionsX;
  41233. var subdivisionsY = this._subdivisionsY;
  41234. for (var row = 0; row < subdivisionsY; row++) {
  41235. for (var col = 0; col < subdivisionsX; col++) {
  41236. i = col * 3;
  41237. j = row * (subdivisionsX + 1) * 3;
  41238. k = (row + 1) * (subdivisionsX + 1) * 3;
  41239. v1.x = positions[j + i];
  41240. v1.y = positions[j + i + 1];
  41241. v1.z = positions[j + i + 2];
  41242. v2.x = positions[j + i + 3];
  41243. v2.y = positions[j + i + 4];
  41244. v2.z = positions[j + i + 5];
  41245. v3.x = positions[k + i];
  41246. v3.y = positions[k + i + 1];
  41247. v3.z = positions[k + i + 2];
  41248. v4.x = positions[k + i + 3];
  41249. v4.y = positions[k + i + 4];
  41250. v4.z = positions[k + i + 5];
  41251. // 2D slope V1V4
  41252. cd = (v4.z - v1.z) / (v4.x - v1.x);
  41253. h = v1.z - cd * v1.x; // v1 belongs to the slope
  41254. // facet equations :
  41255. // we compute each facet normal vector
  41256. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  41257. // we compute the value d by applying the equation to v1 which belongs to the plane
  41258. // then we store the facet equation in a Vector4
  41259. v2.subtractToRef(v1, v1v2);
  41260. v3.subtractToRef(v1, v1v3);
  41261. v4.subtractToRef(v1, v1v4);
  41262. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  41263. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  41264. norm1.normalize();
  41265. norm2.normalize();
  41266. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  41267. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  41268. var quad = this._heightQuads[row * subdivisionsX + col];
  41269. quad.slope.copyFromFloats(cd, h);
  41270. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  41271. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  41272. }
  41273. }
  41274. return this;
  41275. };
  41276. GroundMesh.prototype.serialize = function (serializationObject) {
  41277. _super.prototype.serialize.call(this, serializationObject);
  41278. serializationObject.subdivisionsX = this._subdivisionsX;
  41279. serializationObject.subdivisionsY = this._subdivisionsY;
  41280. serializationObject.minX = this._minX;
  41281. serializationObject.maxX = this._maxX;
  41282. serializationObject.minZ = this._minZ;
  41283. serializationObject.maxZ = this._maxZ;
  41284. serializationObject.width = this._width;
  41285. serializationObject.height = this._height;
  41286. };
  41287. GroundMesh.Parse = function (parsedMesh, scene) {
  41288. var result = new GroundMesh(parsedMesh.name, scene);
  41289. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  41290. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  41291. result._minX = parsedMesh.minX;
  41292. result._maxX = parsedMesh.maxX;
  41293. result._minZ = parsedMesh.minZ;
  41294. result._maxZ = parsedMesh.maxZ;
  41295. result._width = parsedMesh.width;
  41296. result._height = parsedMesh.height;
  41297. return result;
  41298. };
  41299. return GroundMesh;
  41300. }(BABYLON.Mesh));
  41301. BABYLON.GroundMesh = GroundMesh;
  41302. })(BABYLON || (BABYLON = {}));
  41303. //# sourceMappingURL=babylon.groundMesh.js.map
  41304. var BABYLON;
  41305. (function (BABYLON) {
  41306. /**
  41307. * Creates an instance based on a source mesh.
  41308. */
  41309. var InstancedMesh = (function (_super) {
  41310. __extends(InstancedMesh, _super);
  41311. function InstancedMesh(name, source) {
  41312. var _this = _super.call(this, name, source.getScene()) || this;
  41313. source.instances.push(_this);
  41314. _this._sourceMesh = source;
  41315. _this.position.copyFrom(source.position);
  41316. _this.rotation.copyFrom(source.rotation);
  41317. _this.scaling.copyFrom(source.scaling);
  41318. if (source.rotationQuaternion) {
  41319. _this.rotationQuaternion = source.rotationQuaternion.clone();
  41320. }
  41321. _this.infiniteDistance = source.infiniteDistance;
  41322. _this.setPivotMatrix(source.getPivotMatrix());
  41323. _this.refreshBoundingInfo();
  41324. _this._syncSubMeshes();
  41325. return _this;
  41326. }
  41327. /**
  41328. * Returns the string "InstancedMesh".
  41329. */
  41330. InstancedMesh.prototype.getClassName = function () {
  41331. return "InstancedMesh";
  41332. };
  41333. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  41334. // Methods
  41335. get: function () {
  41336. return this._sourceMesh.receiveShadows;
  41337. },
  41338. enumerable: true,
  41339. configurable: true
  41340. });
  41341. Object.defineProperty(InstancedMesh.prototype, "material", {
  41342. get: function () {
  41343. return this._sourceMesh.material;
  41344. },
  41345. enumerable: true,
  41346. configurable: true
  41347. });
  41348. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  41349. get: function () {
  41350. return this._sourceMesh.visibility;
  41351. },
  41352. enumerable: true,
  41353. configurable: true
  41354. });
  41355. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  41356. get: function () {
  41357. return this._sourceMesh.skeleton;
  41358. },
  41359. enumerable: true,
  41360. configurable: true
  41361. });
  41362. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  41363. get: function () {
  41364. return this._sourceMesh.renderingGroupId;
  41365. },
  41366. enumerable: true,
  41367. configurable: true
  41368. });
  41369. /**
  41370. * Returns the total number of vertices (integer).
  41371. */
  41372. InstancedMesh.prototype.getTotalVertices = function () {
  41373. return this._sourceMesh.getTotalVertices();
  41374. };
  41375. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  41376. get: function () {
  41377. return this._sourceMesh;
  41378. },
  41379. enumerable: true,
  41380. configurable: true
  41381. });
  41382. /**
  41383. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  41384. */
  41385. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  41386. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  41387. };
  41388. /**
  41389. * Sets the vertex data of the mesh geometry for the requested `kind`.
  41390. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  41391. * The `data` are either a numeric array either a Float32Array.
  41392. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  41393. * 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).
  41394. * Note that a new underlying VertexBuffer object is created each call.
  41395. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  41396. *
  41397. * Possible `kind` values :
  41398. * - BABYLON.VertexBuffer.PositionKind
  41399. * - BABYLON.VertexBuffer.UVKind
  41400. * - BABYLON.VertexBuffer.UV2Kind
  41401. * - BABYLON.VertexBuffer.UV3Kind
  41402. * - BABYLON.VertexBuffer.UV4Kind
  41403. * - BABYLON.VertexBuffer.UV5Kind
  41404. * - BABYLON.VertexBuffer.UV6Kind
  41405. * - BABYLON.VertexBuffer.ColorKind
  41406. * - BABYLON.VertexBuffer.MatricesIndicesKind
  41407. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  41408. * - BABYLON.VertexBuffer.MatricesWeightsKind
  41409. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  41410. *
  41411. * Returns the Mesh.
  41412. */
  41413. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  41414. if (this.sourceMesh) {
  41415. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  41416. }
  41417. return this.sourceMesh;
  41418. };
  41419. /**
  41420. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  41421. * If the mesh has no geometry, it is simply returned as it is.
  41422. * The `data` are either a numeric array either a Float32Array.
  41423. * No new underlying VertexBuffer object is created.
  41424. * 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.
  41425. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  41426. *
  41427. * Possible `kind` values :
  41428. * - BABYLON.VertexBuffer.PositionKind
  41429. * - BABYLON.VertexBuffer.UVKind
  41430. * - BABYLON.VertexBuffer.UV2Kind
  41431. * - BABYLON.VertexBuffer.UV3Kind
  41432. * - BABYLON.VertexBuffer.UV4Kind
  41433. * - BABYLON.VertexBuffer.UV5Kind
  41434. * - BABYLON.VertexBuffer.UV6Kind
  41435. * - BABYLON.VertexBuffer.ColorKind
  41436. * - BABYLON.VertexBuffer.MatricesIndicesKind
  41437. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  41438. * - BABYLON.VertexBuffer.MatricesWeightsKind
  41439. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  41440. *
  41441. * Returns the Mesh.
  41442. */
  41443. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  41444. if (this.sourceMesh) {
  41445. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  41446. }
  41447. return this.sourceMesh;
  41448. };
  41449. /**
  41450. * Sets the mesh indices.
  41451. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  41452. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  41453. * This method creates a new index buffer each call.
  41454. * Returns the Mesh.
  41455. */
  41456. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  41457. if (this.sourceMesh) {
  41458. this.sourceMesh.setIndices(indices, totalVertices);
  41459. }
  41460. return this.sourceMesh;
  41461. };
  41462. /**
  41463. * Boolean : True if the mesh owns the requested kind of data.
  41464. */
  41465. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  41466. return this._sourceMesh.isVerticesDataPresent(kind);
  41467. };
  41468. /**
  41469. * Returns an array of indices (IndicesArray).
  41470. */
  41471. InstancedMesh.prototype.getIndices = function () {
  41472. return this._sourceMesh.getIndices();
  41473. };
  41474. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  41475. get: function () {
  41476. return this._sourceMesh._positions;
  41477. },
  41478. enumerable: true,
  41479. configurable: true
  41480. });
  41481. /**
  41482. * Sets a new updated BoundingInfo to the mesh.
  41483. * Returns the mesh.
  41484. */
  41485. InstancedMesh.prototype.refreshBoundingInfo = function () {
  41486. var meshBB = this._sourceMesh.getBoundingInfo();
  41487. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  41488. this._updateBoundingInfo();
  41489. return this;
  41490. };
  41491. InstancedMesh.prototype._preActivate = function () {
  41492. if (this._currentLOD) {
  41493. this._currentLOD._preActivate();
  41494. }
  41495. return this;
  41496. };
  41497. InstancedMesh.prototype._activate = function (renderId) {
  41498. if (this._currentLOD) {
  41499. this._currentLOD._registerInstanceForRenderId(this, renderId);
  41500. }
  41501. return this;
  41502. };
  41503. /**
  41504. * Returns the current associated LOD AbstractMesh.
  41505. */
  41506. InstancedMesh.prototype.getLOD = function (camera) {
  41507. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  41508. if (this._currentLOD === this.sourceMesh) {
  41509. return this;
  41510. }
  41511. return this._currentLOD;
  41512. };
  41513. InstancedMesh.prototype._syncSubMeshes = function () {
  41514. this.releaseSubMeshes();
  41515. if (this._sourceMesh.subMeshes) {
  41516. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  41517. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  41518. }
  41519. }
  41520. return this;
  41521. };
  41522. InstancedMesh.prototype._generatePointsArray = function () {
  41523. return this._sourceMesh._generatePointsArray();
  41524. };
  41525. /**
  41526. * Creates a new InstancedMesh from the current mesh.
  41527. * - name (string) : the cloned mesh name
  41528. * - newParent (optional Node) : the optional Node to parent the clone to.
  41529. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  41530. *
  41531. * Returns the clone.
  41532. */
  41533. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  41534. var result = this._sourceMesh.createInstance(name);
  41535. // Deep copy
  41536. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  41537. // Bounding info
  41538. this.refreshBoundingInfo();
  41539. // Parent
  41540. if (newParent) {
  41541. result.parent = newParent;
  41542. }
  41543. if (!doNotCloneChildren) {
  41544. // Children
  41545. for (var index = 0; index < this.getScene().meshes.length; index++) {
  41546. var mesh = this.getScene().meshes[index];
  41547. if (mesh.parent === this) {
  41548. mesh.clone(mesh.name, result);
  41549. }
  41550. }
  41551. }
  41552. result.computeWorldMatrix(true);
  41553. return result;
  41554. };
  41555. /**
  41556. * Disposes the InstancedMesh.
  41557. * Returns nothing.
  41558. */
  41559. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  41560. // Remove from mesh
  41561. var index = this._sourceMesh.instances.indexOf(this);
  41562. this._sourceMesh.instances.splice(index, 1);
  41563. _super.prototype.dispose.call(this, doNotRecurse);
  41564. };
  41565. return InstancedMesh;
  41566. }(BABYLON.AbstractMesh));
  41567. BABYLON.InstancedMesh = InstancedMesh;
  41568. })(BABYLON || (BABYLON = {}));
  41569. //# sourceMappingURL=babylon.instancedMesh.js.map
  41570. /// <reference path="babylon.mesh.ts" />
  41571. var BABYLON;
  41572. (function (BABYLON) {
  41573. var LinesMesh = (function (_super) {
  41574. __extends(LinesMesh, _super);
  41575. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  41576. if (parent === void 0) { parent = null; }
  41577. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  41578. _this.useVertexColor = useVertexColor;
  41579. _this.color = new BABYLON.Color3(1, 1, 1);
  41580. _this.alpha = 1;
  41581. if (source) {
  41582. _this.color = source.color.clone();
  41583. _this.alpha = source.alpha;
  41584. _this.useVertexColor = source.useVertexColor;
  41585. }
  41586. _this._intersectionThreshold = 0.1;
  41587. var options = {
  41588. attributes: [BABYLON.VertexBuffer.PositionKind],
  41589. uniforms: ["world", "viewProjection"],
  41590. needAlphaBlending: false,
  41591. };
  41592. if (!useVertexColor) {
  41593. options.uniforms.push("color");
  41594. options.needAlphaBlending = true;
  41595. }
  41596. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  41597. return _this;
  41598. }
  41599. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  41600. /**
  41601. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  41602. * This margin is expressed in world space coordinates, so its value may vary.
  41603. * Default value is 0.1
  41604. * @returns the intersection Threshold value.
  41605. */
  41606. get: function () {
  41607. return this._intersectionThreshold;
  41608. },
  41609. /**
  41610. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  41611. * This margin is expressed in world space coordinates, so its value may vary.
  41612. * @param value the new threshold to apply
  41613. */
  41614. set: function (value) {
  41615. if (this._intersectionThreshold === value) {
  41616. return;
  41617. }
  41618. this._intersectionThreshold = value;
  41619. if (this.geometry) {
  41620. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  41621. }
  41622. },
  41623. enumerable: true,
  41624. configurable: true
  41625. });
  41626. /**
  41627. * Returns the string "LineMesh"
  41628. */
  41629. LinesMesh.prototype.getClassName = function () {
  41630. return "LinesMesh";
  41631. };
  41632. Object.defineProperty(LinesMesh.prototype, "material", {
  41633. get: function () {
  41634. return this._colorShader;
  41635. },
  41636. enumerable: true,
  41637. configurable: true
  41638. });
  41639. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  41640. get: function () {
  41641. return false;
  41642. },
  41643. enumerable: true,
  41644. configurable: true
  41645. });
  41646. LinesMesh.prototype.createInstance = function (name) {
  41647. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  41648. return null;
  41649. };
  41650. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  41651. // VBOs
  41652. this._geometry._bind(this._colorShader.getEffect());
  41653. // Color
  41654. if (!this.useVertexColor) {
  41655. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  41656. }
  41657. return this;
  41658. };
  41659. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  41660. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  41661. return this;
  41662. }
  41663. var engine = this.getScene().getEngine();
  41664. // Draw order
  41665. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  41666. return this;
  41667. };
  41668. LinesMesh.prototype.dispose = function (doNotRecurse) {
  41669. this._colorShader.dispose();
  41670. _super.prototype.dispose.call(this, doNotRecurse);
  41671. };
  41672. /**
  41673. * Returns a new LineMesh object cloned from the current one.
  41674. */
  41675. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  41676. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  41677. };
  41678. return LinesMesh;
  41679. }(BABYLON.Mesh));
  41680. BABYLON.LinesMesh = LinesMesh;
  41681. })(BABYLON || (BABYLON = {}));
  41682. //# sourceMappingURL=babylon.linesMesh.js.map
  41683. var BABYLON;
  41684. (function (BABYLON) {
  41685. var ShaderMaterial = (function (_super) {
  41686. __extends(ShaderMaterial, _super);
  41687. function ShaderMaterial(name, scene, shaderPath, options) {
  41688. var _this = _super.call(this, name, scene) || this;
  41689. _this._textures = {};
  41690. _this._textureArrays = {};
  41691. _this._floats = {};
  41692. _this._floatsArrays = {};
  41693. _this._colors3 = {};
  41694. _this._colors3Arrays = {};
  41695. _this._colors4 = {};
  41696. _this._vectors2 = {};
  41697. _this._vectors3 = {};
  41698. _this._vectors4 = {};
  41699. _this._matrices = {};
  41700. _this._matrices3x3 = {};
  41701. _this._matrices2x2 = {};
  41702. _this._vectors3Arrays = {};
  41703. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  41704. _this._shaderPath = shaderPath;
  41705. options.needAlphaBlending = options.needAlphaBlending || false;
  41706. options.needAlphaTesting = options.needAlphaTesting || false;
  41707. options.attributes = options.attributes || ["position", "normal", "uv"];
  41708. options.uniforms = options.uniforms || ["worldViewProjection"];
  41709. options.uniformBuffers = options.uniformBuffers || [];
  41710. options.samplers = options.samplers || [];
  41711. options.defines = options.defines || [];
  41712. _this._options = options;
  41713. return _this;
  41714. }
  41715. ShaderMaterial.prototype.getClassName = function () {
  41716. return "ShaderMaterial";
  41717. };
  41718. ShaderMaterial.prototype.needAlphaBlending = function () {
  41719. return this._options.needAlphaBlending;
  41720. };
  41721. ShaderMaterial.prototype.needAlphaTesting = function () {
  41722. return this._options.needAlphaTesting;
  41723. };
  41724. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  41725. if (this._options.uniforms.indexOf(uniformName) === -1) {
  41726. this._options.uniforms.push(uniformName);
  41727. }
  41728. };
  41729. ShaderMaterial.prototype.setTexture = function (name, texture) {
  41730. if (this._options.samplers.indexOf(name) === -1) {
  41731. this._options.samplers.push(name);
  41732. }
  41733. this._textures[name] = texture;
  41734. return this;
  41735. };
  41736. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  41737. if (this._options.samplers.indexOf(name) === -1) {
  41738. this._options.samplers.push(name);
  41739. }
  41740. this._checkUniform(name);
  41741. this._textureArrays[name] = textures;
  41742. return this;
  41743. };
  41744. ShaderMaterial.prototype.setFloat = function (name, value) {
  41745. this._checkUniform(name);
  41746. this._floats[name] = value;
  41747. return this;
  41748. };
  41749. ShaderMaterial.prototype.setFloats = function (name, value) {
  41750. this._checkUniform(name);
  41751. this._floatsArrays[name] = value;
  41752. return this;
  41753. };
  41754. ShaderMaterial.prototype.setColor3 = function (name, value) {
  41755. this._checkUniform(name);
  41756. this._colors3[name] = value;
  41757. return this;
  41758. };
  41759. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  41760. this._checkUniform(name);
  41761. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  41762. color.toArray(arr, arr.length);
  41763. return arr;
  41764. }, []);
  41765. return this;
  41766. };
  41767. ShaderMaterial.prototype.setColor4 = function (name, value) {
  41768. this._checkUniform(name);
  41769. this._colors4[name] = value;
  41770. return this;
  41771. };
  41772. ShaderMaterial.prototype.setVector2 = function (name, value) {
  41773. this._checkUniform(name);
  41774. this._vectors2[name] = value;
  41775. return this;
  41776. };
  41777. ShaderMaterial.prototype.setVector3 = function (name, value) {
  41778. this._checkUniform(name);
  41779. this._vectors3[name] = value;
  41780. return this;
  41781. };
  41782. ShaderMaterial.prototype.setVector4 = function (name, value) {
  41783. this._checkUniform(name);
  41784. this._vectors4[name] = value;
  41785. return this;
  41786. };
  41787. ShaderMaterial.prototype.setMatrix = function (name, value) {
  41788. this._checkUniform(name);
  41789. this._matrices[name] = value;
  41790. return this;
  41791. };
  41792. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  41793. this._checkUniform(name);
  41794. this._matrices3x3[name] = value;
  41795. return this;
  41796. };
  41797. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  41798. this._checkUniform(name);
  41799. this._matrices2x2[name] = value;
  41800. return this;
  41801. };
  41802. ShaderMaterial.prototype.setArray3 = function (name, value) {
  41803. this._checkUniform(name);
  41804. this._vectors3Arrays[name] = value;
  41805. return this;
  41806. };
  41807. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  41808. if (!mesh) {
  41809. return true;
  41810. }
  41811. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  41812. return false;
  41813. }
  41814. return false;
  41815. };
  41816. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  41817. var scene = this.getScene();
  41818. var engine = scene.getEngine();
  41819. if (!this.checkReadyOnEveryCall) {
  41820. if (this._renderId === scene.getRenderId()) {
  41821. if (this._checkCache(scene, mesh, useInstances)) {
  41822. return true;
  41823. }
  41824. }
  41825. }
  41826. // Instances
  41827. var defines = [];
  41828. var attribs = [];
  41829. var fallbacks = new BABYLON.EffectFallbacks();
  41830. if (useInstances) {
  41831. defines.push("#define INSTANCES");
  41832. }
  41833. for (var index = 0; index < this._options.defines.length; index++) {
  41834. defines.push(this._options.defines[index]);
  41835. }
  41836. for (var index = 0; index < this._options.attributes.length; index++) {
  41837. attribs.push(this._options.attributes[index]);
  41838. }
  41839. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  41840. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41841. defines.push("#define VERTEXCOLOR");
  41842. }
  41843. // Bones
  41844. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  41845. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41846. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41847. if (mesh.numBoneInfluencers > 4) {
  41848. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41849. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41850. }
  41851. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  41852. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  41853. fallbacks.addCPUSkinningFallback(0, mesh);
  41854. if (this._options.uniforms.indexOf("mBones") === -1) {
  41855. this._options.uniforms.push("mBones");
  41856. }
  41857. }
  41858. else {
  41859. defines.push("#define NUM_BONE_INFLUENCERS 0");
  41860. }
  41861. // Textures
  41862. for (var name in this._textures) {
  41863. if (!this._textures[name].isReady()) {
  41864. return false;
  41865. }
  41866. }
  41867. // Alpha test
  41868. if (engine.getAlphaTesting()) {
  41869. defines.push("#define ALPHATEST");
  41870. }
  41871. var previousEffect = this._effect;
  41872. var join = defines.join("\n");
  41873. this._effect = engine.createEffect(this._shaderPath, {
  41874. attributes: attribs,
  41875. uniformsNames: this._options.uniforms,
  41876. uniformBuffersNames: this._options.uniformBuffers,
  41877. samplers: this._options.samplers,
  41878. defines: join,
  41879. fallbacks: fallbacks,
  41880. onCompiled: this.onCompiled,
  41881. onError: this.onError
  41882. }, engine);
  41883. if (!this._effect.isReady()) {
  41884. return false;
  41885. }
  41886. if (previousEffect !== this._effect) {
  41887. scene.resetCachedMaterial();
  41888. }
  41889. this._renderId = scene.getRenderId();
  41890. return true;
  41891. };
  41892. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41893. var scene = this.getScene();
  41894. if (this._options.uniforms.indexOf("world") !== -1) {
  41895. this._effect.setMatrix("world", world);
  41896. }
  41897. if (this._options.uniforms.indexOf("worldView") !== -1) {
  41898. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  41899. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  41900. }
  41901. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  41902. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  41903. }
  41904. };
  41905. ShaderMaterial.prototype.bind = function (world, mesh) {
  41906. // Std values
  41907. this.bindOnlyWorldMatrix(world);
  41908. if (this.getScene().getCachedMaterial() !== this) {
  41909. if (this._options.uniforms.indexOf("view") !== -1) {
  41910. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  41911. }
  41912. if (this._options.uniforms.indexOf("projection") !== -1) {
  41913. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  41914. }
  41915. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  41916. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  41917. }
  41918. // Bones
  41919. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  41920. var name;
  41921. // Texture
  41922. for (name in this._textures) {
  41923. this._effect.setTexture(name, this._textures[name]);
  41924. }
  41925. // Texture arrays
  41926. for (name in this._textureArrays) {
  41927. this._effect.setTextureArray(name, this._textureArrays[name]);
  41928. }
  41929. // Float
  41930. for (name in this._floats) {
  41931. this._effect.setFloat(name, this._floats[name]);
  41932. }
  41933. // Float s
  41934. for (name in this._floatsArrays) {
  41935. this._effect.setArray(name, this._floatsArrays[name]);
  41936. }
  41937. // Color3
  41938. for (name in this._colors3) {
  41939. this._effect.setColor3(name, this._colors3[name]);
  41940. }
  41941. for (name in this._colors3Arrays) {
  41942. this._effect.setArray3(name, this._colors3Arrays[name]);
  41943. }
  41944. // Color4
  41945. for (name in this._colors4) {
  41946. var color = this._colors4[name];
  41947. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  41948. }
  41949. // Vector2
  41950. for (name in this._vectors2) {
  41951. this._effect.setVector2(name, this._vectors2[name]);
  41952. }
  41953. // Vector3
  41954. for (name in this._vectors3) {
  41955. this._effect.setVector3(name, this._vectors3[name]);
  41956. }
  41957. // Vector4
  41958. for (name in this._vectors4) {
  41959. this._effect.setVector4(name, this._vectors4[name]);
  41960. }
  41961. // Matrix
  41962. for (name in this._matrices) {
  41963. this._effect.setMatrix(name, this._matrices[name]);
  41964. }
  41965. // Matrix 3x3
  41966. for (name in this._matrices3x3) {
  41967. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  41968. }
  41969. // Matrix 2x2
  41970. for (name in this._matrices2x2) {
  41971. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  41972. }
  41973. // Vector3Array
  41974. for (name in this._vectors3Arrays) {
  41975. this._effect.setArray3(name, this._vectors3Arrays[name]);
  41976. }
  41977. }
  41978. this._afterBind(mesh);
  41979. };
  41980. ShaderMaterial.prototype.getActiveTextures = function () {
  41981. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41982. for (var name in this._textures) {
  41983. activeTextures.push(this._textures[name]);
  41984. }
  41985. for (var name in this._textureArrays) {
  41986. var array = this._textureArrays[name];
  41987. for (var index = 0; index < array.length; index++) {
  41988. activeTextures.push(array[index]);
  41989. }
  41990. }
  41991. return activeTextures;
  41992. };
  41993. ShaderMaterial.prototype.hasTexture = function (texture) {
  41994. if (_super.prototype.hasTexture.call(this, texture)) {
  41995. return true;
  41996. }
  41997. for (var name in this._textures) {
  41998. if (this._textures[name] === texture) {
  41999. return true;
  42000. }
  42001. }
  42002. for (var name in this._textureArrays) {
  42003. var array = this._textureArrays[name];
  42004. for (var index = 0; index < array.length; index++) {
  42005. if (array[index] === texture) {
  42006. return true;
  42007. }
  42008. }
  42009. }
  42010. return false;
  42011. };
  42012. ShaderMaterial.prototype.clone = function (name) {
  42013. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  42014. return newShaderMaterial;
  42015. };
  42016. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42017. if (forceDisposeTextures) {
  42018. var name;
  42019. for (name in this._textures) {
  42020. this._textures[name].dispose();
  42021. }
  42022. for (name in this._textureArrays) {
  42023. var array = this._textureArrays[name];
  42024. for (var index = 0; index < array.length; index++) {
  42025. array[index].dispose();
  42026. }
  42027. }
  42028. }
  42029. this._textures = {};
  42030. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42031. };
  42032. ShaderMaterial.prototype.serialize = function () {
  42033. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42034. serializationObject.customType = "BABYLON.ShaderMaterial";
  42035. serializationObject.options = this._options;
  42036. serializationObject.shaderPath = this._shaderPath;
  42037. var name;
  42038. // Texture
  42039. serializationObject.textures = {};
  42040. for (name in this._textures) {
  42041. serializationObject.textures[name] = this._textures[name].serialize();
  42042. }
  42043. // Texture arrays
  42044. serializationObject.textureArrays = {};
  42045. for (name in this._textureArrays) {
  42046. serializationObject.textureArrays[name] = [];
  42047. var array = this._textureArrays[name];
  42048. for (var index = 0; index < array.length; index++) {
  42049. serializationObject.textureArrays[name].push(array[index].serialize());
  42050. }
  42051. }
  42052. // Float
  42053. serializationObject.floats = {};
  42054. for (name in this._floats) {
  42055. serializationObject.floats[name] = this._floats[name];
  42056. }
  42057. // Float s
  42058. serializationObject.floatArrays = {};
  42059. for (name in this._floatsArrays) {
  42060. serializationObject.floatArrays[name] = this._floatsArrays[name];
  42061. }
  42062. // Color3
  42063. serializationObject.colors3 = {};
  42064. for (name in this._colors3) {
  42065. serializationObject.colors3[name] = this._colors3[name].asArray();
  42066. }
  42067. // Color3 array
  42068. serializationObject.colors3Arrays = {};
  42069. for (name in this._colors3Arrays) {
  42070. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  42071. }
  42072. // Color4
  42073. serializationObject.colors4 = {};
  42074. for (name in this._colors4) {
  42075. serializationObject.colors4[name] = this._colors4[name].asArray();
  42076. }
  42077. // Vector2
  42078. serializationObject.vectors2 = {};
  42079. for (name in this._vectors2) {
  42080. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  42081. }
  42082. // Vector3
  42083. serializationObject.vectors3 = {};
  42084. for (name in this._vectors3) {
  42085. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  42086. }
  42087. // Vector4
  42088. serializationObject.vectors4 = {};
  42089. for (name in this._vectors4) {
  42090. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  42091. }
  42092. // Matrix
  42093. serializationObject.matrices = {};
  42094. for (name in this._matrices) {
  42095. serializationObject.matrices[name] = this._matrices[name].asArray();
  42096. }
  42097. // Matrix 3x3
  42098. serializationObject.matrices3x3 = {};
  42099. for (name in this._matrices3x3) {
  42100. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  42101. }
  42102. // Matrix 2x2
  42103. serializationObject.matrices2x2 = {};
  42104. for (name in this._matrices2x2) {
  42105. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  42106. }
  42107. // Vector3Array
  42108. serializationObject.vectors3Arrays = {};
  42109. for (name in this._vectors3Arrays) {
  42110. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  42111. }
  42112. return serializationObject;
  42113. };
  42114. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  42115. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  42116. var name;
  42117. // Texture
  42118. for (name in source.textures) {
  42119. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  42120. }
  42121. // Texture arrays
  42122. for (name in source.textureArrays) {
  42123. var array = source.textureArrays[name];
  42124. var textureArray = new Array();
  42125. for (var index = 0; index < array.length; index++) {
  42126. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  42127. }
  42128. material.setTextureArray(name, textureArray);
  42129. }
  42130. // Float
  42131. for (name in source.floats) {
  42132. material.setFloat(name, source.floats[name]);
  42133. }
  42134. // Float s
  42135. for (name in source.floatsArrays) {
  42136. material.setFloats(name, source.floatsArrays[name]);
  42137. }
  42138. // Color3
  42139. for (name in source.colors3) {
  42140. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  42141. }
  42142. // Color3 arrays
  42143. for (name in source.colors3Arrays) {
  42144. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  42145. if (i % 3 === 0) {
  42146. arr.push([num]);
  42147. }
  42148. else {
  42149. arr[arr.length - 1].push(num);
  42150. }
  42151. return arr;
  42152. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  42153. material.setColor3Array(name, colors);
  42154. }
  42155. // Color4
  42156. for (name in source.colors4) {
  42157. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  42158. }
  42159. // Vector2
  42160. for (name in source.vectors2) {
  42161. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  42162. }
  42163. // Vector3
  42164. for (name in source.vectors3) {
  42165. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  42166. }
  42167. // Vector4
  42168. for (name in source.vectors4) {
  42169. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  42170. }
  42171. // Matrix
  42172. for (name in source.matrices) {
  42173. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  42174. }
  42175. // Matrix 3x3
  42176. for (name in source.matrices3x3) {
  42177. material.setMatrix3x3(name, source.matrices3x3[name]);
  42178. }
  42179. // Matrix 2x2
  42180. for (name in source.matrices2x2) {
  42181. material.setMatrix2x2(name, source.matrices2x2[name]);
  42182. }
  42183. // Vector3Array
  42184. for (name in source.vectors3Arrays) {
  42185. material.setArray3(name, source.vectors3Arrays[name]);
  42186. }
  42187. return material;
  42188. };
  42189. return ShaderMaterial;
  42190. }(BABYLON.Material));
  42191. BABYLON.ShaderMaterial = ShaderMaterial;
  42192. })(BABYLON || (BABYLON = {}));
  42193. //# sourceMappingURL=babylon.shaderMaterial.js.map
  42194. var BABYLON;
  42195. (function (BABYLON) {
  42196. var MeshBuilder = (function () {
  42197. function MeshBuilder() {
  42198. }
  42199. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  42200. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  42201. return BABYLON.Mesh.DOUBLESIDE;
  42202. }
  42203. if (orientation === undefined || orientation === null) {
  42204. return BABYLON.Mesh.FRONTSIDE;
  42205. }
  42206. return orientation;
  42207. };
  42208. /**
  42209. * Creates a box mesh.
  42210. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  42211. * The parameter `size` sets the size (float) of each box side (default 1).
  42212. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  42213. * 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).
  42214. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  42215. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42216. * 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).
  42217. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42218. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42219. */
  42220. MeshBuilder.CreateBox = function (name, options, scene) {
  42221. var box = new BABYLON.Mesh(name, scene);
  42222. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42223. box.sideOrientation = options.sideOrientation;
  42224. var vertexData = BABYLON.VertexData.CreateBox(options);
  42225. vertexData.applyToMesh(box, options.updatable);
  42226. return box;
  42227. };
  42228. /**
  42229. * Creates a sphere mesh.
  42230. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  42231. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  42232. * 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`).
  42233. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  42234. * 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
  42235. * 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).
  42236. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42237. * 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).
  42238. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42239. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42240. */
  42241. MeshBuilder.CreateSphere = function (name, options, scene) {
  42242. var sphere = new BABYLON.Mesh(name, scene);
  42243. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42244. sphere.sideOrientation = options.sideOrientation;
  42245. var vertexData = BABYLON.VertexData.CreateSphere(options);
  42246. vertexData.applyToMesh(sphere, options.updatable);
  42247. return sphere;
  42248. };
  42249. /**
  42250. * Creates a plane polygonal mesh. By default, this is a disc.
  42251. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  42252. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  42253. * 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.
  42254. * 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
  42255. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42256. * 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).
  42257. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42258. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42259. */
  42260. MeshBuilder.CreateDisc = function (name, options, scene) {
  42261. var disc = new BABYLON.Mesh(name, scene);
  42262. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42263. disc.sideOrientation = options.sideOrientation;
  42264. var vertexData = BABYLON.VertexData.CreateDisc(options);
  42265. vertexData.applyToMesh(disc, options.updatable);
  42266. return disc;
  42267. };
  42268. /**
  42269. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  42270. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  42271. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  42272. * 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`).
  42273. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  42274. * 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.
  42275. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42276. * 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).
  42277. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42278. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42279. */
  42280. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  42281. var sphere = new BABYLON.Mesh(name, scene);
  42282. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42283. sphere.sideOrientation = options.sideOrientation;
  42284. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  42285. vertexData.applyToMesh(sphere, options.updatable);
  42286. return sphere;
  42287. };
  42288. ;
  42289. /**
  42290. * Creates a ribbon mesh.
  42291. * 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.
  42292. *
  42293. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  42294. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  42295. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  42296. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  42297. * 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.
  42298. * 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.
  42299. * 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
  42300. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42301. * 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).
  42302. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42303. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  42304. * 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.
  42305. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  42306. * 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
  42307. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  42308. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  42309. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42310. */
  42311. MeshBuilder.CreateRibbon = function (name, options, scene) {
  42312. var pathArray = options.pathArray;
  42313. var closeArray = options.closeArray;
  42314. var closePath = options.closePath;
  42315. var offset = options.offset;
  42316. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42317. var instance = options.instance;
  42318. var updatable = options.updatable;
  42319. if (instance) {
  42320. // positionFunction : ribbon case
  42321. // only pathArray and sideOrientation parameters are taken into account for positions update
  42322. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  42323. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  42324. var positionFunction = function (positions) {
  42325. var minlg = pathArray[0].length;
  42326. var i = 0;
  42327. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  42328. for (var si = 1; si <= ns; si++) {
  42329. for (var p = 0; p < pathArray.length; p++) {
  42330. var path = pathArray[p];
  42331. var l = path.length;
  42332. minlg = (minlg < l) ? minlg : l;
  42333. var j = 0;
  42334. while (j < minlg) {
  42335. positions[i] = path[j].x;
  42336. positions[i + 1] = path[j].y;
  42337. positions[i + 2] = path[j].z;
  42338. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  42339. BABYLON.Tmp.Vector3[0].x = path[j].x;
  42340. }
  42341. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  42342. BABYLON.Tmp.Vector3[1].x = path[j].x;
  42343. }
  42344. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  42345. BABYLON.Tmp.Vector3[0].y = path[j].y;
  42346. }
  42347. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  42348. BABYLON.Tmp.Vector3[1].y = path[j].y;
  42349. }
  42350. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  42351. BABYLON.Tmp.Vector3[0].z = path[j].z;
  42352. }
  42353. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  42354. BABYLON.Tmp.Vector3[1].z = path[j].z;
  42355. }
  42356. j++;
  42357. i += 3;
  42358. }
  42359. if (instance._closePath) {
  42360. positions[i] = path[0].x;
  42361. positions[i + 1] = path[0].y;
  42362. positions[i + 2] = path[0].z;
  42363. i += 3;
  42364. }
  42365. }
  42366. }
  42367. };
  42368. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42369. positionFunction(positions);
  42370. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  42371. instance._boundingInfo.update(instance._worldMatrix);
  42372. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  42373. if (options.colors) {
  42374. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  42375. for (var c = 0; c < options.colors.length; c++) {
  42376. colors[c * 4] = options.colors[c].r;
  42377. colors[c * 4 + 1] = options.colors[c].g;
  42378. colors[c * 4 + 2] = options.colors[c].b;
  42379. colors[c * 4 + 3] = options.colors[c].a;
  42380. }
  42381. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  42382. }
  42383. if (options.uvs) {
  42384. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  42385. for (var i = 0; i < options.uvs.length; i++) {
  42386. uvs[i * 2] = options.uvs[i].x;
  42387. uvs[i * 2 + 1] = options.uvs[i].y;
  42388. }
  42389. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  42390. }
  42391. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  42392. var indices = instance.getIndices();
  42393. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  42394. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  42395. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  42396. if (instance._closePath) {
  42397. var indexFirst = 0;
  42398. var indexLast = 0;
  42399. for (var p = 0; p < pathArray.length; p++) {
  42400. indexFirst = instance._idx[p] * 3;
  42401. if (p + 1 < pathArray.length) {
  42402. indexLast = (instance._idx[p + 1] - 1) * 3;
  42403. }
  42404. else {
  42405. indexLast = normals.length - 3;
  42406. }
  42407. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  42408. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  42409. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  42410. normals[indexLast] = normals[indexFirst];
  42411. normals[indexLast + 1] = normals[indexFirst + 1];
  42412. normals[indexLast + 2] = normals[indexFirst + 2];
  42413. }
  42414. }
  42415. if (!(instance.areNormalsFrozen)) {
  42416. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  42417. }
  42418. }
  42419. return instance;
  42420. }
  42421. else {
  42422. var ribbon = new BABYLON.Mesh(name, scene);
  42423. ribbon.sideOrientation = sideOrientation;
  42424. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  42425. if (closePath) {
  42426. ribbon._idx = vertexData._idx;
  42427. }
  42428. ribbon._closePath = closePath;
  42429. ribbon._closeArray = closeArray;
  42430. vertexData.applyToMesh(ribbon, updatable);
  42431. return ribbon;
  42432. }
  42433. };
  42434. /**
  42435. * Creates a cylinder or a cone mesh.
  42436. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  42437. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  42438. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  42439. * 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.
  42440. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  42441. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  42442. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  42443. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  42444. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  42445. * 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).
  42446. * 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
  42447. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  42448. * 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
  42449. * 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.
  42450. * If `enclose` is false, a ring surface is one element.
  42451. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  42452. * 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
  42453. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42454. * 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).
  42455. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42456. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42457. */
  42458. MeshBuilder.CreateCylinder = function (name, options, scene) {
  42459. var cylinder = new BABYLON.Mesh(name, scene);
  42460. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42461. cylinder.sideOrientation = options.sideOrientation;
  42462. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  42463. vertexData.applyToMesh(cylinder, options.updatable);
  42464. return cylinder;
  42465. };
  42466. /**
  42467. * Creates a torus mesh.
  42468. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  42469. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  42470. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  42471. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  42472. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42473. * 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).
  42474. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42475. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42476. */
  42477. MeshBuilder.CreateTorus = function (name, options, scene) {
  42478. var torus = new BABYLON.Mesh(name, scene);
  42479. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42480. torus.sideOrientation = options.sideOrientation;
  42481. var vertexData = BABYLON.VertexData.CreateTorus(options);
  42482. vertexData.applyToMesh(torus, options.updatable);
  42483. return torus;
  42484. };
  42485. /**
  42486. * Creates a torus knot mesh.
  42487. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  42488. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  42489. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  42490. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  42491. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  42492. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42493. * 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).
  42494. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42495. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42496. */
  42497. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  42498. var torusKnot = new BABYLON.Mesh(name, scene);
  42499. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42500. torusKnot.sideOrientation = options.sideOrientation;
  42501. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  42502. vertexData.applyToMesh(torusKnot, options.updatable);
  42503. return torusKnot;
  42504. };
  42505. /**
  42506. * Creates a line system mesh.
  42507. * A line system is a pool of many lines gathered in a single mesh.
  42508. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  42509. * 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.
  42510. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  42511. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  42512. * 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
  42513. * 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
  42514. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  42515. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42516. */
  42517. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  42518. var instance = options.instance;
  42519. var lines = options.lines;
  42520. if (instance) {
  42521. var positionFunction = function (positions) {
  42522. var i = 0;
  42523. for (var l = 0; l < lines.length; l++) {
  42524. var points = lines[l];
  42525. for (var p = 0; p < points.length; p++) {
  42526. positions[i] = points[p].x;
  42527. positions[i + 1] = points[p].y;
  42528. positions[i + 2] = points[p].z;
  42529. i += 3;
  42530. }
  42531. }
  42532. };
  42533. instance.updateMeshPositions(positionFunction, false);
  42534. return instance;
  42535. }
  42536. // line system creation
  42537. var lineSystem = new BABYLON.LinesMesh(name, scene);
  42538. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  42539. vertexData.applyToMesh(lineSystem, options.updatable);
  42540. return lineSystem;
  42541. };
  42542. /**
  42543. * Creates a line mesh.
  42544. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  42545. * 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.
  42546. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  42547. * The parameter `points` is an array successive Vector3.
  42548. * 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
  42549. * When updating an instance, remember that only point positions can change, not the number of points.
  42550. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42551. */
  42552. MeshBuilder.CreateLines = function (name, options, scene) {
  42553. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  42554. return lines;
  42555. };
  42556. /**
  42557. * Creates a dashed line mesh.
  42558. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  42559. * 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.
  42560. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  42561. * The parameter `points` is an array successive Vector3.
  42562. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  42563. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  42564. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  42565. * 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
  42566. * When updating an instance, remember that only point positions can change, not the number of points.
  42567. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42568. */
  42569. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  42570. var points = options.points;
  42571. var instance = options.instance;
  42572. var gapSize = options.gapSize;
  42573. var dashNb = options.dashNb;
  42574. var dashSize = options.dashSize;
  42575. if (instance) {
  42576. var positionFunction = function (positions) {
  42577. var curvect = BABYLON.Vector3.Zero();
  42578. var nbSeg = positions.length / 6;
  42579. var lg = 0;
  42580. var nb = 0;
  42581. var shft = 0;
  42582. var dashshft = 0;
  42583. var curshft = 0;
  42584. var p = 0;
  42585. var i = 0;
  42586. var j = 0;
  42587. for (i = 0; i < points.length - 1; i++) {
  42588. points[i + 1].subtractToRef(points[i], curvect);
  42589. lg += curvect.length();
  42590. }
  42591. shft = lg / nbSeg;
  42592. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  42593. for (i = 0; i < points.length - 1; i++) {
  42594. points[i + 1].subtractToRef(points[i], curvect);
  42595. nb = Math.floor(curvect.length() / shft);
  42596. curvect.normalize();
  42597. j = 0;
  42598. while (j < nb && p < positions.length) {
  42599. curshft = shft * j;
  42600. positions[p] = points[i].x + curshft * curvect.x;
  42601. positions[p + 1] = points[i].y + curshft * curvect.y;
  42602. positions[p + 2] = points[i].z + curshft * curvect.z;
  42603. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  42604. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  42605. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  42606. p += 6;
  42607. j++;
  42608. }
  42609. }
  42610. while (p < positions.length) {
  42611. positions[p] = points[i].x;
  42612. positions[p + 1] = points[i].y;
  42613. positions[p + 2] = points[i].z;
  42614. p += 3;
  42615. }
  42616. };
  42617. instance.updateMeshPositions(positionFunction, false);
  42618. return instance;
  42619. }
  42620. // dashed lines creation
  42621. var dashedLines = new BABYLON.LinesMesh(name, scene);
  42622. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  42623. vertexData.applyToMesh(dashedLines, options.updatable);
  42624. dashedLines.dashSize = dashSize;
  42625. dashedLines.gapSize = gapSize;
  42626. return dashedLines;
  42627. };
  42628. /**
  42629. * Creates an extruded shape mesh.
  42630. * 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.
  42631. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  42632. *
  42633. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  42634. * 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
  42635. * extruded along the Z axis.
  42636. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  42637. * 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.
  42638. * The parameter `scale` (float, default 1) is the value to scale the shape.
  42639. * 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
  42640. * 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
  42641. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  42642. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42643. * 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).
  42644. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42645. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  42646. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42647. */
  42648. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  42649. var path = options.path;
  42650. var shape = options.shape;
  42651. var scale = options.scale || 1;
  42652. var rotation = options.rotation || 0;
  42653. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  42654. var updatable = options.updatable;
  42655. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42656. var instance = options.instance;
  42657. var invertUV = options.invertUV || false;
  42658. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  42659. };
  42660. /**
  42661. * Creates an custom extruded shape mesh.
  42662. * 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.
  42663. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  42664. *
  42665. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  42666. * 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
  42667. * extruded along the Z axis.
  42668. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  42669. * 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
  42670. * and the distance of this point from the begining of the path :
  42671. * ```javascript
  42672. * var rotationFunction = function(i, distance) {
  42673. * // do things
  42674. * return rotationValue; }
  42675. * ```
  42676. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  42677. * 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
  42678. * and the distance of this point from the begining of the path :
  42679. * ```javascript
  42680. * var scaleFunction = function(i, distance) {
  42681. * // do things
  42682. * return scaleValue;}
  42683. * ```
  42684. * It must returns a float value that will be the scale value applied to the shape on each path point.
  42685. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  42686. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  42687. * 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
  42688. * 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
  42689. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  42690. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42691. * 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).
  42692. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42693. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  42694. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42695. */
  42696. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  42697. var path = options.path;
  42698. var shape = options.shape;
  42699. var scaleFunction = options.scaleFunction || (function () { return 1; });
  42700. var rotationFunction = options.rotationFunction || (function () { return 0; });
  42701. var ribbonCloseArray = options.ribbonCloseArray || false;
  42702. var ribbonClosePath = options.ribbonClosePath || false;
  42703. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  42704. var updatable = options.updatable;
  42705. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42706. var instance = options.instance;
  42707. var invertUV = options.invertUV || false;
  42708. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  42709. };
  42710. /**
  42711. * Creates lathe mesh.
  42712. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  42713. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  42714. *
  42715. * 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
  42716. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  42717. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  42718. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  42719. * 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.
  42720. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  42721. * 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
  42722. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42723. * 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).
  42724. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42725. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  42726. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42727. */
  42728. MeshBuilder.CreateLathe = function (name, options, scene) {
  42729. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  42730. var closed = (options.closed === undefined) ? true : options.closed;
  42731. var shape = options.shape;
  42732. var radius = options.radius || 1;
  42733. var tessellation = options.tessellation || 64;
  42734. var updatable = options.updatable;
  42735. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42736. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  42737. var pi2 = Math.PI * 2;
  42738. var paths = new Array();
  42739. var invertUV = options.invertUV || false;
  42740. var i = 0;
  42741. var p = 0;
  42742. var step = pi2 / tessellation * arc;
  42743. var rotated;
  42744. var path = new Array();
  42745. ;
  42746. for (i = 0; i <= tessellation; i++) {
  42747. var path = [];
  42748. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  42749. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  42750. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  42751. }
  42752. for (p = 0; p < shape.length; p++) {
  42753. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  42754. path.push(rotated);
  42755. }
  42756. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  42757. 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));
  42758. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  42759. }
  42760. paths.push(path);
  42761. }
  42762. // lathe ribbon
  42763. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  42764. return lathe;
  42765. };
  42766. /**
  42767. * Creates a plane mesh.
  42768. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  42769. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  42770. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  42771. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  42772. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42773. * 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).
  42774. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42775. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42776. */
  42777. MeshBuilder.CreatePlane = function (name, options, scene) {
  42778. var plane = new BABYLON.Mesh(name, scene);
  42779. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42780. plane.sideOrientation = options.sideOrientation;
  42781. var vertexData = BABYLON.VertexData.CreatePlane(options);
  42782. vertexData.applyToMesh(plane, options.updatable);
  42783. if (options.sourcePlane) {
  42784. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  42785. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  42786. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  42787. plane.rotate(vectorProduct, product);
  42788. }
  42789. return plane;
  42790. };
  42791. /**
  42792. * Creates a ground mesh.
  42793. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  42794. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  42795. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  42796. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42797. */
  42798. MeshBuilder.CreateGround = function (name, options, scene) {
  42799. var ground = new BABYLON.GroundMesh(name, scene);
  42800. ground._setReady(false);
  42801. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  42802. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  42803. ground._width = options.width || 1;
  42804. ground._height = options.height || 1;
  42805. ground._maxX = ground._width / 2;
  42806. ground._maxZ = ground._height / 2;
  42807. ground._minX = -ground._maxX;
  42808. ground._minZ = -ground._maxZ;
  42809. var vertexData = BABYLON.VertexData.CreateGround(options);
  42810. vertexData.applyToMesh(ground, options.updatable);
  42811. ground._setReady(true);
  42812. return ground;
  42813. };
  42814. /**
  42815. * Creates a tiled ground mesh.
  42816. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  42817. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  42818. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  42819. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  42820. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  42821. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  42822. * numbers of subdivisions on the ground width and height of each tile.
  42823. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42824. */
  42825. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  42826. var tiledGround = new BABYLON.Mesh(name, scene);
  42827. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  42828. vertexData.applyToMesh(tiledGround, options.updatable);
  42829. return tiledGround;
  42830. };
  42831. /**
  42832. * Creates a ground mesh from a height map.
  42833. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  42834. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  42835. * The parameter `url` sets the URL of the height map image resource.
  42836. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  42837. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  42838. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  42839. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  42840. * 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.
  42841. * 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).
  42842. * This function is passed the newly built mesh :
  42843. * ```javascript
  42844. * function(mesh) { // do things
  42845. * return; }
  42846. * ```
  42847. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42848. */
  42849. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  42850. var width = options.width || 10.0;
  42851. var height = options.height || 10.0;
  42852. var subdivisions = options.subdivisions || 1 | 0;
  42853. var minHeight = options.minHeight || 0.0;
  42854. var maxHeight = options.maxHeight || 10.0;
  42855. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  42856. var updatable = options.updatable;
  42857. var onReady = options.onReady;
  42858. var ground = new BABYLON.GroundMesh(name, scene);
  42859. ground._subdivisionsX = subdivisions;
  42860. ground._subdivisionsY = subdivisions;
  42861. ground._width = width;
  42862. ground._height = height;
  42863. ground._maxX = ground._width / 2.0;
  42864. ground._maxZ = ground._height / 2.0;
  42865. ground._minX = -ground._maxX;
  42866. ground._minZ = -ground._maxZ;
  42867. ground._setReady(false);
  42868. var onload = function (img) {
  42869. // Getting height map data
  42870. var canvas = document.createElement("canvas");
  42871. var context = canvas.getContext("2d");
  42872. var bufferWidth = img.width;
  42873. var bufferHeight = img.height;
  42874. canvas.width = bufferWidth;
  42875. canvas.height = bufferHeight;
  42876. context.drawImage(img, 0, 0);
  42877. // Create VertexData from map data
  42878. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  42879. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  42880. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  42881. width: width, height: height,
  42882. subdivisions: subdivisions,
  42883. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  42884. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  42885. });
  42886. vertexData.applyToMesh(ground, updatable);
  42887. ground._setReady(true);
  42888. //execute ready callback, if set
  42889. if (onReady) {
  42890. onReady(ground);
  42891. }
  42892. };
  42893. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  42894. return ground;
  42895. };
  42896. /**
  42897. * Creates a polygon mesh.
  42898. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  42899. * 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.
  42900. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42901. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42902. * 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).
  42903. * Remember you can only change the shape positions, not their number when updating a polygon.
  42904. */
  42905. MeshBuilder.CreatePolygon = function (name, options, scene) {
  42906. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42907. var shape = options.shape;
  42908. var holes = options.holes || [];
  42909. var depth = options.depth || 0;
  42910. var contours = [];
  42911. var hole = [];
  42912. for (var i = 0; i < shape.length; i++) {
  42913. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  42914. }
  42915. var epsilon = 0.00000001;
  42916. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  42917. contours.pop();
  42918. }
  42919. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  42920. for (var hNb = 0; hNb < holes.length; hNb++) {
  42921. hole = [];
  42922. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  42923. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  42924. }
  42925. polygonTriangulation.addHole(hole);
  42926. }
  42927. var polygon = polygonTriangulation.build(options.updatable, depth);
  42928. polygon.sideOrientation = options.sideOrientation;
  42929. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  42930. vertexData.applyToMesh(polygon, options.updatable);
  42931. return polygon;
  42932. };
  42933. ;
  42934. /**
  42935. * Creates an extruded polygon mesh, with depth in the Y direction.
  42936. * 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).
  42937. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  42938. */
  42939. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  42940. return MeshBuilder.CreatePolygon(name, options, scene);
  42941. };
  42942. ;
  42943. /**
  42944. * Creates a tube mesh.
  42945. * 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.
  42946. *
  42947. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  42948. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  42949. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  42950. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  42951. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  42952. * 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.
  42953. * It must return a radius value (positive float) :
  42954. * ```javascript
  42955. * var radiusFunction = function(i, distance) {
  42956. * // do things
  42957. * return radius; }
  42958. * ```
  42959. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  42960. * 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
  42961. * 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
  42962. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42963. * 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).
  42964. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42965. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  42966. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42967. */
  42968. MeshBuilder.CreateTube = function (name, options, scene) {
  42969. var path = options.path;
  42970. var radius = options.radius || 1.0;
  42971. var tessellation = options.tessellation || 64 | 0;
  42972. var radiusFunction = options.radiusFunction;
  42973. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  42974. var invertUV = options.invertUV || false;
  42975. var updatable = options.updatable;
  42976. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42977. var instance = options.instance;
  42978. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  42979. // tube geometry
  42980. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  42981. var tangents = path3D.getTangents();
  42982. var normals = path3D.getNormals();
  42983. var distances = path3D.getDistances();
  42984. var pi2 = Math.PI * 2;
  42985. var step = pi2 / tessellation * arc;
  42986. var returnRadius = function () { return radius; };
  42987. var radiusFunctionFinal = radiusFunction || returnRadius;
  42988. var circlePath;
  42989. var rad;
  42990. var normal;
  42991. var rotated;
  42992. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  42993. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  42994. for (var i = 0; i < path.length; i++) {
  42995. rad = radiusFunctionFinal(i, distances[i]); // current radius
  42996. circlePath = Array(); // current circle array
  42997. normal = normals[i]; // current normal
  42998. for (var t = 0; t < tessellation; t++) {
  42999. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  43000. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  43001. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  43002. rotated.scaleInPlace(rad).addInPlace(path[i]);
  43003. circlePath[t] = rotated;
  43004. }
  43005. circlePaths[index] = circlePath;
  43006. index++;
  43007. }
  43008. // cap
  43009. var capPath = function (nbPoints, pathIndex) {
  43010. var pointCap = Array();
  43011. for (var i = 0; i < nbPoints; i++) {
  43012. pointCap.push(path[pathIndex]);
  43013. }
  43014. return pointCap;
  43015. };
  43016. switch (cap) {
  43017. case BABYLON.Mesh.NO_CAP:
  43018. break;
  43019. case BABYLON.Mesh.CAP_START:
  43020. circlePaths[0] = capPath(tessellation, 0);
  43021. circlePaths[1] = circlePaths[2].slice(0);
  43022. break;
  43023. case BABYLON.Mesh.CAP_END:
  43024. circlePaths[index] = circlePaths[index - 1].slice(0);
  43025. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  43026. break;
  43027. case BABYLON.Mesh.CAP_ALL:
  43028. circlePaths[0] = capPath(tessellation, 0);
  43029. circlePaths[1] = circlePaths[2].slice(0);
  43030. circlePaths[index] = circlePaths[index - 1].slice(0);
  43031. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  43032. break;
  43033. default:
  43034. break;
  43035. }
  43036. return circlePaths;
  43037. };
  43038. var path3D;
  43039. var pathArray;
  43040. if (instance) {
  43041. var arc = options.arc || instance.arc;
  43042. path3D = (instance.path3D).update(path);
  43043. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  43044. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  43045. instance.path3D = path3D;
  43046. instance.pathArray = pathArray;
  43047. instance.arc = arc;
  43048. return instance;
  43049. }
  43050. // tube creation
  43051. path3D = new BABYLON.Path3D(path);
  43052. var newPathArray = new Array();
  43053. cap = (cap < 0 || cap > 3) ? 0 : cap;
  43054. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  43055. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  43056. tube.pathArray = pathArray;
  43057. tube.path3D = path3D;
  43058. tube.tessellation = tessellation;
  43059. tube.cap = cap;
  43060. tube.arc = options.arc;
  43061. return tube;
  43062. };
  43063. /**
  43064. * Creates a polyhedron mesh.
  43065. *
  43066. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  43067. * 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
  43068. * to choose the wanted type.
  43069. * The parameter `size` (positive float, default 1) sets the polygon size.
  43070. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  43071. * 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`.
  43072. * 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
  43073. * 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)`).
  43074. * 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
  43075. * 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.
  43076. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43077. * 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).
  43078. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43079. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43080. */
  43081. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  43082. var polyhedron = new BABYLON.Mesh(name, scene);
  43083. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43084. polyhedron.sideOrientation = options.sideOrientation;
  43085. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  43086. vertexData.applyToMesh(polyhedron, options.updatable);
  43087. return polyhedron;
  43088. };
  43089. /**
  43090. * Creates a decal mesh.
  43091. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  43092. * 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.
  43093. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  43094. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  43095. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  43096. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  43097. */
  43098. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  43099. var indices = sourceMesh.getIndices();
  43100. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  43101. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  43102. var position = options.position || BABYLON.Vector3.Zero();
  43103. var normal = options.normal || BABYLON.Vector3.Up();
  43104. var size = options.size || BABYLON.Vector3.One();
  43105. var angle = options.angle || 0;
  43106. // Getting correct rotation
  43107. if (!normal) {
  43108. var target = new BABYLON.Vector3(0, 0, 1);
  43109. var camera = sourceMesh.getScene().activeCamera;
  43110. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  43111. normal = camera.globalPosition.subtract(cameraWorldTarget);
  43112. }
  43113. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  43114. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  43115. var pitch = Math.atan2(normal.y, len);
  43116. // Matrix
  43117. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  43118. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  43119. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  43120. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  43121. var vertexData = new BABYLON.VertexData();
  43122. vertexData.indices = [];
  43123. vertexData.positions = [];
  43124. vertexData.normals = [];
  43125. vertexData.uvs = [];
  43126. var currentVertexDataIndex = 0;
  43127. var extractDecalVector3 = function (indexId) {
  43128. var vertexId = indices[indexId];
  43129. var result = new BABYLON.PositionNormalVertex();
  43130. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  43131. // Send vector to decal local world
  43132. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  43133. // Get normal
  43134. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  43135. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  43136. return result;
  43137. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  43138. var clip = function (vertices, axis) {
  43139. if (vertices.length === 0) {
  43140. return vertices;
  43141. }
  43142. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  43143. var clipVertices = function (v0, v1) {
  43144. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  43145. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  43146. };
  43147. var result = new Array();
  43148. for (var index = 0; index < vertices.length; index += 3) {
  43149. var v1Out;
  43150. var v2Out;
  43151. var v3Out;
  43152. var total = 0;
  43153. var nV1, nV2, nV3, nV4;
  43154. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  43155. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  43156. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  43157. v1Out = d1 > 0;
  43158. v2Out = d2 > 0;
  43159. v3Out = d3 > 0;
  43160. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  43161. switch (total) {
  43162. case 0:
  43163. result.push(vertices[index]);
  43164. result.push(vertices[index + 1]);
  43165. result.push(vertices[index + 2]);
  43166. break;
  43167. case 1:
  43168. if (v1Out) {
  43169. nV1 = vertices[index + 1];
  43170. nV2 = vertices[index + 2];
  43171. nV3 = clipVertices(vertices[index], nV1);
  43172. nV4 = clipVertices(vertices[index], nV2);
  43173. }
  43174. if (v2Out) {
  43175. nV1 = vertices[index];
  43176. nV2 = vertices[index + 2];
  43177. nV3 = clipVertices(vertices[index + 1], nV1);
  43178. nV4 = clipVertices(vertices[index + 1], nV2);
  43179. result.push(nV3);
  43180. result.push(nV2.clone());
  43181. result.push(nV1.clone());
  43182. result.push(nV2.clone());
  43183. result.push(nV3.clone());
  43184. result.push(nV4);
  43185. break;
  43186. }
  43187. if (v3Out) {
  43188. nV1 = vertices[index];
  43189. nV2 = vertices[index + 1];
  43190. nV3 = clipVertices(vertices[index + 2], nV1);
  43191. nV4 = clipVertices(vertices[index + 2], nV2);
  43192. }
  43193. result.push(nV1.clone());
  43194. result.push(nV2.clone());
  43195. result.push(nV3);
  43196. result.push(nV4);
  43197. result.push(nV3.clone());
  43198. result.push(nV2.clone());
  43199. break;
  43200. case 2:
  43201. if (!v1Out) {
  43202. nV1 = vertices[index].clone();
  43203. nV2 = clipVertices(nV1, vertices[index + 1]);
  43204. nV3 = clipVertices(nV1, vertices[index + 2]);
  43205. result.push(nV1);
  43206. result.push(nV2);
  43207. result.push(nV3);
  43208. }
  43209. if (!v2Out) {
  43210. nV1 = vertices[index + 1].clone();
  43211. nV2 = clipVertices(nV1, vertices[index + 2]);
  43212. nV3 = clipVertices(nV1, vertices[index]);
  43213. result.push(nV1);
  43214. result.push(nV2);
  43215. result.push(nV3);
  43216. }
  43217. if (!v3Out) {
  43218. nV1 = vertices[index + 2].clone();
  43219. nV2 = clipVertices(nV1, vertices[index]);
  43220. nV3 = clipVertices(nV1, vertices[index + 1]);
  43221. result.push(nV1);
  43222. result.push(nV2);
  43223. result.push(nV3);
  43224. }
  43225. break;
  43226. case 3:
  43227. break;
  43228. }
  43229. }
  43230. return result;
  43231. };
  43232. for (var index = 0; index < indices.length; index += 3) {
  43233. var faceVertices = new Array();
  43234. faceVertices.push(extractDecalVector3(index));
  43235. faceVertices.push(extractDecalVector3(index + 1));
  43236. faceVertices.push(extractDecalVector3(index + 2));
  43237. // Clip
  43238. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  43239. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  43240. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  43241. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  43242. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  43243. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  43244. if (faceVertices.length === 0) {
  43245. continue;
  43246. }
  43247. // Add UVs and get back to world
  43248. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  43249. var vertex = faceVertices[vIndex];
  43250. //TODO check for Int32Array | Uint32Array | Uint16Array
  43251. vertexData.indices.push(currentVertexDataIndex);
  43252. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  43253. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  43254. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  43255. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  43256. currentVertexDataIndex++;
  43257. }
  43258. }
  43259. // Return mesh
  43260. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  43261. vertexData.applyToMesh(decal);
  43262. decal.position = position.clone();
  43263. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  43264. return decal;
  43265. };
  43266. // Privates
  43267. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  43268. // extrusion geometry
  43269. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  43270. var tangents = path3D.getTangents();
  43271. var normals = path3D.getNormals();
  43272. var binormals = path3D.getBinormals();
  43273. var distances = path3D.getDistances();
  43274. var angle = 0;
  43275. var returnScale = function () { return scale; };
  43276. var returnRotation = function () { return rotation; };
  43277. var rotate = custom ? rotateFunction : returnRotation;
  43278. var scl = custom ? scaleFunction : returnScale;
  43279. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  43280. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  43281. for (var i = 0; i < curve.length; i++) {
  43282. var shapePath = new Array();
  43283. var angleStep = rotate(i, distances[i]);
  43284. var scaleRatio = scl(i, distances[i]);
  43285. for (var p = 0; p < shape.length; p++) {
  43286. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  43287. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  43288. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  43289. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  43290. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  43291. shapePath[p] = rotated;
  43292. }
  43293. shapePaths[index] = shapePath;
  43294. angle += angleStep;
  43295. index++;
  43296. }
  43297. // cap
  43298. var capPath = function (shapePath) {
  43299. var pointCap = Array();
  43300. var barycenter = BABYLON.Vector3.Zero();
  43301. var i;
  43302. for (i = 0; i < shapePath.length; i++) {
  43303. barycenter.addInPlace(shapePath[i]);
  43304. }
  43305. barycenter.scaleInPlace(1.0 / shapePath.length);
  43306. for (i = 0; i < shapePath.length; i++) {
  43307. pointCap.push(barycenter);
  43308. }
  43309. return pointCap;
  43310. };
  43311. switch (cap) {
  43312. case BABYLON.Mesh.NO_CAP:
  43313. break;
  43314. case BABYLON.Mesh.CAP_START:
  43315. shapePaths[0] = capPath(shapePaths[2]);
  43316. shapePaths[1] = shapePaths[2];
  43317. break;
  43318. case BABYLON.Mesh.CAP_END:
  43319. shapePaths[index] = shapePaths[index - 1];
  43320. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  43321. break;
  43322. case BABYLON.Mesh.CAP_ALL:
  43323. shapePaths[0] = capPath(shapePaths[2]);
  43324. shapePaths[1] = shapePaths[2];
  43325. shapePaths[index] = shapePaths[index - 1];
  43326. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  43327. break;
  43328. default:
  43329. break;
  43330. }
  43331. return shapePaths;
  43332. };
  43333. var path3D;
  43334. var pathArray;
  43335. if (instance) {
  43336. path3D = (instance.path3D).update(curve);
  43337. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  43338. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  43339. return instance;
  43340. }
  43341. // extruded shape creation
  43342. path3D = new BABYLON.Path3D(curve);
  43343. var newShapePaths = new Array();
  43344. cap = (cap < 0 || cap > 3) ? 0 : cap;
  43345. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  43346. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs, backUVs: backUVs }, scene);
  43347. extrudedGeneric.pathArray = pathArray;
  43348. extrudedGeneric.path3D = path3D;
  43349. extrudedGeneric.cap = cap;
  43350. return extrudedGeneric;
  43351. };
  43352. return MeshBuilder;
  43353. }());
  43354. BABYLON.MeshBuilder = MeshBuilder;
  43355. })(BABYLON || (BABYLON = {}));
  43356. //# sourceMappingURL=babylon.meshBuilder.js.map
  43357. var BABYLON;
  43358. (function (BABYLON) {
  43359. var AudioEngine = (function () {
  43360. function AudioEngine() {
  43361. this._audioContext = null;
  43362. this._audioContextInitialized = false;
  43363. this.canUseWebAudio = false;
  43364. this.WarnedWebAudioUnsupported = false;
  43365. this.unlocked = false;
  43366. this.isMP3supported = false;
  43367. this.isOGGsupported = false;
  43368. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  43369. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  43370. this.canUseWebAudio = true;
  43371. }
  43372. var audioElem = document.createElement('audio');
  43373. try {
  43374. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  43375. this.isMP3supported = true;
  43376. }
  43377. }
  43378. catch (e) {
  43379. // protect error during capability check.
  43380. }
  43381. try {
  43382. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  43383. this.isOGGsupported = true;
  43384. }
  43385. }
  43386. catch (e) {
  43387. // protect error during capability check.
  43388. }
  43389. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  43390. this._unlockiOSaudio();
  43391. }
  43392. else {
  43393. this.unlocked = true;
  43394. }
  43395. }
  43396. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  43397. get: function () {
  43398. if (!this._audioContextInitialized) {
  43399. this._initializeAudioContext();
  43400. }
  43401. return this._audioContext;
  43402. },
  43403. enumerable: true,
  43404. configurable: true
  43405. });
  43406. AudioEngine.prototype._unlockiOSaudio = function () {
  43407. var _this = this;
  43408. var unlockaudio = function () {
  43409. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  43410. var source = _this.audioContext.createBufferSource();
  43411. source.buffer = buffer;
  43412. source.connect(_this.audioContext.destination);
  43413. source.start(0);
  43414. setTimeout(function () {
  43415. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  43416. _this.unlocked = true;
  43417. window.removeEventListener('touchend', unlockaudio, false);
  43418. if (_this.onAudioUnlocked) {
  43419. _this.onAudioUnlocked();
  43420. }
  43421. }
  43422. }, 0);
  43423. };
  43424. window.addEventListener('touchend', unlockaudio, false);
  43425. };
  43426. AudioEngine.prototype._initializeAudioContext = function () {
  43427. try {
  43428. if (this.canUseWebAudio) {
  43429. this._audioContext = new AudioContext();
  43430. // create a global volume gain node
  43431. this.masterGain = this._audioContext.createGain();
  43432. this.masterGain.gain.value = 1;
  43433. this.masterGain.connect(this._audioContext.destination);
  43434. this._audioContextInitialized = true;
  43435. }
  43436. }
  43437. catch (e) {
  43438. this.canUseWebAudio = false;
  43439. BABYLON.Tools.Error("Web Audio: " + e.message);
  43440. }
  43441. };
  43442. AudioEngine.prototype.dispose = function () {
  43443. if (this.canUseWebAudio && this._audioContextInitialized) {
  43444. if (this._connectedAnalyser) {
  43445. this._connectedAnalyser.stopDebugCanvas();
  43446. this._connectedAnalyser.dispose();
  43447. this.masterGain.disconnect();
  43448. this.masterGain.connect(this._audioContext.destination);
  43449. this._connectedAnalyser = null;
  43450. }
  43451. this.masterGain.gain.value = 1;
  43452. }
  43453. this.WarnedWebAudioUnsupported = false;
  43454. };
  43455. AudioEngine.prototype.getGlobalVolume = function () {
  43456. if (this.canUseWebAudio && this._audioContextInitialized) {
  43457. return this.masterGain.gain.value;
  43458. }
  43459. else {
  43460. return -1;
  43461. }
  43462. };
  43463. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  43464. if (this.canUseWebAudio && this._audioContextInitialized) {
  43465. this.masterGain.gain.value = newVolume;
  43466. }
  43467. };
  43468. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  43469. if (this._connectedAnalyser) {
  43470. this._connectedAnalyser.stopDebugCanvas();
  43471. }
  43472. if (this.canUseWebAudio && this._audioContextInitialized) {
  43473. this._connectedAnalyser = analyser;
  43474. this.masterGain.disconnect();
  43475. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  43476. }
  43477. };
  43478. return AudioEngine;
  43479. }());
  43480. BABYLON.AudioEngine = AudioEngine;
  43481. })(BABYLON || (BABYLON = {}));
  43482. //# sourceMappingURL=babylon.audioEngine.js.map
  43483. var BABYLON;
  43484. (function (BABYLON) {
  43485. var Sound = (function () {
  43486. /**
  43487. * Create a sound and attach it to a scene
  43488. * @param name Name of your sound
  43489. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  43490. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  43491. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  43492. */
  43493. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  43494. var _this = this;
  43495. this.autoplay = false;
  43496. this.loop = false;
  43497. this.useCustomAttenuation = false;
  43498. this.spatialSound = false;
  43499. this.refDistance = 1;
  43500. this.rolloffFactor = 1;
  43501. this.maxDistance = 100;
  43502. this.distanceModel = "linear";
  43503. this._panningModel = "equalpower";
  43504. this._playbackRate = 1;
  43505. this._streaming = false;
  43506. this._startTime = 0;
  43507. this._startOffset = 0;
  43508. this._position = BABYLON.Vector3.Zero();
  43509. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  43510. this._volume = 1;
  43511. this._isLoaded = false;
  43512. this._isReadyToPlay = false;
  43513. this.isPlaying = false;
  43514. this.isPaused = false;
  43515. this._isDirectional = false;
  43516. // Used if you'd like to create a directional sound.
  43517. // If not set, the sound will be omnidirectional
  43518. this._coneInnerAngle = 360;
  43519. this._coneOuterAngle = 360;
  43520. this._coneOuterGain = 0;
  43521. this._isOutputConnected = false;
  43522. this._urlType = "Unknown";
  43523. this.name = name;
  43524. this._scene = scene;
  43525. this._readyToPlayCallback = readyToPlayCallback;
  43526. // Default custom attenuation function is a linear attenuation
  43527. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  43528. if (currentDistance < maxDistance) {
  43529. return currentVolume * (1 - currentDistance / maxDistance);
  43530. }
  43531. else {
  43532. return 0;
  43533. }
  43534. };
  43535. if (options) {
  43536. this.autoplay = options.autoplay || false;
  43537. this.loop = options.loop || false;
  43538. // if volume === 0, we need another way to check this option
  43539. if (options.volume !== undefined) {
  43540. this._volume = options.volume;
  43541. }
  43542. this.spatialSound = options.spatialSound || false;
  43543. this.maxDistance = options.maxDistance || 100;
  43544. this.useCustomAttenuation = options.useCustomAttenuation || false;
  43545. this.rolloffFactor = options.rolloffFactor || 1;
  43546. this.refDistance = options.refDistance || 1;
  43547. this.distanceModel = options.distanceModel || "linear";
  43548. this._playbackRate = options.playbackRate || 1;
  43549. this._streaming = options.streaming || false;
  43550. }
  43551. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43552. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  43553. this._soundGain.gain.value = this._volume;
  43554. this._inputAudioNode = this._soundGain;
  43555. this._ouputAudioNode = this._soundGain;
  43556. if (this.spatialSound) {
  43557. this._createSpatialParameters();
  43558. }
  43559. this._scene.mainSoundTrack.AddSound(this);
  43560. var validParameter = true;
  43561. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  43562. if (urlOrArrayBuffer) {
  43563. if (typeof (urlOrArrayBuffer) === "string")
  43564. this._urlType = "String";
  43565. if (Array.isArray(urlOrArrayBuffer))
  43566. this._urlType = "Array";
  43567. if (urlOrArrayBuffer instanceof ArrayBuffer)
  43568. this._urlType = "ArrayBuffer";
  43569. var urls = [];
  43570. var codecSupportedFound = false;
  43571. switch (this._urlType) {
  43572. case "ArrayBuffer":
  43573. if (urlOrArrayBuffer.byteLength > 0) {
  43574. codecSupportedFound = true;
  43575. this._soundLoaded(urlOrArrayBuffer);
  43576. }
  43577. break;
  43578. case "String":
  43579. urls.push(urlOrArrayBuffer);
  43580. case "Array":
  43581. if (urls.length === 0)
  43582. urls = urlOrArrayBuffer;
  43583. // If we found a supported format, we load it immediately and stop the loop
  43584. for (var i = 0; i < urls.length; i++) {
  43585. var url = urls[i];
  43586. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  43587. codecSupportedFound = true;
  43588. }
  43589. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  43590. codecSupportedFound = true;
  43591. }
  43592. if (url.indexOf(".wav", url.length - 4) !== -1) {
  43593. codecSupportedFound = true;
  43594. }
  43595. if (url.indexOf("blob:") !== -1) {
  43596. codecSupportedFound = true;
  43597. }
  43598. if (codecSupportedFound) {
  43599. // Loading sound using XHR2
  43600. if (!this._streaming) {
  43601. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  43602. }
  43603. else {
  43604. this._htmlAudioElement = new Audio(url);
  43605. this._htmlAudioElement.controls = false;
  43606. this._htmlAudioElement.loop = this.loop;
  43607. this._htmlAudioElement.crossOrigin = "anonymous";
  43608. this._htmlAudioElement.preload = "auto";
  43609. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  43610. _this._isReadyToPlay = true;
  43611. if (_this.autoplay) {
  43612. _this.play();
  43613. }
  43614. if (_this._readyToPlayCallback) {
  43615. _this._readyToPlayCallback();
  43616. }
  43617. });
  43618. document.body.appendChild(this._htmlAudioElement);
  43619. }
  43620. break;
  43621. }
  43622. }
  43623. break;
  43624. default:
  43625. validParameter = false;
  43626. break;
  43627. }
  43628. if (!validParameter) {
  43629. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  43630. }
  43631. else {
  43632. if (!codecSupportedFound) {
  43633. this._isReadyToPlay = true;
  43634. // Simulating a ready to play event to avoid breaking code path
  43635. if (this._readyToPlayCallback) {
  43636. window.setTimeout(function () {
  43637. _this._readyToPlayCallback();
  43638. }, 1000);
  43639. }
  43640. }
  43641. }
  43642. }
  43643. }
  43644. else {
  43645. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  43646. this._scene.mainSoundTrack.AddSound(this);
  43647. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  43648. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  43649. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  43650. }
  43651. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  43652. if (this._readyToPlayCallback) {
  43653. window.setTimeout(function () {
  43654. _this._readyToPlayCallback();
  43655. }, 1000);
  43656. }
  43657. }
  43658. }
  43659. Sound.prototype.dispose = function () {
  43660. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  43661. if (this.isPlaying) {
  43662. this.stop();
  43663. }
  43664. this._isReadyToPlay = false;
  43665. if (this.soundTrackId === -1) {
  43666. this._scene.mainSoundTrack.RemoveSound(this);
  43667. }
  43668. else {
  43669. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  43670. }
  43671. if (this._soundGain) {
  43672. this._soundGain.disconnect();
  43673. this._soundGain = null;
  43674. }
  43675. if (this._soundPanner) {
  43676. this._soundPanner.disconnect();
  43677. this._soundPanner = null;
  43678. }
  43679. if (this._soundSource) {
  43680. this._soundSource.disconnect();
  43681. this._soundSource = null;
  43682. }
  43683. this._audioBuffer = null;
  43684. if (this._htmlAudioElement) {
  43685. this._htmlAudioElement.pause();
  43686. this._htmlAudioElement.src = "";
  43687. document.body.removeChild(this._htmlAudioElement);
  43688. }
  43689. if (this._connectedMesh) {
  43690. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  43691. this._connectedMesh = null;
  43692. }
  43693. }
  43694. };
  43695. Sound.prototype.isReady = function () {
  43696. return this._isReadyToPlay;
  43697. };
  43698. Sound.prototype._soundLoaded = function (audioData) {
  43699. var _this = this;
  43700. this._isLoaded = true;
  43701. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  43702. _this._audioBuffer = buffer;
  43703. _this._isReadyToPlay = true;
  43704. if (_this.autoplay) {
  43705. _this.play();
  43706. }
  43707. if (_this._readyToPlayCallback) {
  43708. _this._readyToPlayCallback();
  43709. }
  43710. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  43711. };
  43712. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  43713. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43714. this._audioBuffer = audioBuffer;
  43715. this._isReadyToPlay = true;
  43716. }
  43717. };
  43718. Sound.prototype.updateOptions = function (options) {
  43719. if (options) {
  43720. this.loop = options.loop || this.loop;
  43721. this.maxDistance = options.maxDistance || this.maxDistance;
  43722. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  43723. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  43724. this.refDistance = options.refDistance || this.refDistance;
  43725. this.distanceModel = options.distanceModel || this.distanceModel;
  43726. this._playbackRate = options.playbackRate || this._playbackRate;
  43727. this._updateSpatialParameters();
  43728. if (this.isPlaying) {
  43729. if (this._streaming) {
  43730. this._htmlAudioElement.playbackRate = this._playbackRate;
  43731. }
  43732. else {
  43733. this._soundSource.playbackRate.value = this._playbackRate;
  43734. }
  43735. }
  43736. }
  43737. };
  43738. Sound.prototype._createSpatialParameters = function () {
  43739. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43740. if (this._scene.headphone) {
  43741. this._panningModel = "HRTF";
  43742. }
  43743. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  43744. this._updateSpatialParameters();
  43745. this._soundPanner.connect(this._ouputAudioNode);
  43746. this._inputAudioNode = this._soundPanner;
  43747. }
  43748. };
  43749. Sound.prototype._updateSpatialParameters = function () {
  43750. if (this.spatialSound) {
  43751. if (this.useCustomAttenuation) {
  43752. // Tricks to disable in a way embedded Web Audio attenuation
  43753. this._soundPanner.distanceModel = "linear";
  43754. this._soundPanner.maxDistance = Number.MAX_VALUE;
  43755. this._soundPanner.refDistance = 1;
  43756. this._soundPanner.rolloffFactor = 1;
  43757. this._soundPanner.panningModel = this._panningModel;
  43758. }
  43759. else {
  43760. this._soundPanner.distanceModel = this.distanceModel;
  43761. this._soundPanner.maxDistance = this.maxDistance;
  43762. this._soundPanner.refDistance = this.refDistance;
  43763. this._soundPanner.rolloffFactor = this.rolloffFactor;
  43764. this._soundPanner.panningModel = this._panningModel;
  43765. }
  43766. }
  43767. };
  43768. Sound.prototype.switchPanningModelToHRTF = function () {
  43769. this._panningModel = "HRTF";
  43770. this._switchPanningModel();
  43771. };
  43772. Sound.prototype.switchPanningModelToEqualPower = function () {
  43773. this._panningModel = "equalpower";
  43774. this._switchPanningModel();
  43775. };
  43776. Sound.prototype._switchPanningModel = function () {
  43777. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  43778. this._soundPanner.panningModel = this._panningModel;
  43779. }
  43780. };
  43781. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  43782. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43783. if (this._isOutputConnected) {
  43784. this._ouputAudioNode.disconnect();
  43785. }
  43786. this._ouputAudioNode.connect(soundTrackAudioNode);
  43787. this._isOutputConnected = true;
  43788. }
  43789. };
  43790. /**
  43791. * Transform this sound into a directional source
  43792. * @param coneInnerAngle Size of the inner cone in degree
  43793. * @param coneOuterAngle Size of the outer cone in degree
  43794. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  43795. */
  43796. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  43797. if (coneOuterAngle < coneInnerAngle) {
  43798. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  43799. return;
  43800. }
  43801. this._coneInnerAngle = coneInnerAngle;
  43802. this._coneOuterAngle = coneOuterAngle;
  43803. this._coneOuterGain = coneOuterGain;
  43804. this._isDirectional = true;
  43805. if (this.isPlaying && this.loop) {
  43806. this.stop();
  43807. this.play();
  43808. }
  43809. };
  43810. Sound.prototype.setPosition = function (newPosition) {
  43811. this._position = newPosition;
  43812. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  43813. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  43814. }
  43815. };
  43816. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  43817. this._localDirection = newLocalDirection;
  43818. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  43819. this._updateDirection();
  43820. }
  43821. };
  43822. Sound.prototype._updateDirection = function () {
  43823. var mat = this._connectedMesh.getWorldMatrix();
  43824. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  43825. direction.normalize();
  43826. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  43827. };
  43828. Sound.prototype.updateDistanceFromListener = function () {
  43829. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  43830. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  43831. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  43832. }
  43833. };
  43834. Sound.prototype.setAttenuationFunction = function (callback) {
  43835. this._customAttenuationFunction = callback;
  43836. };
  43837. /**
  43838. * Play the sound
  43839. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  43840. * @param offset (optional) Start the sound setting it at a specific time
  43841. */
  43842. Sound.prototype.play = function (time, offset) {
  43843. var _this = this;
  43844. if (this._isReadyToPlay && this._scene.audioEnabled) {
  43845. try {
  43846. if (this._startOffset < 0) {
  43847. time = -this._startOffset;
  43848. this._startOffset = 0;
  43849. }
  43850. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  43851. if (!this._soundSource || !this._streamingSource) {
  43852. if (this.spatialSound) {
  43853. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  43854. if (this._isDirectional) {
  43855. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  43856. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  43857. this._soundPanner.coneOuterGain = this._coneOuterGain;
  43858. if (this._connectedMesh) {
  43859. this._updateDirection();
  43860. }
  43861. else {
  43862. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  43863. }
  43864. }
  43865. }
  43866. }
  43867. if (this._streaming) {
  43868. if (!this._streamingSource) {
  43869. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  43870. this._htmlAudioElement.onended = function () { _this._onended(); };
  43871. this._htmlAudioElement.playbackRate = this._playbackRate;
  43872. }
  43873. this._streamingSource.disconnect();
  43874. this._streamingSource.connect(this._inputAudioNode);
  43875. this._htmlAudioElement.play();
  43876. }
  43877. else {
  43878. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  43879. this._soundSource.buffer = this._audioBuffer;
  43880. this._soundSource.connect(this._inputAudioNode);
  43881. this._soundSource.loop = this.loop;
  43882. this._soundSource.playbackRate.value = this._playbackRate;
  43883. this._soundSource.onended = function () { _this._onended(); };
  43884. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  43885. }
  43886. this._startTime = startTime;
  43887. this.isPlaying = true;
  43888. this.isPaused = false;
  43889. }
  43890. catch (ex) {
  43891. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  43892. }
  43893. }
  43894. };
  43895. Sound.prototype._onended = function () {
  43896. this.isPlaying = false;
  43897. if (this.onended) {
  43898. this.onended();
  43899. }
  43900. };
  43901. /**
  43902. * Stop the sound
  43903. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  43904. */
  43905. Sound.prototype.stop = function (time) {
  43906. if (this.isPlaying) {
  43907. if (this._streaming) {
  43908. this._htmlAudioElement.pause();
  43909. // Test needed for Firefox or it will generate an Invalid State Error
  43910. if (this._htmlAudioElement.currentTime > 0) {
  43911. this._htmlAudioElement.currentTime = 0;
  43912. }
  43913. }
  43914. else {
  43915. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  43916. this._soundSource.stop(stopTime);
  43917. this._soundSource.onended = null;
  43918. if (!this.isPaused) {
  43919. this._startOffset = 0;
  43920. }
  43921. }
  43922. this.isPlaying = false;
  43923. }
  43924. };
  43925. Sound.prototype.pause = function () {
  43926. if (this.isPlaying) {
  43927. this.isPaused = true;
  43928. if (this._streaming) {
  43929. this._htmlAudioElement.pause();
  43930. }
  43931. else {
  43932. this.stop(0);
  43933. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  43934. }
  43935. }
  43936. };
  43937. Sound.prototype.setVolume = function (newVolume, time) {
  43938. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43939. if (time) {
  43940. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  43941. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  43942. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  43943. }
  43944. else {
  43945. this._soundGain.gain.value = newVolume;
  43946. }
  43947. }
  43948. this._volume = newVolume;
  43949. };
  43950. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  43951. this._playbackRate = newPlaybackRate;
  43952. if (this.isPlaying) {
  43953. if (this._streaming) {
  43954. this._htmlAudioElement.playbackRate = this._playbackRate;
  43955. }
  43956. else {
  43957. this._soundSource.playbackRate.value = this._playbackRate;
  43958. }
  43959. }
  43960. };
  43961. Sound.prototype.getVolume = function () {
  43962. return this._volume;
  43963. };
  43964. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  43965. var _this = this;
  43966. if (this._connectedMesh) {
  43967. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  43968. this._registerFunc = null;
  43969. }
  43970. this._connectedMesh = meshToConnectTo;
  43971. if (!this.spatialSound) {
  43972. this.spatialSound = true;
  43973. this._createSpatialParameters();
  43974. if (this.isPlaying && this.loop) {
  43975. this.stop();
  43976. this.play();
  43977. }
  43978. }
  43979. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  43980. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  43981. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  43982. };
  43983. Sound.prototype.detachFromMesh = function () {
  43984. if (this._connectedMesh) {
  43985. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  43986. this._registerFunc = null;
  43987. this._connectedMesh = null;
  43988. }
  43989. };
  43990. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  43991. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  43992. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  43993. this._updateDirection();
  43994. }
  43995. };
  43996. Sound.prototype.clone = function () {
  43997. var _this = this;
  43998. if (!this._streaming) {
  43999. var setBufferAndRun = function () {
  44000. if (_this._isReadyToPlay) {
  44001. clonedSound._audioBuffer = _this.getAudioBuffer();
  44002. clonedSound._isReadyToPlay = true;
  44003. if (clonedSound.autoplay) {
  44004. clonedSound.play();
  44005. }
  44006. }
  44007. else {
  44008. window.setTimeout(setBufferAndRun, 300);
  44009. }
  44010. };
  44011. var currentOptions = {
  44012. autoplay: this.autoplay, loop: this.loop,
  44013. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  44014. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  44015. refDistance: this.refDistance, distanceModel: this.distanceModel
  44016. };
  44017. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  44018. if (this.useCustomAttenuation) {
  44019. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  44020. }
  44021. clonedSound.setPosition(this._position);
  44022. clonedSound.setPlaybackRate(this._playbackRate);
  44023. setBufferAndRun();
  44024. return clonedSound;
  44025. }
  44026. else {
  44027. return null;
  44028. }
  44029. };
  44030. Sound.prototype.getAudioBuffer = function () {
  44031. return this._audioBuffer;
  44032. };
  44033. Sound.prototype.serialize = function () {
  44034. var serializationObject = {
  44035. name: this.name,
  44036. url: this.name,
  44037. autoplay: this.autoplay,
  44038. loop: this.loop,
  44039. volume: this._volume,
  44040. spatialSound: this.spatialSound,
  44041. maxDistance: this.maxDistance,
  44042. rolloffFactor: this.rolloffFactor,
  44043. refDistance: this.refDistance,
  44044. distanceModel: this.distanceModel,
  44045. playbackRate: this._playbackRate,
  44046. panningModel: this._panningModel,
  44047. soundTrackId: this.soundTrackId
  44048. };
  44049. if (this.spatialSound) {
  44050. if (this._connectedMesh)
  44051. serializationObject.connectedMeshId = this._connectedMesh.id;
  44052. serializationObject.position = this._position.asArray();
  44053. serializationObject.refDistance = this.refDistance;
  44054. serializationObject.distanceModel = this.distanceModel;
  44055. serializationObject.isDirectional = this._isDirectional;
  44056. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  44057. serializationObject.coneInnerAngle = this._coneInnerAngle;
  44058. serializationObject.coneOuterAngle = this._coneOuterAngle;
  44059. serializationObject.coneOuterGain = this._coneOuterGain;
  44060. }
  44061. return serializationObject;
  44062. };
  44063. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  44064. var soundName = parsedSound.name;
  44065. var soundUrl;
  44066. if (parsedSound.url) {
  44067. soundUrl = rootUrl + parsedSound.url;
  44068. }
  44069. else {
  44070. soundUrl = rootUrl + soundName;
  44071. }
  44072. var options = {
  44073. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  44074. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  44075. rolloffFactor: parsedSound.rolloffFactor,
  44076. refDistance: parsedSound.refDistance,
  44077. distanceModel: parsedSound.distanceModel,
  44078. playbackRate: parsedSound.playbackRate
  44079. };
  44080. var newSound;
  44081. if (!sourceSound) {
  44082. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  44083. scene._addPendingData(newSound);
  44084. }
  44085. else {
  44086. var setBufferAndRun = function () {
  44087. if (sourceSound._isReadyToPlay) {
  44088. newSound._audioBuffer = sourceSound.getAudioBuffer();
  44089. newSound._isReadyToPlay = true;
  44090. if (newSound.autoplay) {
  44091. newSound.play();
  44092. }
  44093. }
  44094. else {
  44095. window.setTimeout(setBufferAndRun, 300);
  44096. }
  44097. };
  44098. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  44099. setBufferAndRun();
  44100. }
  44101. if (parsedSound.position) {
  44102. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  44103. newSound.setPosition(soundPosition);
  44104. }
  44105. if (parsedSound.isDirectional) {
  44106. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  44107. if (parsedSound.localDirectionToMesh) {
  44108. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  44109. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  44110. }
  44111. }
  44112. if (parsedSound.connectedMeshId) {
  44113. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  44114. if (connectedMesh) {
  44115. newSound.attachToMesh(connectedMesh);
  44116. }
  44117. }
  44118. return newSound;
  44119. };
  44120. return Sound;
  44121. }());
  44122. BABYLON.Sound = Sound;
  44123. })(BABYLON || (BABYLON = {}));
  44124. //# sourceMappingURL=babylon.sound.js.map
  44125. var BABYLON;
  44126. (function (BABYLON) {
  44127. var SoundTrack = (function () {
  44128. function SoundTrack(scene, options) {
  44129. this.id = -1;
  44130. this._isMainTrack = false;
  44131. this._isInitialized = false;
  44132. this._scene = scene;
  44133. this.soundCollection = new Array();
  44134. this._options = options;
  44135. if (!this._isMainTrack) {
  44136. this._scene.soundTracks.push(this);
  44137. this.id = this._scene.soundTracks.length - 1;
  44138. }
  44139. }
  44140. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  44141. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44142. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  44143. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  44144. if (this._options) {
  44145. if (this._options.volume) {
  44146. this._outputAudioNode.gain.value = this._options.volume;
  44147. }
  44148. if (this._options.mainTrack) {
  44149. this._isMainTrack = this._options.mainTrack;
  44150. }
  44151. }
  44152. this._isInitialized = true;
  44153. }
  44154. };
  44155. SoundTrack.prototype.dispose = function () {
  44156. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44157. if (this._connectedAnalyser) {
  44158. this._connectedAnalyser.stopDebugCanvas();
  44159. }
  44160. while (this.soundCollection.length) {
  44161. this.soundCollection[0].dispose();
  44162. }
  44163. if (this._outputAudioNode) {
  44164. this._outputAudioNode.disconnect();
  44165. }
  44166. this._outputAudioNode = null;
  44167. }
  44168. };
  44169. SoundTrack.prototype.AddSound = function (sound) {
  44170. if (!this._isInitialized) {
  44171. this._initializeSoundTrackAudioGraph();
  44172. }
  44173. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44174. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  44175. }
  44176. if (sound.soundTrackId) {
  44177. if (sound.soundTrackId === -1) {
  44178. this._scene.mainSoundTrack.RemoveSound(sound);
  44179. }
  44180. else {
  44181. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  44182. }
  44183. }
  44184. this.soundCollection.push(sound);
  44185. sound.soundTrackId = this.id;
  44186. };
  44187. SoundTrack.prototype.RemoveSound = function (sound) {
  44188. var index = this.soundCollection.indexOf(sound);
  44189. if (index !== -1) {
  44190. this.soundCollection.splice(index, 1);
  44191. }
  44192. };
  44193. SoundTrack.prototype.setVolume = function (newVolume) {
  44194. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44195. this._outputAudioNode.gain.value = newVolume;
  44196. }
  44197. };
  44198. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  44199. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44200. for (var i = 0; i < this.soundCollection.length; i++) {
  44201. this.soundCollection[i].switchPanningModelToHRTF();
  44202. }
  44203. }
  44204. };
  44205. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  44206. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44207. for (var i = 0; i < this.soundCollection.length; i++) {
  44208. this.soundCollection[i].switchPanningModelToEqualPower();
  44209. }
  44210. }
  44211. };
  44212. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  44213. if (this._connectedAnalyser) {
  44214. this._connectedAnalyser.stopDebugCanvas();
  44215. }
  44216. this._connectedAnalyser = analyser;
  44217. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44218. this._outputAudioNode.disconnect();
  44219. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  44220. }
  44221. };
  44222. return SoundTrack;
  44223. }());
  44224. BABYLON.SoundTrack = SoundTrack;
  44225. })(BABYLON || (BABYLON = {}));
  44226. //# sourceMappingURL=babylon.soundtrack.js.map
  44227. var BABYLON;
  44228. (function (BABYLON) {
  44229. var Analyser = (function () {
  44230. function Analyser(scene) {
  44231. this.SMOOTHING = 0.75;
  44232. this.FFT_SIZE = 512;
  44233. this.BARGRAPHAMPLITUDE = 256;
  44234. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  44235. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  44236. this._scene = scene;
  44237. this._audioEngine = BABYLON.Engine.audioEngine;
  44238. if (this._audioEngine.canUseWebAudio) {
  44239. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  44240. this._webAudioAnalyser.minDecibels = -140;
  44241. this._webAudioAnalyser.maxDecibels = 0;
  44242. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  44243. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  44244. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  44245. }
  44246. }
  44247. Analyser.prototype.getFrequencyBinCount = function () {
  44248. if (this._audioEngine.canUseWebAudio) {
  44249. return this._webAudioAnalyser.frequencyBinCount;
  44250. }
  44251. else {
  44252. return 0;
  44253. }
  44254. };
  44255. Analyser.prototype.getByteFrequencyData = function () {
  44256. if (this._audioEngine.canUseWebAudio) {
  44257. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  44258. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  44259. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  44260. }
  44261. return this._byteFreqs;
  44262. };
  44263. Analyser.prototype.getByteTimeDomainData = function () {
  44264. if (this._audioEngine.canUseWebAudio) {
  44265. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  44266. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  44267. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  44268. }
  44269. return this._byteTime;
  44270. };
  44271. Analyser.prototype.getFloatFrequencyData = function () {
  44272. if (this._audioEngine.canUseWebAudio) {
  44273. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  44274. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  44275. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  44276. }
  44277. return this._floatFreqs;
  44278. };
  44279. Analyser.prototype.drawDebugCanvas = function () {
  44280. var _this = this;
  44281. if (this._audioEngine.canUseWebAudio) {
  44282. if (!this._debugCanvas) {
  44283. this._debugCanvas = document.createElement("canvas");
  44284. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  44285. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  44286. this._debugCanvas.style.position = "absolute";
  44287. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  44288. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  44289. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  44290. document.body.appendChild(this._debugCanvas);
  44291. this._registerFunc = function () {
  44292. _this.drawDebugCanvas();
  44293. };
  44294. this._scene.registerBeforeRender(this._registerFunc);
  44295. }
  44296. if (this._registerFunc) {
  44297. var workingArray = this.getByteFrequencyData();
  44298. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  44299. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  44300. // Draw the frequency domain chart.
  44301. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  44302. var value = workingArray[i];
  44303. var percent = value / this.BARGRAPHAMPLITUDE;
  44304. var height = this.DEBUGCANVASSIZE.height * percent;
  44305. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  44306. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  44307. var hue = i / this.getFrequencyBinCount() * 360;
  44308. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  44309. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  44310. }
  44311. }
  44312. }
  44313. };
  44314. Analyser.prototype.stopDebugCanvas = function () {
  44315. if (this._debugCanvas) {
  44316. this._scene.unregisterBeforeRender(this._registerFunc);
  44317. this._registerFunc = null;
  44318. document.body.removeChild(this._debugCanvas);
  44319. this._debugCanvas = null;
  44320. this._debugCanvasContext = null;
  44321. }
  44322. };
  44323. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  44324. if (this._audioEngine.canUseWebAudio) {
  44325. inputAudioNode.connect(this._webAudioAnalyser);
  44326. this._webAudioAnalyser.connect(outputAudioNode);
  44327. }
  44328. };
  44329. Analyser.prototype.dispose = function () {
  44330. if (this._audioEngine.canUseWebAudio) {
  44331. this._webAudioAnalyser.disconnect();
  44332. }
  44333. };
  44334. return Analyser;
  44335. }());
  44336. BABYLON.Analyser = Analyser;
  44337. })(BABYLON || (BABYLON = {}));
  44338. //# sourceMappingURL=babylon.analyser.js.map
  44339. var BABYLON;
  44340. (function (BABYLON) {
  44341. var CubeTexture = (function (_super) {
  44342. __extends(CubeTexture, _super);
  44343. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  44344. if (onLoad === void 0) { onLoad = null; }
  44345. if (onError === void 0) { onError = null; }
  44346. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  44347. if (prefiltered === void 0) { prefiltered = false; }
  44348. if (forcedExtension === void 0) { forcedExtension = null; }
  44349. var _this = _super.call(this, scene) || this;
  44350. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  44351. _this.name = rootUrl;
  44352. _this.url = rootUrl;
  44353. _this._noMipmap = noMipmap;
  44354. _this.hasAlpha = false;
  44355. _this._format = format;
  44356. _this._prefiltered = prefiltered;
  44357. _this.isCube = true;
  44358. _this._textureMatrix = BABYLON.Matrix.Identity();
  44359. if (prefiltered) {
  44360. _this.gammaSpace = false;
  44361. }
  44362. if (!rootUrl && !files) {
  44363. return _this;
  44364. }
  44365. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  44366. if (!files) {
  44367. if (!extensions) {
  44368. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  44369. }
  44370. files = [];
  44371. for (var index = 0; index < extensions.length; index++) {
  44372. files.push(rootUrl + extensions[index]);
  44373. }
  44374. _this._extensions = extensions;
  44375. }
  44376. _this._files = files;
  44377. if (!_this._texture) {
  44378. if (!scene.useDelayedTextureLoading) {
  44379. if (prefiltered) {
  44380. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  44381. }
  44382. else {
  44383. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  44384. }
  44385. }
  44386. else {
  44387. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  44388. }
  44389. }
  44390. else if (onLoad) {
  44391. if (_this._texture.isReady) {
  44392. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  44393. }
  44394. else {
  44395. _this._texture.onLoadedCallbacks.push(onLoad);
  44396. }
  44397. }
  44398. return _this;
  44399. }
  44400. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  44401. return new CubeTexture("", scene, null, noMipmap, files);
  44402. };
  44403. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  44404. if (forcedExtension === void 0) { forcedExtension = null; }
  44405. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  44406. };
  44407. // Methods
  44408. CubeTexture.prototype.delayLoad = function () {
  44409. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  44410. return;
  44411. }
  44412. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  44413. this._texture = this._getFromCache(this.url, this._noMipmap);
  44414. if (!this._texture) {
  44415. if (this._prefiltered) {
  44416. this._texture = this.getScene().getEngine().createPrefilteredCubeTexture(this.url, this.getScene(), this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  44417. }
  44418. else {
  44419. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  44420. }
  44421. }
  44422. };
  44423. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  44424. return this._textureMatrix;
  44425. };
  44426. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  44427. this._textureMatrix = value;
  44428. };
  44429. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  44430. var texture = BABYLON.SerializationHelper.Parse(function () {
  44431. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  44432. }, parsedTexture, scene);
  44433. // Animations
  44434. if (parsedTexture.animations) {
  44435. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  44436. var parsedAnimation = parsedTexture.animations[animationIndex];
  44437. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  44438. }
  44439. }
  44440. return texture;
  44441. };
  44442. CubeTexture.prototype.clone = function () {
  44443. var _this = this;
  44444. return BABYLON.SerializationHelper.Clone(function () {
  44445. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  44446. }, this);
  44447. };
  44448. return CubeTexture;
  44449. }(BABYLON.BaseTexture));
  44450. BABYLON.CubeTexture = CubeTexture;
  44451. })(BABYLON || (BABYLON = {}));
  44452. //# sourceMappingURL=babylon.cubeTexture.js.map
  44453. var BABYLON;
  44454. (function (BABYLON) {
  44455. var RenderTargetTexture = (function (_super) {
  44456. __extends(RenderTargetTexture, _super);
  44457. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  44458. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  44459. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  44460. if (isCube === void 0) { isCube = false; }
  44461. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44462. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  44463. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  44464. if (isMulti === void 0) { isMulti = false; }
  44465. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  44466. _this.isCube = isCube;
  44467. /**
  44468. * Use this list to define the list of mesh you want to render.
  44469. */
  44470. _this.renderList = new Array();
  44471. _this.renderParticles = true;
  44472. _this.renderSprites = false;
  44473. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  44474. _this.ignoreCameraViewport = false;
  44475. // Events
  44476. /**
  44477. * An event triggered when the texture is unbind.
  44478. * @type {BABYLON.Observable}
  44479. */
  44480. _this.onBeforeBindObservable = new BABYLON.Observable();
  44481. /**
  44482. * An event triggered when the texture is unbind.
  44483. * @type {BABYLON.Observable}
  44484. */
  44485. _this.onAfterUnbindObservable = new BABYLON.Observable();
  44486. /**
  44487. * An event triggered before rendering the texture
  44488. * @type {BABYLON.Observable}
  44489. */
  44490. _this.onBeforeRenderObservable = new BABYLON.Observable();
  44491. /**
  44492. * An event triggered after rendering the texture
  44493. * @type {BABYLON.Observable}
  44494. */
  44495. _this.onAfterRenderObservable = new BABYLON.Observable();
  44496. /**
  44497. * An event triggered after the texture clear
  44498. * @type {BABYLON.Observable}
  44499. */
  44500. _this.onClearObservable = new BABYLON.Observable();
  44501. _this._currentRefreshId = -1;
  44502. _this._refreshRate = 1;
  44503. _this._samples = 1;
  44504. scene = _this.getScene();
  44505. _this.name = name;
  44506. _this.isRenderTarget = true;
  44507. _this._size = size;
  44508. _this._generateMipMaps = generateMipMaps;
  44509. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  44510. // Rendering groups
  44511. _this._renderingManager = new BABYLON.RenderingManager(scene);
  44512. if (isMulti) {
  44513. return _this;
  44514. }
  44515. _this._renderTargetOptions = {
  44516. generateMipMaps: generateMipMaps,
  44517. type: type,
  44518. samplingMode: samplingMode,
  44519. generateDepthBuffer: generateDepthBuffer,
  44520. generateStencilBuffer: generateStencilBuffer
  44521. };
  44522. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  44523. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44524. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44525. }
  44526. if (isCube) {
  44527. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  44528. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  44529. _this._textureMatrix = BABYLON.Matrix.Identity();
  44530. }
  44531. else {
  44532. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  44533. }
  44534. return _this;
  44535. }
  44536. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  44537. get: function () {
  44538. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  44539. },
  44540. enumerable: true,
  44541. configurable: true
  44542. });
  44543. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  44544. get: function () {
  44545. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  44546. },
  44547. enumerable: true,
  44548. configurable: true
  44549. });
  44550. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  44551. get: function () {
  44552. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  44553. },
  44554. enumerable: true,
  44555. configurable: true
  44556. });
  44557. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  44558. set: function (callback) {
  44559. if (this._onAfterUnbindObserver) {
  44560. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  44561. }
  44562. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  44563. },
  44564. enumerable: true,
  44565. configurable: true
  44566. });
  44567. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  44568. set: function (callback) {
  44569. if (this._onBeforeRenderObserver) {
  44570. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  44571. }
  44572. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  44573. },
  44574. enumerable: true,
  44575. configurable: true
  44576. });
  44577. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  44578. set: function (callback) {
  44579. if (this._onAfterRenderObserver) {
  44580. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  44581. }
  44582. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  44583. },
  44584. enumerable: true,
  44585. configurable: true
  44586. });
  44587. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  44588. set: function (callback) {
  44589. if (this._onClearObserver) {
  44590. this.onClearObservable.remove(this._onClearObserver);
  44591. }
  44592. this._onClearObserver = this.onClearObservable.add(callback);
  44593. },
  44594. enumerable: true,
  44595. configurable: true
  44596. });
  44597. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  44598. get: function () {
  44599. return this._renderTargetOptions;
  44600. },
  44601. enumerable: true,
  44602. configurable: true
  44603. });
  44604. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  44605. get: function () {
  44606. return this._samples;
  44607. },
  44608. set: function (value) {
  44609. if (this._samples === value) {
  44610. return;
  44611. }
  44612. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  44613. },
  44614. enumerable: true,
  44615. configurable: true
  44616. });
  44617. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  44618. this._currentRefreshId = -1;
  44619. };
  44620. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  44621. get: function () {
  44622. return this._refreshRate;
  44623. },
  44624. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  44625. set: function (value) {
  44626. this._refreshRate = value;
  44627. this.resetRefreshCounter();
  44628. },
  44629. enumerable: true,
  44630. configurable: true
  44631. });
  44632. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  44633. if (!this._postProcessManager) {
  44634. this._postProcessManager = new BABYLON.PostProcessManager(this.getScene());
  44635. this._postProcesses = new Array();
  44636. }
  44637. this._postProcesses.push(postProcess);
  44638. this._postProcesses[0].autoClear = false;
  44639. };
  44640. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  44641. if (!this._postProcesses) {
  44642. return;
  44643. }
  44644. if (dispose) {
  44645. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  44646. var postProcess = _a[_i];
  44647. postProcess.dispose();
  44648. postProcess = null;
  44649. }
  44650. }
  44651. this._postProcesses = [];
  44652. };
  44653. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  44654. if (!this._postProcesses) {
  44655. return;
  44656. }
  44657. var index = this._postProcesses.indexOf(postProcess);
  44658. if (index === -1) {
  44659. return;
  44660. }
  44661. this._postProcesses.splice(index, 1);
  44662. if (this._postProcesses.length > 0) {
  44663. this._postProcesses[0].autoClear = false;
  44664. }
  44665. };
  44666. RenderTargetTexture.prototype._shouldRender = function () {
  44667. if (this._currentRefreshId === -1) {
  44668. this._currentRefreshId = 1;
  44669. return true;
  44670. }
  44671. if (this.refreshRate === this._currentRefreshId) {
  44672. this._currentRefreshId = 1;
  44673. return true;
  44674. }
  44675. this._currentRefreshId++;
  44676. return false;
  44677. };
  44678. RenderTargetTexture.prototype.isReady = function () {
  44679. if (!this.getScene().renderTargetsEnabled) {
  44680. return false;
  44681. }
  44682. return _super.prototype.isReady.call(this);
  44683. };
  44684. RenderTargetTexture.prototype.getRenderSize = function () {
  44685. return this._size;
  44686. };
  44687. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  44688. get: function () {
  44689. return true;
  44690. },
  44691. enumerable: true,
  44692. configurable: true
  44693. });
  44694. RenderTargetTexture.prototype.scale = function (ratio) {
  44695. var newSize = this._size * ratio;
  44696. this.resize(newSize);
  44697. };
  44698. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  44699. if (this.isCube) {
  44700. return this._textureMatrix;
  44701. }
  44702. return _super.prototype.getReflectionTextureMatrix.call(this);
  44703. };
  44704. RenderTargetTexture.prototype.resize = function (size) {
  44705. this.releaseInternalTexture();
  44706. if (this.isCube) {
  44707. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  44708. }
  44709. else {
  44710. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  44711. }
  44712. };
  44713. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  44714. var scene = this.getScene();
  44715. var engine = scene.getEngine();
  44716. if (this.useCameraPostProcesses !== undefined) {
  44717. useCameraPostProcess = this.useCameraPostProcesses;
  44718. }
  44719. if (this._waitingRenderList) {
  44720. this.renderList = [];
  44721. for (var index = 0; index < this._waitingRenderList.length; index++) {
  44722. var id = this._waitingRenderList[index];
  44723. this.renderList.push(scene.getMeshByID(id));
  44724. }
  44725. delete this._waitingRenderList;
  44726. }
  44727. // Is predicate defined?
  44728. if (this.renderListPredicate) {
  44729. this.renderList.splice(0); // Clear previous renderList
  44730. var sceneMeshes = this.getScene().meshes;
  44731. for (var index = 0; index < sceneMeshes.length; index++) {
  44732. var mesh = sceneMeshes[index];
  44733. if (this.renderListPredicate(mesh)) {
  44734. this.renderList.push(mesh);
  44735. }
  44736. }
  44737. }
  44738. if (this.renderList && this.renderList.length === 0) {
  44739. return;
  44740. }
  44741. this.onBeforeBindObservable.notifyObservers(this);
  44742. // Set custom projection.
  44743. // Needs to be before binding to prevent changing the aspect ratio.
  44744. var camera;
  44745. if (this.activeCamera) {
  44746. camera = this.activeCamera;
  44747. engine.setViewport(this.activeCamera.viewport, this._size, this._size);
  44748. if (this.activeCamera !== scene.activeCamera) {
  44749. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  44750. }
  44751. }
  44752. else {
  44753. camera = scene.activeCamera;
  44754. engine.setViewport(scene.activeCamera.viewport, this._size, this._size);
  44755. }
  44756. // Prepare renderingManager
  44757. this._renderingManager.reset();
  44758. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  44759. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  44760. var sceneRenderId = scene.getRenderId();
  44761. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  44762. var mesh = currentRenderList[meshIndex];
  44763. if (mesh) {
  44764. if (!mesh.isReady()) {
  44765. // Reset _currentRefreshId
  44766. this.resetRefreshCounter();
  44767. continue;
  44768. }
  44769. mesh._preActivateForIntermediateRendering(sceneRenderId);
  44770. var isMasked = void 0;
  44771. if (!this.renderList) {
  44772. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  44773. }
  44774. else {
  44775. isMasked = false;
  44776. }
  44777. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  44778. mesh._activate(sceneRenderId);
  44779. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  44780. var subMesh = mesh.subMeshes[subIndex];
  44781. scene._activeIndices.addCount(subMesh.indexCount, false);
  44782. this._renderingManager.dispatch(subMesh);
  44783. }
  44784. }
  44785. }
  44786. }
  44787. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  44788. var particleSystem = scene.particleSystems[particleIndex];
  44789. var emitter = particleSystem.emitter;
  44790. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  44791. continue;
  44792. }
  44793. if (currentRenderList.indexOf(emitter) >= 0) {
  44794. this._renderingManager.dispatchParticles(particleSystem);
  44795. }
  44796. }
  44797. if (this.isCube) {
  44798. for (var face = 0; face < 6; face++) {
  44799. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  44800. scene.incrementRenderId();
  44801. scene.resetCachedMaterial();
  44802. }
  44803. }
  44804. else {
  44805. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  44806. }
  44807. this.onAfterUnbindObservable.notifyObservers(this);
  44808. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  44809. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  44810. }
  44811. engine.setViewport(scene.activeCamera.viewport);
  44812. scene.resetCachedMaterial();
  44813. };
  44814. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  44815. var _this = this;
  44816. var scene = this.getScene();
  44817. var engine = scene.getEngine();
  44818. // Bind
  44819. if (this._postProcessManager) {
  44820. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  44821. }
  44822. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  44823. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  44824. }
  44825. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  44826. // Clear
  44827. if (this.onClearObservable.hasObservers()) {
  44828. this.onClearObservable.notifyObservers(engine);
  44829. }
  44830. else {
  44831. engine.clear(scene.clearColor, true, true, true);
  44832. }
  44833. if (!this._doNotChangeAspectRatio) {
  44834. scene.updateTransformMatrix(true);
  44835. }
  44836. // Render
  44837. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  44838. if (this._postProcessManager) {
  44839. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses);
  44840. }
  44841. else if (useCameraPostProcess) {
  44842. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  44843. }
  44844. if (!this._doNotChangeAspectRatio) {
  44845. scene.updateTransformMatrix(true);
  44846. }
  44847. // Dump ?
  44848. if (dumpForDebug) {
  44849. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  44850. }
  44851. // Unbind
  44852. if (!this.isCube || faceIndex === 5) {
  44853. if (this.isCube) {
  44854. if (faceIndex === 5) {
  44855. engine.generateMipMapsForCubemap(this._texture);
  44856. }
  44857. }
  44858. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  44859. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  44860. });
  44861. }
  44862. else {
  44863. this.onAfterRenderObservable.notifyObservers(faceIndex);
  44864. }
  44865. };
  44866. /**
  44867. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  44868. * This allowed control for front to back rendering or reversly depending of the special needs.
  44869. *
  44870. * @param renderingGroupId The rendering group id corresponding to its index
  44871. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  44872. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  44873. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  44874. */
  44875. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  44876. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  44877. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  44878. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  44879. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  44880. };
  44881. /**
  44882. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  44883. *
  44884. * @param renderingGroupId The rendering group id corresponding to its index
  44885. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  44886. */
  44887. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  44888. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  44889. };
  44890. RenderTargetTexture.prototype.clone = function () {
  44891. var textureSize = this.getSize();
  44892. 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);
  44893. // Base texture
  44894. newTexture.hasAlpha = this.hasAlpha;
  44895. newTexture.level = this.level;
  44896. // RenderTarget Texture
  44897. newTexture.coordinatesMode = this.coordinatesMode;
  44898. newTexture.renderList = this.renderList.slice(0);
  44899. return newTexture;
  44900. };
  44901. RenderTargetTexture.prototype.serialize = function () {
  44902. if (!this.name) {
  44903. return null;
  44904. }
  44905. var serializationObject = _super.prototype.serialize.call(this);
  44906. serializationObject.renderTargetSize = this.getRenderSize();
  44907. serializationObject.renderList = [];
  44908. for (var index = 0; index < this.renderList.length; index++) {
  44909. serializationObject.renderList.push(this.renderList[index].id);
  44910. }
  44911. return serializationObject;
  44912. };
  44913. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  44914. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  44915. this.getScene().getEngine()._releaseFramebufferObjects(this.getInternalTexture());
  44916. };
  44917. RenderTargetTexture.prototype.dispose = function () {
  44918. if (this._postProcessManager) {
  44919. this._postProcessManager.dispose();
  44920. this._postProcessManager = null;
  44921. }
  44922. this.clearPostProcesses(true);
  44923. this.renderList = null;
  44924. // Remove from custom render targets
  44925. var scene = this.getScene();
  44926. var index = scene.customRenderTargets.indexOf(this);
  44927. if (index >= 0) {
  44928. scene.customRenderTargets.splice(index, 1);
  44929. }
  44930. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  44931. var camera = _a[_i];
  44932. index = camera.customRenderTargets.indexOf(this);
  44933. if (index >= 0) {
  44934. camera.customRenderTargets.splice(index, 1);
  44935. }
  44936. }
  44937. _super.prototype.dispose.call(this);
  44938. };
  44939. return RenderTargetTexture;
  44940. }(BABYLON.Texture));
  44941. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  44942. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  44943. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  44944. BABYLON.RenderTargetTexture = RenderTargetTexture;
  44945. })(BABYLON || (BABYLON = {}));
  44946. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  44947. var BABYLON;
  44948. (function (BABYLON) {
  44949. ;
  44950. var MultiRenderTarget = (function (_super) {
  44951. __extends(MultiRenderTarget, _super);
  44952. function MultiRenderTarget(name, size, count, scene, options) {
  44953. var _this = this;
  44954. options = options || {};
  44955. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  44956. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  44957. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  44958. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  44959. if (!_this.isSupported) {
  44960. _this.dispose();
  44961. return;
  44962. }
  44963. var types = [];
  44964. var samplingModes = [];
  44965. for (var i = 0; i < count; i++) {
  44966. if (options.types && options.types[i]) {
  44967. types.push(options.types[i]);
  44968. }
  44969. else {
  44970. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  44971. }
  44972. if (options.samplingModes && options.samplingModes[i]) {
  44973. samplingModes.push(options.samplingModes[i]);
  44974. }
  44975. else {
  44976. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  44977. }
  44978. }
  44979. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  44980. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  44981. _this._count = count;
  44982. _this._size = size;
  44983. _this._multiRenderTargetOptions = {
  44984. samplingModes: samplingModes,
  44985. generateMipMaps: generateMipMaps,
  44986. generateDepthBuffer: generateDepthBuffer,
  44987. generateStencilBuffer: generateStencilBuffer,
  44988. generateDepthTexture: generateDepthTexture,
  44989. types: types,
  44990. textureCount: count
  44991. };
  44992. _this._webGLTextures = scene.getEngine().createMultipleRenderTarget(size, _this._multiRenderTargetOptions);
  44993. _this._createInternalTextures();
  44994. return _this;
  44995. }
  44996. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  44997. get: function () {
  44998. var engine = this.getScene().getEngine();
  44999. return engine.webGLVersion > 1 || engine.getCaps().drawBuffersExtension;
  45000. },
  45001. enumerable: true,
  45002. configurable: true
  45003. });
  45004. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  45005. get: function () {
  45006. return this._textures;
  45007. },
  45008. enumerable: true,
  45009. configurable: true
  45010. });
  45011. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  45012. get: function () {
  45013. return this._textures[this._textures.length - 1];
  45014. },
  45015. enumerable: true,
  45016. configurable: true
  45017. });
  45018. MultiRenderTarget.prototype._createInternalTextures = function () {
  45019. this._textures = [];
  45020. for (var i = 0; i < this._webGLTextures.length; i++) {
  45021. var texture = new BABYLON.Texture(null, this.getScene());
  45022. texture._texture = this._webGLTextures[i];
  45023. this._textures.push(texture);
  45024. }
  45025. // Keeps references to frame buffer and stencil/depth buffer
  45026. this._texture = this._webGLTextures[0];
  45027. };
  45028. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  45029. get: function () {
  45030. return this._samples;
  45031. },
  45032. set: function (value) {
  45033. if (this._samples === value) {
  45034. return;
  45035. }
  45036. for (var i = 0; i < this._webGLTextures.length; i++) {
  45037. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._webGLTextures[i], value);
  45038. }
  45039. },
  45040. enumerable: true,
  45041. configurable: true
  45042. });
  45043. MultiRenderTarget.prototype.resize = function (size) {
  45044. this.releaseInternalTextures();
  45045. this._webGLTextures = this.getScene().getEngine().createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  45046. this._createInternalTextures();
  45047. };
  45048. MultiRenderTarget.prototype.dispose = function () {
  45049. this.releaseInternalTextures();
  45050. _super.prototype.dispose.call(this);
  45051. };
  45052. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  45053. if (!this._webGLTextures) {
  45054. return;
  45055. }
  45056. for (var i = this._webGLTextures.length - 1; i >= 0; i--) {
  45057. if (this._webGLTextures[i] !== undefined) {
  45058. this.getScene().getEngine().releaseInternalTexture(this._webGLTextures[i]);
  45059. this._webGLTextures.splice(i, 1);
  45060. }
  45061. }
  45062. };
  45063. return MultiRenderTarget;
  45064. }(BABYLON.RenderTargetTexture));
  45065. BABYLON.MultiRenderTarget = MultiRenderTarget;
  45066. })(BABYLON || (BABYLON = {}));
  45067. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  45068. /// <reference path="babylon.renderTargetTexture.ts" />
  45069. var BABYLON;
  45070. (function (BABYLON) {
  45071. var MirrorTexture = (function (_super) {
  45072. __extends(MirrorTexture, _super);
  45073. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  45074. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  45075. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  45076. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  45077. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  45078. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  45079. _this._transformMatrix = BABYLON.Matrix.Zero();
  45080. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  45081. _this._blurKernelX = 0;
  45082. _this._blurKernelY = 0;
  45083. _this._blurRatio = 1.0;
  45084. _this.onBeforeRenderObservable.add(function () {
  45085. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  45086. _this._savedViewMatrix = scene.getViewMatrix();
  45087. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  45088. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  45089. scene.clipPlane = _this.mirrorPlane;
  45090. scene.getEngine().cullBackFaces = false;
  45091. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  45092. });
  45093. _this.onAfterRenderObservable.add(function () {
  45094. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  45095. scene.getEngine().cullBackFaces = true;
  45096. scene._mirroredCameraPosition = null;
  45097. delete scene.clipPlane;
  45098. });
  45099. return _this;
  45100. }
  45101. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  45102. get: function () {
  45103. return this._blurRatio;
  45104. },
  45105. set: function (value) {
  45106. if (this._blurRatio === value) {
  45107. return;
  45108. }
  45109. this._blurRatio = value;
  45110. this._preparePostProcesses();
  45111. },
  45112. enumerable: true,
  45113. configurable: true
  45114. });
  45115. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  45116. set: function (value) {
  45117. this.blurKernelX = value;
  45118. this.blurKernelY = value;
  45119. },
  45120. enumerable: true,
  45121. configurable: true
  45122. });
  45123. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  45124. get: function () {
  45125. return this._blurKernelX;
  45126. },
  45127. set: function (value) {
  45128. if (this._blurKernelX === value) {
  45129. return;
  45130. }
  45131. this._blurKernelX = value;
  45132. this._preparePostProcesses();
  45133. },
  45134. enumerable: true,
  45135. configurable: true
  45136. });
  45137. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  45138. get: function () {
  45139. return this._blurKernelY;
  45140. },
  45141. set: function (value) {
  45142. if (this._blurKernelY === value) {
  45143. return;
  45144. }
  45145. this._blurKernelY = value;
  45146. this._preparePostProcesses();
  45147. },
  45148. enumerable: true,
  45149. configurable: true
  45150. });
  45151. MirrorTexture.prototype._preparePostProcesses = function () {
  45152. this.clearPostProcesses(true);
  45153. if (this._blurKernelX && this._blurKernelY) {
  45154. var engine = this.getScene().getEngine();
  45155. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  45156. 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);
  45157. this._blurX.autoClear = false;
  45158. if (this._blurRatio === 1 && this.samples < 2) {
  45159. this._blurX.outputTexture = this._texture;
  45160. }
  45161. else {
  45162. this._blurX.alwaysForcePOT = true;
  45163. }
  45164. 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);
  45165. this._blurY.autoClear = false;
  45166. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  45167. this.addPostProcess(this._blurX);
  45168. this.addPostProcess(this._blurY);
  45169. }
  45170. };
  45171. MirrorTexture.prototype.clone = function () {
  45172. var textureSize = this.getSize();
  45173. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  45174. // Base texture
  45175. newTexture.hasAlpha = this.hasAlpha;
  45176. newTexture.level = this.level;
  45177. // Mirror Texture
  45178. newTexture.mirrorPlane = this.mirrorPlane.clone();
  45179. newTexture.renderList = this.renderList.slice(0);
  45180. return newTexture;
  45181. };
  45182. MirrorTexture.prototype.serialize = function () {
  45183. if (!this.name) {
  45184. return null;
  45185. }
  45186. var serializationObject = _super.prototype.serialize.call(this);
  45187. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  45188. return serializationObject;
  45189. };
  45190. return MirrorTexture;
  45191. }(BABYLON.RenderTargetTexture));
  45192. BABYLON.MirrorTexture = MirrorTexture;
  45193. })(BABYLON || (BABYLON = {}));
  45194. //# sourceMappingURL=babylon.mirrorTexture.js.map
  45195. /// <reference path="babylon.renderTargetTexture.ts" />
  45196. var BABYLON;
  45197. (function (BABYLON) {
  45198. /**
  45199. * Creates a refraction texture used by refraction channel of the standard material.
  45200. * @param name the texture name
  45201. * @param size size of the underlying texture
  45202. * @param scene root scene
  45203. */
  45204. var RefractionTexture = (function (_super) {
  45205. __extends(RefractionTexture, _super);
  45206. function RefractionTexture(name, size, scene, generateMipMaps) {
  45207. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  45208. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  45209. _this.depth = 2.0;
  45210. _this.onBeforeRenderObservable.add(function () {
  45211. scene.clipPlane = _this.refractionPlane;
  45212. });
  45213. _this.onAfterRenderObservable.add(function () {
  45214. delete scene.clipPlane;
  45215. });
  45216. return _this;
  45217. }
  45218. RefractionTexture.prototype.clone = function () {
  45219. var textureSize = this.getSize();
  45220. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  45221. // Base texture
  45222. newTexture.hasAlpha = this.hasAlpha;
  45223. newTexture.level = this.level;
  45224. // Refraction Texture
  45225. newTexture.refractionPlane = this.refractionPlane.clone();
  45226. newTexture.renderList = this.renderList.slice(0);
  45227. newTexture.depth = this.depth;
  45228. return newTexture;
  45229. };
  45230. RefractionTexture.prototype.serialize = function () {
  45231. if (!this.name) {
  45232. return null;
  45233. }
  45234. var serializationObject = _super.prototype.serialize.call(this);
  45235. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  45236. serializationObject.depth = this.depth;
  45237. return serializationObject;
  45238. };
  45239. return RefractionTexture;
  45240. }(BABYLON.RenderTargetTexture));
  45241. BABYLON.RefractionTexture = RefractionTexture;
  45242. })(BABYLON || (BABYLON = {}));
  45243. //# sourceMappingURL=babylon.refractionTexture.js.map
  45244. /// <reference path="babylon.texture.ts" />
  45245. var BABYLON;
  45246. (function (BABYLON) {
  45247. var DynamicTexture = (function (_super) {
  45248. __extends(DynamicTexture, _super);
  45249. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  45250. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45251. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  45252. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  45253. _this.name = name;
  45254. var engine = _this.getScene().getEngine();
  45255. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45256. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45257. _this._generateMipMaps = generateMipMaps;
  45258. if (options.getContext) {
  45259. _this._canvas = options;
  45260. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  45261. }
  45262. else {
  45263. _this._canvas = document.createElement("canvas");
  45264. if (options.width) {
  45265. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  45266. }
  45267. else {
  45268. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  45269. }
  45270. }
  45271. var textureSize = _this.getSize();
  45272. _this._canvas.width = textureSize.width;
  45273. _this._canvas.height = textureSize.height;
  45274. _this._context = _this._canvas.getContext("2d");
  45275. return _this;
  45276. }
  45277. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  45278. get: function () {
  45279. return true;
  45280. },
  45281. enumerable: true,
  45282. configurable: true
  45283. });
  45284. DynamicTexture.prototype._recreate = function (textureSize) {
  45285. this._canvas.width = textureSize.width;
  45286. this._canvas.height = textureSize.height;
  45287. this.releaseInternalTexture();
  45288. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  45289. };
  45290. DynamicTexture.prototype.scale = function (ratio) {
  45291. var textureSize = this.getSize();
  45292. textureSize.width *= ratio;
  45293. textureSize.height *= ratio;
  45294. this._recreate(textureSize);
  45295. };
  45296. DynamicTexture.prototype.scaleTo = function (width, height) {
  45297. var textureSize = this.getSize();
  45298. textureSize.width = width;
  45299. textureSize.height = height;
  45300. this._recreate(textureSize);
  45301. };
  45302. DynamicTexture.prototype.getContext = function () {
  45303. return this._context;
  45304. };
  45305. DynamicTexture.prototype.clear = function () {
  45306. var size = this.getSize();
  45307. this._context.fillRect(0, 0, size.width, size.height);
  45308. };
  45309. DynamicTexture.prototype.update = function (invertY) {
  45310. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  45311. };
  45312. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  45313. if (update === void 0) { update = true; }
  45314. var size = this.getSize();
  45315. if (clearColor) {
  45316. this._context.fillStyle = clearColor;
  45317. this._context.fillRect(0, 0, size.width, size.height);
  45318. }
  45319. this._context.font = font;
  45320. if (x === null || x === undefined) {
  45321. var textSize = this._context.measureText(text);
  45322. x = (size.width - textSize.width) / 2;
  45323. }
  45324. if (y === null || y === undefined) {
  45325. var fontSize = parseInt((font.replace(/\D/g, '')));
  45326. ;
  45327. y = (size.height / 2) + (fontSize / 3.65);
  45328. }
  45329. this._context.fillStyle = color;
  45330. this._context.fillText(text, x, y);
  45331. if (update) {
  45332. this.update(invertY);
  45333. }
  45334. };
  45335. DynamicTexture.prototype.clone = function () {
  45336. var textureSize = this.getSize();
  45337. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  45338. // Base texture
  45339. newTexture.hasAlpha = this.hasAlpha;
  45340. newTexture.level = this.level;
  45341. // Dynamic Texture
  45342. newTexture.wrapU = this.wrapU;
  45343. newTexture.wrapV = this.wrapV;
  45344. return newTexture;
  45345. };
  45346. return DynamicTexture;
  45347. }(BABYLON.Texture));
  45348. BABYLON.DynamicTexture = DynamicTexture;
  45349. })(BABYLON || (BABYLON = {}));
  45350. //# sourceMappingURL=babylon.dynamicTexture.js.map
  45351. var BABYLON;
  45352. (function (BABYLON) {
  45353. var VideoTexture = (function (_super) {
  45354. __extends(VideoTexture, _super);
  45355. /**
  45356. * Creates a video texture.
  45357. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  45358. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  45359. * @param {BABYLON.Scene} scene is obviously the current scene.
  45360. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  45361. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  45362. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  45363. */
  45364. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  45365. if (generateMipMaps === void 0) { generateMipMaps = false; }
  45366. if (invertY === void 0) { invertY = false; }
  45367. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45368. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  45369. _this._autoLaunch = true;
  45370. var urls;
  45371. _this.name = name;
  45372. if (urlsOrVideo instanceof HTMLVideoElement) {
  45373. _this.video = urlsOrVideo;
  45374. }
  45375. else {
  45376. urls = urlsOrVideo;
  45377. _this.video = document.createElement("video");
  45378. _this.video.autoplay = false;
  45379. _this.video.loop = true;
  45380. }
  45381. _this._generateMipMaps = generateMipMaps;
  45382. _this._samplingMode = samplingMode;
  45383. if (!_this.getScene().getEngine().needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  45384. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  45385. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  45386. }
  45387. else {
  45388. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45389. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45390. _this._generateMipMaps = false;
  45391. }
  45392. if (urls) {
  45393. _this.video.addEventListener("canplay", function () {
  45394. _this._createTexture();
  45395. });
  45396. urls.forEach(function (url) {
  45397. var source = document.createElement("source");
  45398. source.src = url;
  45399. _this.video.appendChild(source);
  45400. });
  45401. }
  45402. else {
  45403. _this._createTexture();
  45404. }
  45405. _this._lastUpdate = BABYLON.Tools.Now;
  45406. return _this;
  45407. }
  45408. VideoTexture.prototype.__setTextureReady = function () {
  45409. this._texture.isReady = true;
  45410. };
  45411. VideoTexture.prototype._createTexture = function () {
  45412. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  45413. if (this._autoLaunch) {
  45414. this._autoLaunch = false;
  45415. this.video.play();
  45416. }
  45417. this._setTextureReady = this.__setTextureReady.bind(this);
  45418. this.video.addEventListener("playing", this._setTextureReady);
  45419. };
  45420. VideoTexture.prototype.update = function () {
  45421. var now = BABYLON.Tools.Now;
  45422. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  45423. return false;
  45424. }
  45425. this._lastUpdate = now;
  45426. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  45427. return true;
  45428. };
  45429. VideoTexture.prototype.dispose = function () {
  45430. _super.prototype.dispose.call(this);
  45431. this.video.removeEventListener("playing", this._setTextureReady);
  45432. };
  45433. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  45434. var video = document.createElement("video");
  45435. var constraintsDeviceId;
  45436. if (constraints && constraints.deviceId) {
  45437. constraintsDeviceId = {
  45438. exact: constraints.deviceId
  45439. };
  45440. }
  45441. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  45442. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  45443. if (navigator.getUserMedia) {
  45444. navigator.getUserMedia({
  45445. video: {
  45446. deviceId: constraintsDeviceId,
  45447. width: {
  45448. min: (constraints && constraints.minWidth) || 256,
  45449. max: (constraints && constraints.maxWidth) || 640
  45450. },
  45451. height: {
  45452. min: (constraints && constraints.minHeight) || 256,
  45453. max: (constraints && constraints.maxHeight) || 480
  45454. }
  45455. }
  45456. }, function (stream) {
  45457. if (video.mozSrcObject !== undefined) {
  45458. video.mozSrcObject = stream;
  45459. }
  45460. else {
  45461. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  45462. }
  45463. video.play();
  45464. if (onReady) {
  45465. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  45466. }
  45467. }, function (e) {
  45468. BABYLON.Tools.Error(e.name);
  45469. });
  45470. }
  45471. };
  45472. return VideoTexture;
  45473. }(BABYLON.Texture));
  45474. BABYLON.VideoTexture = VideoTexture;
  45475. })(BABYLON || (BABYLON = {}));
  45476. //# sourceMappingURL=babylon.videoTexture.js.map
  45477. var BABYLON;
  45478. (function (BABYLON) {
  45479. var RawTexture = (function (_super) {
  45480. __extends(RawTexture, _super);
  45481. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  45482. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45483. if (invertY === void 0) { invertY = false; }
  45484. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45485. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  45486. _this.format = format;
  45487. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  45488. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45489. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45490. return _this;
  45491. }
  45492. RawTexture.prototype.update = function (data) {
  45493. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  45494. };
  45495. // Statics
  45496. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45497. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45498. if (invertY === void 0) { invertY = false; }
  45499. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45500. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  45501. };
  45502. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45503. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45504. if (invertY === void 0) { invertY = false; }
  45505. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45506. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  45507. };
  45508. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45509. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45510. if (invertY === void 0) { invertY = false; }
  45511. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45512. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  45513. };
  45514. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45515. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45516. if (invertY === void 0) { invertY = false; }
  45517. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45518. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  45519. };
  45520. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45521. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45522. if (invertY === void 0) { invertY = false; }
  45523. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45524. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  45525. };
  45526. return RawTexture;
  45527. }(BABYLON.Texture));
  45528. BABYLON.RawTexture = RawTexture;
  45529. })(BABYLON || (BABYLON = {}));
  45530. //# sourceMappingURL=babylon.rawTexture.js.map
  45531. var BABYLON;
  45532. (function (BABYLON) {
  45533. var PostProcess = (function () {
  45534. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  45535. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  45536. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  45537. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  45538. if (blockCompilation === void 0) { blockCompilation = false; }
  45539. this.name = name;
  45540. this.width = -1;
  45541. this.height = -1;
  45542. this.autoClear = true;
  45543. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  45544. /*
  45545. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  45546. Can only be used on a single postprocess or on the last one of a chain.
  45547. */
  45548. this.enablePixelPerfectMode = false;
  45549. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  45550. this.alwaysForcePOT = false;
  45551. this.samples = 1;
  45552. this._reusable = false;
  45553. this._textures = new BABYLON.SmartArray(2);
  45554. this._currentRenderTextureInd = 0;
  45555. this._scaleRatio = new BABYLON.Vector2(1, 1);
  45556. this._texelSize = BABYLON.Vector2.Zero();
  45557. // Events
  45558. /**
  45559. * An event triggered when the postprocess is activated.
  45560. * @type {BABYLON.Observable}
  45561. */
  45562. this.onActivateObservable = new BABYLON.Observable();
  45563. /**
  45564. * An event triggered when the postprocess changes its size.
  45565. * @type {BABYLON.Observable}
  45566. */
  45567. this.onSizeChangedObservable = new BABYLON.Observable();
  45568. /**
  45569. * An event triggered when the postprocess applies its effect.
  45570. * @type {BABYLON.Observable}
  45571. */
  45572. this.onApplyObservable = new BABYLON.Observable();
  45573. /**
  45574. * An event triggered before rendering the postprocess
  45575. * @type {BABYLON.Observable}
  45576. */
  45577. this.onBeforeRenderObservable = new BABYLON.Observable();
  45578. /**
  45579. * An event triggered after rendering the postprocess
  45580. * @type {BABYLON.Observable}
  45581. */
  45582. this.onAfterRenderObservable = new BABYLON.Observable();
  45583. if (camera != null) {
  45584. this._camera = camera;
  45585. this._scene = camera.getScene();
  45586. camera.attachPostProcess(this);
  45587. this._engine = this._scene.getEngine();
  45588. }
  45589. else {
  45590. this._engine = engine;
  45591. }
  45592. this._options = options;
  45593. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  45594. this._reusable = reusable || false;
  45595. this._textureType = textureType;
  45596. this._samplers = samplers || [];
  45597. this._samplers.push("textureSampler");
  45598. this._fragmentUrl = fragmentUrl;
  45599. this._vertexUrl = vertexUrl;
  45600. this._parameters = parameters || [];
  45601. this._parameters.push("scale");
  45602. this._indexParameters = indexParameters;
  45603. if (!blockCompilation) {
  45604. this.updateEffect(defines);
  45605. }
  45606. }
  45607. Object.defineProperty(PostProcess.prototype, "onActivate", {
  45608. set: function (callback) {
  45609. if (this._onActivateObserver) {
  45610. this.onActivateObservable.remove(this._onActivateObserver);
  45611. }
  45612. this._onActivateObserver = this.onActivateObservable.add(callback);
  45613. },
  45614. enumerable: true,
  45615. configurable: true
  45616. });
  45617. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  45618. set: function (callback) {
  45619. if (this._onSizeChangedObserver) {
  45620. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  45621. }
  45622. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  45623. },
  45624. enumerable: true,
  45625. configurable: true
  45626. });
  45627. Object.defineProperty(PostProcess.prototype, "onApply", {
  45628. set: function (callback) {
  45629. if (this._onApplyObserver) {
  45630. this.onApplyObservable.remove(this._onApplyObserver);
  45631. }
  45632. this._onApplyObserver = this.onApplyObservable.add(callback);
  45633. },
  45634. enumerable: true,
  45635. configurable: true
  45636. });
  45637. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  45638. set: function (callback) {
  45639. if (this._onBeforeRenderObserver) {
  45640. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  45641. }
  45642. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  45643. },
  45644. enumerable: true,
  45645. configurable: true
  45646. });
  45647. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  45648. set: function (callback) {
  45649. if (this._onAfterRenderObserver) {
  45650. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  45651. }
  45652. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  45653. },
  45654. enumerable: true,
  45655. configurable: true
  45656. });
  45657. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  45658. get: function () {
  45659. return this._textures.data[this._currentRenderTextureInd];
  45660. },
  45661. set: function (value) {
  45662. this._forcedOutputTexture = value;
  45663. },
  45664. enumerable: true,
  45665. configurable: true
  45666. });
  45667. PostProcess.prototype.getCamera = function () {
  45668. return this._camera;
  45669. };
  45670. Object.defineProperty(PostProcess.prototype, "texelSize", {
  45671. get: function () {
  45672. if (this._shareOutputWithPostProcess) {
  45673. return this._shareOutputWithPostProcess.texelSize;
  45674. }
  45675. if (this._forcedOutputTexture) {
  45676. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture._width, 1.0 / this._forcedOutputTexture._height);
  45677. }
  45678. return this._texelSize;
  45679. },
  45680. enumerable: true,
  45681. configurable: true
  45682. });
  45683. PostProcess.prototype.getEngine = function () {
  45684. return this._engine;
  45685. };
  45686. PostProcess.prototype.getEffect = function () {
  45687. return this._effect;
  45688. };
  45689. PostProcess.prototype.shareOutputWith = function (postProcess) {
  45690. this._disposeTextures();
  45691. this._shareOutputWithPostProcess = postProcess;
  45692. return this;
  45693. };
  45694. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  45695. 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);
  45696. };
  45697. PostProcess.prototype.isReusable = function () {
  45698. return this._reusable;
  45699. };
  45700. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  45701. PostProcess.prototype.markTextureDirty = function () {
  45702. this.width = -1;
  45703. };
  45704. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  45705. var _this = this;
  45706. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  45707. camera = camera || this._camera;
  45708. var scene = camera.getScene();
  45709. var engine = scene.getEngine();
  45710. var maxSize = engine.getCaps().maxTextureSize;
  45711. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  45712. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  45713. var desiredWidth = this._options.width || requiredWidth;
  45714. var desiredHeight = this._options.height || requiredHeight;
  45715. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  45716. if (!this._options.width) {
  45717. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  45718. }
  45719. if (!this._options.height) {
  45720. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  45721. }
  45722. }
  45723. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  45724. if (this._textures.length > 0) {
  45725. for (var i = 0; i < this._textures.length; i++) {
  45726. this._engine._releaseTexture(this._textures.data[i]);
  45727. }
  45728. this._textures.reset();
  45729. }
  45730. this.width = desiredWidth;
  45731. this.height = desiredHeight;
  45732. var textureSize = { width: this.width, height: this.height };
  45733. var textureOptions = {
  45734. generateMipMaps: false,
  45735. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  45736. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  45737. samplingMode: this.renderTargetSamplingMode,
  45738. type: this._textureType
  45739. };
  45740. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  45741. if (this._reusable) {
  45742. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  45743. }
  45744. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  45745. this.onSizeChangedObservable.notifyObservers(this);
  45746. }
  45747. this._textures.forEach(function (texture) {
  45748. if (texture.samples !== _this.samples) {
  45749. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  45750. }
  45751. });
  45752. }
  45753. var target;
  45754. if (this._shareOutputWithPostProcess) {
  45755. target = this._shareOutputWithPostProcess.outputTexture;
  45756. }
  45757. else if (this._forcedOutputTexture) {
  45758. target = this._forcedOutputTexture;
  45759. this.width = this._forcedOutputTexture._width;
  45760. this.height = this._forcedOutputTexture._height;
  45761. }
  45762. else {
  45763. target = this.outputTexture;
  45764. }
  45765. if (this.enablePixelPerfectMode) {
  45766. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  45767. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  45768. }
  45769. else {
  45770. this._scaleRatio.copyFromFloats(1, 1);
  45771. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  45772. }
  45773. this.onActivateObservable.notifyObservers(camera);
  45774. // Clear
  45775. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  45776. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  45777. }
  45778. if (this._reusable) {
  45779. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  45780. }
  45781. };
  45782. Object.defineProperty(PostProcess.prototype, "isSupported", {
  45783. get: function () {
  45784. return this._effect.isSupported;
  45785. },
  45786. enumerable: true,
  45787. configurable: true
  45788. });
  45789. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  45790. get: function () {
  45791. if (this._shareOutputWithPostProcess) {
  45792. return this._shareOutputWithPostProcess.aspectRatio;
  45793. }
  45794. if (this._forcedOutputTexture) {
  45795. var size = this._forcedOutputTexture._width / this._forcedOutputTexture._height;
  45796. }
  45797. return this.width / this.height;
  45798. },
  45799. enumerable: true,
  45800. configurable: true
  45801. });
  45802. PostProcess.prototype.apply = function () {
  45803. // Check
  45804. if (!this._effect || !this._effect.isReady())
  45805. return null;
  45806. // States
  45807. this._engine.enableEffect(this._effect);
  45808. this._engine.setState(false);
  45809. this._engine.setDepthBuffer(false);
  45810. this._engine.setDepthWrite(false);
  45811. // Alpha
  45812. this._engine.setAlphaMode(this.alphaMode);
  45813. if (this.alphaConstants) {
  45814. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  45815. }
  45816. // Texture
  45817. var source;
  45818. if (this._shareOutputWithPostProcess) {
  45819. source = this._shareOutputWithPostProcess.outputTexture;
  45820. }
  45821. else if (this._forcedOutputTexture) {
  45822. source = this._forcedOutputTexture;
  45823. }
  45824. else {
  45825. source = this.outputTexture;
  45826. }
  45827. this._effect._bindTexture("textureSampler", source);
  45828. // Parameters
  45829. this._effect.setVector2("scale", this._scaleRatio);
  45830. this.onApplyObservable.notifyObservers(this._effect);
  45831. return this._effect;
  45832. };
  45833. PostProcess.prototype._disposeTextures = function () {
  45834. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  45835. return;
  45836. }
  45837. if (this._textures.length > 0) {
  45838. for (var i = 0; i < this._textures.length; i++) {
  45839. this._engine._releaseTexture(this._textures.data[i]);
  45840. }
  45841. }
  45842. this._textures.dispose();
  45843. };
  45844. PostProcess.prototype.dispose = function (camera) {
  45845. camera = camera || this._camera;
  45846. this._disposeTextures();
  45847. if (!camera) {
  45848. return;
  45849. }
  45850. camera.detachPostProcess(this);
  45851. var index = camera._postProcesses.indexOf(this);
  45852. if (index === 0 && camera._postProcesses.length > 0) {
  45853. this._camera._postProcesses[0].markTextureDirty();
  45854. }
  45855. this.onActivateObservable.clear();
  45856. this.onAfterRenderObservable.clear();
  45857. this.onApplyObservable.clear();
  45858. this.onBeforeRenderObservable.clear();
  45859. this.onSizeChangedObservable.clear();
  45860. };
  45861. return PostProcess;
  45862. }());
  45863. BABYLON.PostProcess = PostProcess;
  45864. })(BABYLON || (BABYLON = {}));
  45865. //# sourceMappingURL=babylon.postProcess.js.map
  45866. var BABYLON;
  45867. (function (BABYLON) {
  45868. var PassPostProcess = (function (_super) {
  45869. __extends(PassPostProcess, _super);
  45870. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  45871. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  45872. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  45873. }
  45874. return PassPostProcess;
  45875. }(BABYLON.PostProcess));
  45876. BABYLON.PassPostProcess = PassPostProcess;
  45877. })(BABYLON || (BABYLON = {}));
  45878. //# sourceMappingURL=babylon.passPostProcess.js.map
  45879. var BABYLON;
  45880. (function (BABYLON) {
  45881. var ShadowGenerator = (function () {
  45882. /**
  45883. * Creates a ShadowGenerator object.
  45884. * A ShadowGenerator is the required tool to use the shadows.
  45885. * Each light casting shadows needs to use its own ShadowGenerator.
  45886. * Required parameters :
  45887. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  45888. * - `light`: the light object generating the shadows.
  45889. * - `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.
  45890. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  45891. */
  45892. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  45893. // Members
  45894. this._bias = 0.00005;
  45895. this._blurBoxOffset = 1;
  45896. this._blurScale = 2;
  45897. this._blurKernel = 1;
  45898. this._useKernelBlur = false;
  45899. this._filter = ShadowGenerator.FILTER_NONE;
  45900. this._darkness = 0;
  45901. this._transparencyShadow = false;
  45902. /**
  45903. * Controls the extent to which the shadows fade out at the edge of the frustum
  45904. * Used only by directionals and spots
  45905. */
  45906. this.frustumEdgeFalloff = 0;
  45907. this.forceBackFacesOnly = false;
  45908. this._lightDirection = BABYLON.Vector3.Zero();
  45909. this._viewMatrix = BABYLON.Matrix.Zero();
  45910. this._projectionMatrix = BABYLON.Matrix.Zero();
  45911. this._transformMatrix = BABYLON.Matrix.Zero();
  45912. this._worldViewProjection = BABYLON.Matrix.Zero();
  45913. this._currentFaceIndex = 0;
  45914. this._currentFaceIndexCache = 0;
  45915. this._isCube = false;
  45916. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  45917. this._mapSize = mapSize;
  45918. this._light = light;
  45919. this._scene = light.getScene();
  45920. light._shadowGenerator = this;
  45921. // Texture type fallback from float to int if not supported.
  45922. var caps = this._scene.getEngine().getCaps();
  45923. if (!useFullFloatFirst) {
  45924. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  45925. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  45926. }
  45927. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  45928. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  45929. }
  45930. else {
  45931. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  45932. }
  45933. }
  45934. else {
  45935. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  45936. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  45937. }
  45938. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  45939. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  45940. }
  45941. else {
  45942. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  45943. }
  45944. }
  45945. this._initializeGenerator();
  45946. }
  45947. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  45948. // Static
  45949. get: function () {
  45950. return ShadowGenerator._FILTER_NONE;
  45951. },
  45952. enumerable: true,
  45953. configurable: true
  45954. });
  45955. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  45956. get: function () {
  45957. return ShadowGenerator._FILTER_POISSONSAMPLING;
  45958. },
  45959. enumerable: true,
  45960. configurable: true
  45961. });
  45962. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  45963. get: function () {
  45964. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  45965. },
  45966. enumerable: true,
  45967. configurable: true
  45968. });
  45969. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  45970. get: function () {
  45971. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  45972. },
  45973. enumerable: true,
  45974. configurable: true
  45975. });
  45976. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  45977. get: function () {
  45978. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  45979. },
  45980. enumerable: true,
  45981. configurable: true
  45982. });
  45983. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  45984. get: function () {
  45985. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  45986. },
  45987. enumerable: true,
  45988. configurable: true
  45989. });
  45990. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  45991. get: function () {
  45992. return this._bias;
  45993. },
  45994. set: function (bias) {
  45995. this._bias = bias;
  45996. },
  45997. enumerable: true,
  45998. configurable: true
  45999. });
  46000. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  46001. get: function () {
  46002. return this._blurBoxOffset;
  46003. },
  46004. set: function (value) {
  46005. if (this._blurBoxOffset === value) {
  46006. return;
  46007. }
  46008. this._blurBoxOffset = value;
  46009. this._disposeBlurPostProcesses();
  46010. },
  46011. enumerable: true,
  46012. configurable: true
  46013. });
  46014. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  46015. get: function () {
  46016. return this._blurScale;
  46017. },
  46018. set: function (value) {
  46019. if (this._blurScale === value) {
  46020. return;
  46021. }
  46022. this._blurScale = value;
  46023. this._disposeBlurPostProcesses();
  46024. },
  46025. enumerable: true,
  46026. configurable: true
  46027. });
  46028. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  46029. get: function () {
  46030. return this._blurKernel;
  46031. },
  46032. set: function (value) {
  46033. if (this._blurKernel === value) {
  46034. return;
  46035. }
  46036. this._blurKernel = value;
  46037. this._disposeBlurPostProcesses();
  46038. },
  46039. enumerable: true,
  46040. configurable: true
  46041. });
  46042. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  46043. get: function () {
  46044. return this._useKernelBlur;
  46045. },
  46046. set: function (value) {
  46047. if (this._useKernelBlur === value) {
  46048. return;
  46049. }
  46050. this._useKernelBlur = value;
  46051. this._disposeBlurPostProcesses();
  46052. },
  46053. enumerable: true,
  46054. configurable: true
  46055. });
  46056. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  46057. get: function () {
  46058. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  46059. },
  46060. set: function (value) {
  46061. this._depthScale = value;
  46062. },
  46063. enumerable: true,
  46064. configurable: true
  46065. });
  46066. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  46067. get: function () {
  46068. return this._filter;
  46069. },
  46070. set: function (value) {
  46071. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  46072. if (this._light.needCube()) {
  46073. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  46074. this.useExponentialShadowMap = true;
  46075. return;
  46076. }
  46077. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  46078. this.useCloseExponentialShadowMap = true;
  46079. return;
  46080. }
  46081. }
  46082. if (this._filter === value) {
  46083. return;
  46084. }
  46085. this._filter = value;
  46086. this._disposeBlurPostProcesses();
  46087. this._applyFilterValues();
  46088. this._light._markMeshesAsLightDirty();
  46089. },
  46090. enumerable: true,
  46091. configurable: true
  46092. });
  46093. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  46094. get: function () {
  46095. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  46096. },
  46097. set: function (value) {
  46098. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  46099. },
  46100. enumerable: true,
  46101. configurable: true
  46102. });
  46103. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  46104. get: function () {
  46105. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  46106. return this.useExponentialShadowMap;
  46107. },
  46108. set: function (value) {
  46109. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  46110. this.useExponentialShadowMap = value;
  46111. },
  46112. enumerable: true,
  46113. configurable: true
  46114. });
  46115. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  46116. get: function () {
  46117. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  46118. return this.useBlurExponentialShadowMap;
  46119. },
  46120. set: function (value) {
  46121. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  46122. this.useBlurExponentialShadowMap = value;
  46123. },
  46124. enumerable: true,
  46125. configurable: true
  46126. });
  46127. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  46128. get: function () {
  46129. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  46130. },
  46131. set: function (value) {
  46132. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  46133. },
  46134. enumerable: true,
  46135. configurable: true
  46136. });
  46137. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  46138. get: function () {
  46139. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  46140. },
  46141. set: function (value) {
  46142. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  46143. },
  46144. enumerable: true,
  46145. configurable: true
  46146. });
  46147. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  46148. get: function () {
  46149. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  46150. },
  46151. set: function (value) {
  46152. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  46153. },
  46154. enumerable: true,
  46155. configurable: true
  46156. });
  46157. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  46158. get: function () {
  46159. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  46160. },
  46161. set: function (value) {
  46162. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  46163. },
  46164. enumerable: true,
  46165. configurable: true
  46166. });
  46167. /**
  46168. * Returns the darkness value (float).
  46169. */
  46170. ShadowGenerator.prototype.getDarkness = function () {
  46171. return this._darkness;
  46172. };
  46173. /**
  46174. * Sets the ShadowGenerator darkness value (float <= 1.0).
  46175. * Returns the ShadowGenerator.
  46176. */
  46177. ShadowGenerator.prototype.setDarkness = function (darkness) {
  46178. if (darkness >= 1.0)
  46179. this._darkness = 1.0;
  46180. else if (darkness <= 0.0)
  46181. this._darkness = 0.0;
  46182. else
  46183. this._darkness = darkness;
  46184. return this;
  46185. };
  46186. /**
  46187. * Sets the ability to have transparent shadow (boolean).
  46188. * Returns the ShadowGenerator.
  46189. */
  46190. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  46191. this._transparencyShadow = hasShadow;
  46192. return this;
  46193. };
  46194. /**
  46195. * Returns a RenderTargetTexture object : the shadow map texture.
  46196. */
  46197. ShadowGenerator.prototype.getShadowMap = function () {
  46198. return this._shadowMap;
  46199. };
  46200. /**
  46201. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  46202. */
  46203. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  46204. if (this._shadowMap2) {
  46205. return this._shadowMap2;
  46206. }
  46207. return this._shadowMap;
  46208. };
  46209. /**
  46210. * Returns the associated light object.
  46211. */
  46212. ShadowGenerator.prototype.getLight = function () {
  46213. return this._light;
  46214. };
  46215. ShadowGenerator.prototype._initializeGenerator = function () {
  46216. this._light._markMeshesAsLightDirty();
  46217. this._initializeShadowMap();
  46218. };
  46219. ShadowGenerator.prototype._initializeShadowMap = function () {
  46220. var _this = this;
  46221. // Render target
  46222. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  46223. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46224. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46225. this._shadowMap.anisotropicFilteringLevel = 1;
  46226. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  46227. this._shadowMap.renderParticles = false;
  46228. // Record Face Index before render.
  46229. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  46230. _this._currentFaceIndex = faceIndex;
  46231. });
  46232. // Custom render function.
  46233. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  46234. // Blur if required afer render.
  46235. this._shadowMap.onAfterUnbindObservable.add(function () {
  46236. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  46237. return;
  46238. }
  46239. if (!_this._blurPostProcesses) {
  46240. _this._initializeBlurRTTAndPostProcesses();
  46241. }
  46242. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, _this.getShadowMapForRendering().getInternalTexture());
  46243. });
  46244. // Clear according to the chosen filter.
  46245. this._shadowMap.onClearObservable.add(function (engine) {
  46246. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  46247. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  46248. }
  46249. else {
  46250. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  46251. }
  46252. });
  46253. };
  46254. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  46255. var _this = this;
  46256. var engine = this._scene.getEngine();
  46257. var targetSize = this._mapSize / this.blurScale;
  46258. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  46259. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  46260. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46261. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46262. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  46263. }
  46264. if (this.useKernelBlur) {
  46265. 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);
  46266. this._kernelBlurXPostprocess.width = targetSize;
  46267. this._kernelBlurXPostprocess.height = targetSize;
  46268. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  46269. effect.setTexture("textureSampler", _this._shadowMap);
  46270. });
  46271. 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);
  46272. this._kernelBlurXPostprocess.autoClear = false;
  46273. this._kernelBlurYPostprocess.autoClear = false;
  46274. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  46275. this._kernelBlurXPostprocess.packedFloat = true;
  46276. this._kernelBlurYPostprocess.packedFloat = true;
  46277. }
  46278. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  46279. }
  46280. else {
  46281. 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);
  46282. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  46283. effect.setFloat2("screenSize", targetSize, targetSize);
  46284. effect.setTexture("textureSampler", _this._shadowMap);
  46285. });
  46286. this._boxBlurPostprocess.autoClear = false;
  46287. this._blurPostProcesses = [this._boxBlurPostprocess];
  46288. }
  46289. };
  46290. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  46291. var index;
  46292. for (index = 0; index < opaqueSubMeshes.length; index++) {
  46293. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  46294. }
  46295. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  46296. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  46297. }
  46298. if (this._transparencyShadow) {
  46299. for (index = 0; index < transparentSubMeshes.length; index++) {
  46300. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  46301. }
  46302. }
  46303. };
  46304. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  46305. var _this = this;
  46306. var mesh = subMesh.getRenderingMesh();
  46307. var scene = this._scene;
  46308. var engine = scene.getEngine();
  46309. // Culling
  46310. engine.setState(subMesh.getMaterial().backFaceCulling);
  46311. // Managing instances
  46312. var batch = mesh._getInstancesRenderList(subMesh._id);
  46313. if (batch.mustReturn) {
  46314. return;
  46315. }
  46316. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  46317. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  46318. engine.enableEffect(this._effect);
  46319. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  46320. var material = subMesh.getMaterial();
  46321. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  46322. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  46323. this._effect.setVector3("lightPosition", this.getLight().position);
  46324. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  46325. // Alpha test
  46326. if (material && material.needAlphaTesting()) {
  46327. var alphaTexture = material.getAlphaTestTexture();
  46328. if (alphaTexture) {
  46329. this._effect.setTexture("diffuseSampler", alphaTexture);
  46330. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  46331. }
  46332. }
  46333. // Bones
  46334. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  46335. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  46336. }
  46337. if (this.forceBackFacesOnly) {
  46338. engine.setState(true, 0, false, true);
  46339. }
  46340. // Draw
  46341. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  46342. if (this.forceBackFacesOnly) {
  46343. engine.setState(true, 0, false, false);
  46344. }
  46345. }
  46346. else {
  46347. // Need to reset refresh rate of the shadowMap
  46348. this._shadowMap.resetRefreshCounter();
  46349. }
  46350. };
  46351. ShadowGenerator.prototype._applyFilterValues = function () {
  46352. if (this.filter === ShadowGenerator.FILTER_NONE) {
  46353. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  46354. }
  46355. else {
  46356. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  46357. }
  46358. };
  46359. /**
  46360. * Force shader compilation including textures ready check
  46361. */
  46362. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  46363. var _this = this;
  46364. var scene = this._scene;
  46365. var engine = scene.getEngine();
  46366. var subMeshes = new Array();
  46367. var currentIndex = 0;
  46368. for (var _i = 0, _a = this.getShadowMap().renderList; _i < _a.length; _i++) {
  46369. var mesh = _a[_i];
  46370. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  46371. }
  46372. var checkReady = function () {
  46373. if (!_this._scene || !_this._scene.getEngine()) {
  46374. return;
  46375. }
  46376. var subMesh = subMeshes[currentIndex];
  46377. if (_this.isReady(subMesh, options ? options.useInstances : false)) {
  46378. currentIndex++;
  46379. if (currentIndex >= subMeshes.length) {
  46380. if (onCompiled) {
  46381. onCompiled(_this);
  46382. }
  46383. return;
  46384. }
  46385. }
  46386. setTimeout(checkReady, 16);
  46387. };
  46388. if (subMeshes.length > 0) {
  46389. checkReady();
  46390. }
  46391. };
  46392. /**
  46393. * Boolean : true when the ShadowGenerator is finally computed.
  46394. */
  46395. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  46396. var defines = [];
  46397. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  46398. defines.push("#define FLOAT");
  46399. }
  46400. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  46401. defines.push("#define ESM");
  46402. }
  46403. var attribs = [BABYLON.VertexBuffer.PositionKind];
  46404. var mesh = subMesh.getMesh();
  46405. var material = subMesh.getMaterial();
  46406. // Alpha test
  46407. if (material && material.needAlphaTesting()) {
  46408. var alphaTexture = material.getAlphaTestTexture();
  46409. if (alphaTexture) {
  46410. defines.push("#define ALPHATEST");
  46411. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  46412. attribs.push(BABYLON.VertexBuffer.UVKind);
  46413. defines.push("#define UV1");
  46414. }
  46415. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  46416. if (alphaTexture.coordinatesIndex === 1) {
  46417. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  46418. defines.push("#define UV2");
  46419. }
  46420. }
  46421. }
  46422. }
  46423. // Bones
  46424. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  46425. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  46426. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  46427. if (mesh.numBoneInfluencers > 4) {
  46428. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  46429. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  46430. }
  46431. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  46432. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  46433. }
  46434. else {
  46435. defines.push("#define NUM_BONE_INFLUENCERS 0");
  46436. }
  46437. // Instances
  46438. if (useInstances) {
  46439. defines.push("#define INSTANCES");
  46440. attribs.push("world0");
  46441. attribs.push("world1");
  46442. attribs.push("world2");
  46443. attribs.push("world3");
  46444. }
  46445. // Get correct effect
  46446. var join = defines.join("\n");
  46447. if (this._cachedDefines !== join) {
  46448. this._cachedDefines = join;
  46449. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  46450. }
  46451. return this._effect.isReady();
  46452. };
  46453. /**
  46454. * This creates the defines related to the standard BJS materials.
  46455. */
  46456. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  46457. var scene = this._scene;
  46458. var light = this._light;
  46459. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  46460. return;
  46461. }
  46462. defines["SHADOW" + lightIndex] = true;
  46463. if (this.usePoissonSampling) {
  46464. defines["SHADOWPCF" + lightIndex] = true;
  46465. }
  46466. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  46467. defines["SHADOWESM" + lightIndex] = true;
  46468. }
  46469. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  46470. defines["SHADOWCLOSEESM" + lightIndex] = true;
  46471. }
  46472. if (light.needCube()) {
  46473. defines["SHADOWCUBE" + lightIndex] = true;
  46474. }
  46475. };
  46476. /**
  46477. * This binds shadow lights related to the standard BJS materials.
  46478. * It implies the unifroms available on the materials are the standard BJS ones.
  46479. */
  46480. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  46481. var light = this._light;
  46482. var scene = this._scene;
  46483. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  46484. return;
  46485. }
  46486. if (!light.needCube()) {
  46487. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  46488. }
  46489. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  46490. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / this.getShadowMap().getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  46491. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera), lightIndex);
  46492. };
  46493. // Methods
  46494. /**
  46495. * Returns a Matrix object : the updated transformation matrix.
  46496. */
  46497. ShadowGenerator.prototype.getTransformMatrix = function () {
  46498. var scene = this._scene;
  46499. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  46500. return this._transformMatrix;
  46501. }
  46502. this._currentRenderID = scene.getRenderId();
  46503. this._currentFaceIndexCache = this._currentFaceIndex;
  46504. var lightPosition = this._light.position;
  46505. if (this._light.computeTransformedInformation()) {
  46506. lightPosition = this._light.transformedPosition;
  46507. }
  46508. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  46509. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  46510. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  46511. }
  46512. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  46513. this._cachedPosition = lightPosition.clone();
  46514. this._cachedDirection = this._lightDirection.clone();
  46515. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  46516. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  46517. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  46518. }
  46519. return this._transformMatrix;
  46520. };
  46521. ShadowGenerator.prototype.recreateShadowMap = function () {
  46522. // Track render list.
  46523. var renderList = this._shadowMap.renderList;
  46524. // Clean up existing data.
  46525. this._disposeRTTandPostProcesses();
  46526. // Reinitializes.
  46527. this._initializeGenerator();
  46528. // Reaffect the filter to ensure a correct fallback if necessary.
  46529. this.filter = this.filter;
  46530. // Reaffect the filter.
  46531. this._applyFilterValues();
  46532. // Reaffect Render List.
  46533. this._shadowMap.renderList = renderList;
  46534. };
  46535. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  46536. if (this._shadowMap2) {
  46537. this._shadowMap2.dispose();
  46538. this._shadowMap2 = null;
  46539. }
  46540. if (this._downSamplePostprocess) {
  46541. this._downSamplePostprocess.dispose();
  46542. this._downSamplePostprocess = null;
  46543. }
  46544. if (this._boxBlurPostprocess) {
  46545. this._boxBlurPostprocess.dispose();
  46546. this._boxBlurPostprocess = null;
  46547. }
  46548. if (this._kernelBlurXPostprocess) {
  46549. this._kernelBlurXPostprocess.dispose();
  46550. this._kernelBlurXPostprocess = null;
  46551. }
  46552. if (this._kernelBlurYPostprocess) {
  46553. this._kernelBlurYPostprocess.dispose();
  46554. this._kernelBlurYPostprocess = null;
  46555. }
  46556. this._blurPostProcesses = null;
  46557. };
  46558. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  46559. if (this._shadowMap) {
  46560. this._shadowMap.dispose();
  46561. this._shadowMap = null;
  46562. }
  46563. this._disposeBlurPostProcesses();
  46564. };
  46565. /**
  46566. * Disposes the ShadowGenerator.
  46567. * Returns nothing.
  46568. */
  46569. ShadowGenerator.prototype.dispose = function () {
  46570. this._disposeRTTandPostProcesses();
  46571. this._light._shadowGenerator = null;
  46572. this._light._markMeshesAsLightDirty();
  46573. };
  46574. /**
  46575. * Serializes the ShadowGenerator and returns a serializationObject.
  46576. */
  46577. ShadowGenerator.prototype.serialize = function () {
  46578. var serializationObject = {};
  46579. var shadowMap = this.getShadowMap();
  46580. serializationObject.lightId = this._light.id;
  46581. serializationObject.mapSize = shadowMap.getRenderSize();
  46582. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  46583. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  46584. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  46585. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  46586. serializationObject.usePoissonSampling = this.usePoissonSampling;
  46587. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  46588. serializationObject.depthScale = this.depthScale;
  46589. serializationObject.darkness = this.getDarkness();
  46590. serializationObject.blurBoxOffset = this.blurBoxOffset;
  46591. serializationObject.blurKernel = this.blurKernel;
  46592. serializationObject.blurScale = this.blurScale;
  46593. serializationObject.useKernelBlur = this.useKernelBlur;
  46594. serializationObject.transparencyShadow = this._transparencyShadow;
  46595. serializationObject.renderList = [];
  46596. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  46597. var mesh = shadowMap.renderList[meshIndex];
  46598. serializationObject.renderList.push(mesh.id);
  46599. }
  46600. return serializationObject;
  46601. };
  46602. /**
  46603. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  46604. */
  46605. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  46606. //casting to point light, as light is missing the position attr and typescript complains.
  46607. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  46608. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  46609. var shadowMap = shadowGenerator.getShadowMap();
  46610. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  46611. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  46612. meshes.forEach(function (mesh) {
  46613. shadowMap.renderList.push(mesh);
  46614. });
  46615. }
  46616. if (parsedShadowGenerator.usePoissonSampling) {
  46617. shadowGenerator.usePoissonSampling = true;
  46618. }
  46619. else if (parsedShadowGenerator.useExponentialShadowMap) {
  46620. shadowGenerator.useExponentialShadowMap = true;
  46621. }
  46622. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  46623. shadowGenerator.useBlurExponentialShadowMap = true;
  46624. }
  46625. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  46626. shadowGenerator.useCloseExponentialShadowMap = true;
  46627. }
  46628. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  46629. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  46630. }
  46631. else if (parsedShadowGenerator.useVarianceShadowMap) {
  46632. shadowGenerator.useExponentialShadowMap = true;
  46633. }
  46634. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  46635. shadowGenerator.useBlurExponentialShadowMap = true;
  46636. }
  46637. if (parsedShadowGenerator.depthScale) {
  46638. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  46639. }
  46640. if (parsedShadowGenerator.blurScale) {
  46641. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  46642. }
  46643. if (parsedShadowGenerator.blurBoxOffset) {
  46644. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  46645. }
  46646. if (parsedShadowGenerator.useKernelBlur) {
  46647. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  46648. }
  46649. if (parsedShadowGenerator.blurKernel) {
  46650. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  46651. }
  46652. if (parsedShadowGenerator.bias !== undefined) {
  46653. shadowGenerator.bias = parsedShadowGenerator.bias;
  46654. }
  46655. if (parsedShadowGenerator.darkness) {
  46656. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  46657. }
  46658. if (parsedShadowGenerator.transparencyShadow) {
  46659. shadowGenerator.setTransparencyShadow(true);
  46660. }
  46661. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  46662. return shadowGenerator;
  46663. };
  46664. return ShadowGenerator;
  46665. }());
  46666. ShadowGenerator._FILTER_NONE = 0;
  46667. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  46668. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  46669. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  46670. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  46671. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  46672. BABYLON.ShadowGenerator = ShadowGenerator;
  46673. })(BABYLON || (BABYLON = {}));
  46674. //# sourceMappingURL=babylon.shadowGenerator.js.map
  46675. var BABYLON;
  46676. (function (BABYLON) {
  46677. var DefaultLoadingScreen = (function () {
  46678. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  46679. if (_loadingText === void 0) { _loadingText = ""; }
  46680. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  46681. var _this = this;
  46682. this._renderingCanvas = _renderingCanvas;
  46683. this._loadingText = _loadingText;
  46684. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  46685. // Resize
  46686. this._resizeLoadingUI = function () {
  46687. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  46688. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  46689. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  46690. _this._loadingDiv.style.left = canvasRect.left + "px";
  46691. _this._loadingDiv.style.top = canvasRect.top + "px";
  46692. _this._loadingDiv.style.width = canvasRect.width + "px";
  46693. _this._loadingDiv.style.height = canvasRect.height + "px";
  46694. };
  46695. }
  46696. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  46697. if (this._loadingDiv) {
  46698. // Do not add a loading screen if there is already one
  46699. return;
  46700. }
  46701. this._loadingDiv = document.createElement("div");
  46702. this._loadingDiv.id = "babylonjsLoadingDiv";
  46703. this._loadingDiv.style.opacity = "0";
  46704. this._loadingDiv.style.transition = "opacity 1.5s ease";
  46705. // Loading text
  46706. this._loadingTextDiv = document.createElement("div");
  46707. this._loadingTextDiv.style.position = "absolute";
  46708. this._loadingTextDiv.style.left = "0";
  46709. this._loadingTextDiv.style.top = "50%";
  46710. this._loadingTextDiv.style.marginTop = "80px";
  46711. this._loadingTextDiv.style.width = "100%";
  46712. this._loadingTextDiv.style.height = "20px";
  46713. this._loadingTextDiv.style.fontFamily = "Arial";
  46714. this._loadingTextDiv.style.fontSize = "14px";
  46715. this._loadingTextDiv.style.color = "white";
  46716. this._loadingTextDiv.style.textAlign = "center";
  46717. this._loadingTextDiv.innerHTML = "Loading";
  46718. this._loadingDiv.appendChild(this._loadingTextDiv);
  46719. //set the predefined text
  46720. this._loadingTextDiv.innerHTML = this._loadingText;
  46721. // Generating keyframes
  46722. var style = document.createElement('style');
  46723. style.type = 'text/css';
  46724. 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 }";
  46725. style.innerHTML = keyFrames;
  46726. document.getElementsByTagName('head')[0].appendChild(style);
  46727. // Loading img
  46728. var imgBack = new Image();
  46729. 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";
  46730. imgBack.style.position = "absolute";
  46731. imgBack.style.left = "50%";
  46732. imgBack.style.top = "50%";
  46733. imgBack.style.marginLeft = "-60px";
  46734. imgBack.style.marginTop = "-60px";
  46735. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  46736. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  46737. imgBack.style.transformOrigin = "50% 50%";
  46738. imgBack.style.webkitTransformOrigin = "50% 50%";
  46739. this._loadingDiv.appendChild(imgBack);
  46740. this._resizeLoadingUI();
  46741. window.addEventListener("resize", this._resizeLoadingUI);
  46742. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  46743. document.body.appendChild(this._loadingDiv);
  46744. this._loadingDiv.style.opacity = "1";
  46745. };
  46746. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  46747. var _this = this;
  46748. if (!this._loadingDiv) {
  46749. return;
  46750. }
  46751. var onTransitionEnd = function () {
  46752. if (!_this._loadingDiv) {
  46753. return;
  46754. }
  46755. document.body.removeChild(_this._loadingDiv);
  46756. window.removeEventListener("resize", _this._resizeLoadingUI);
  46757. _this._loadingDiv = null;
  46758. };
  46759. this._loadingDiv.style.opacity = "0";
  46760. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  46761. };
  46762. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  46763. set: function (text) {
  46764. this._loadingText = text;
  46765. if (this._loadingTextDiv) {
  46766. this._loadingTextDiv.innerHTML = this._loadingText;
  46767. }
  46768. },
  46769. enumerable: true,
  46770. configurable: true
  46771. });
  46772. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  46773. get: function () {
  46774. return this._loadingDivBackgroundColor;
  46775. },
  46776. set: function (color) {
  46777. this._loadingDivBackgroundColor = color;
  46778. if (!this._loadingDiv) {
  46779. return;
  46780. }
  46781. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  46782. },
  46783. enumerable: true,
  46784. configurable: true
  46785. });
  46786. return DefaultLoadingScreen;
  46787. }());
  46788. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  46789. })(BABYLON || (BABYLON = {}));
  46790. //# sourceMappingURL=babylon.loadingScreen.js.map
  46791. var BABYLON;
  46792. (function (BABYLON) {
  46793. var SceneLoader = (function () {
  46794. function SceneLoader() {
  46795. }
  46796. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  46797. get: function () {
  46798. return 0;
  46799. },
  46800. enumerable: true,
  46801. configurable: true
  46802. });
  46803. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  46804. get: function () {
  46805. return 1;
  46806. },
  46807. enumerable: true,
  46808. configurable: true
  46809. });
  46810. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  46811. get: function () {
  46812. return 2;
  46813. },
  46814. enumerable: true,
  46815. configurable: true
  46816. });
  46817. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  46818. get: function () {
  46819. return 3;
  46820. },
  46821. enumerable: true,
  46822. configurable: true
  46823. });
  46824. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  46825. get: function () {
  46826. return SceneLoader._ForceFullSceneLoadingForIncremental;
  46827. },
  46828. set: function (value) {
  46829. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  46830. },
  46831. enumerable: true,
  46832. configurable: true
  46833. });
  46834. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  46835. get: function () {
  46836. return SceneLoader._ShowLoadingScreen;
  46837. },
  46838. set: function (value) {
  46839. SceneLoader._ShowLoadingScreen = value;
  46840. },
  46841. enumerable: true,
  46842. configurable: true
  46843. });
  46844. Object.defineProperty(SceneLoader, "loggingLevel", {
  46845. get: function () {
  46846. return SceneLoader._loggingLevel;
  46847. },
  46848. set: function (value) {
  46849. SceneLoader._loggingLevel = value;
  46850. },
  46851. enumerable: true,
  46852. configurable: true
  46853. });
  46854. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  46855. get: function () {
  46856. return SceneLoader._CleanBoneMatrixWeights;
  46857. },
  46858. set: function (value) {
  46859. SceneLoader._CleanBoneMatrixWeights = value;
  46860. },
  46861. enumerable: true,
  46862. configurable: true
  46863. });
  46864. SceneLoader._getDefaultPlugin = function () {
  46865. return SceneLoader._registeredPlugins[".babylon"];
  46866. };
  46867. SceneLoader._getPluginForExtension = function (extension) {
  46868. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  46869. if (registeredPlugin) {
  46870. return registeredPlugin;
  46871. }
  46872. return SceneLoader._getDefaultPlugin();
  46873. };
  46874. SceneLoader._getPluginForDirectLoad = function (data) {
  46875. for (var extension in SceneLoader._registeredPlugins) {
  46876. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  46877. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  46878. return SceneLoader._registeredPlugins[extension];
  46879. }
  46880. }
  46881. return SceneLoader._getDefaultPlugin();
  46882. };
  46883. SceneLoader._getPluginForFilename = function (sceneFilename) {
  46884. if (sceneFilename.name) {
  46885. sceneFilename = sceneFilename.name;
  46886. }
  46887. var dotPosition = sceneFilename.lastIndexOf(".");
  46888. var queryStringPosition = sceneFilename.indexOf("?");
  46889. if (queryStringPosition === -1) {
  46890. queryStringPosition = sceneFilename.length;
  46891. }
  46892. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  46893. return SceneLoader._getPluginForExtension(extension);
  46894. };
  46895. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  46896. SceneLoader._getDirectLoad = function (sceneFilename) {
  46897. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  46898. return sceneFilename.substr(5);
  46899. }
  46900. return null;
  46901. };
  46902. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  46903. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  46904. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename);
  46905. var plugin = registeredPlugin.plugin;
  46906. var useArrayBuffer = registeredPlugin.isBinary;
  46907. var database;
  46908. SceneLoader.OnPluginActivatedObservable.notifyObservers(registeredPlugin.plugin);
  46909. var dataCallback = function (data) {
  46910. if (scene.isDisposed) {
  46911. onError("Scene has been disposed");
  46912. return;
  46913. }
  46914. scene.database = database;
  46915. try {
  46916. onSuccess(plugin, data);
  46917. }
  46918. catch (e) {
  46919. onError(null, e);
  46920. }
  46921. };
  46922. var manifestChecked = function (success) {
  46923. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) {
  46924. onError(request.status + " " + request.statusText);
  46925. });
  46926. };
  46927. if (directLoad) {
  46928. dataCallback(directLoad);
  46929. return;
  46930. }
  46931. if (rootUrl.indexOf("file:") === -1) {
  46932. if (scene.getEngine().enableOfflineSupport) {
  46933. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  46934. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  46935. }
  46936. else {
  46937. manifestChecked(true);
  46938. }
  46939. }
  46940. else {
  46941. BABYLON.Tools.ReadFile(sceneFilename, dataCallback, onProgress, useArrayBuffer);
  46942. }
  46943. };
  46944. // Public functions
  46945. SceneLoader.GetPluginForExtension = function (extension) {
  46946. return SceneLoader._getPluginForExtension(extension).plugin;
  46947. };
  46948. SceneLoader.RegisterPlugin = function (plugin) {
  46949. if (typeof plugin.extensions === "string") {
  46950. var extension = plugin.extensions;
  46951. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  46952. plugin: plugin,
  46953. isBinary: false
  46954. };
  46955. }
  46956. else {
  46957. var extensions = plugin.extensions;
  46958. Object.keys(extensions).forEach(function (extension) {
  46959. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  46960. plugin: plugin,
  46961. isBinary: extensions[extension].isBinary
  46962. };
  46963. });
  46964. }
  46965. };
  46966. /**
  46967. * Import meshes into a scene
  46968. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  46969. * @param rootUrl a string that defines the root url for scene and resources
  46970. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  46971. * @param scene the instance of BABYLON.Scene to append to
  46972. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  46973. * @param onProgress a callback with a progress event for each file being loaded
  46974. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  46975. */
  46976. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  46977. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  46978. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  46979. return;
  46980. }
  46981. var loadingToken = {};
  46982. scene._addPendingData(loadingToken);
  46983. var errorHandler = function (message, exception) {
  46984. if (onError) {
  46985. onError(scene, "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : ""));
  46986. }
  46987. scene._removePendingData(loadingToken);
  46988. };
  46989. var progressHandler = function (event) {
  46990. if (onProgress) {
  46991. onProgress(event);
  46992. }
  46993. };
  46994. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  46995. if (plugin.importMesh) {
  46996. var syncedPlugin = plugin;
  46997. var meshes = [];
  46998. var particleSystems = [];
  46999. var skeletons = [];
  47000. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  47001. return;
  47002. }
  47003. if (onSuccess) {
  47004. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  47005. onSuccess(meshes, particleSystems, skeletons);
  47006. scene._removePendingData(loadingToken);
  47007. }
  47008. }
  47009. else {
  47010. var asyncedPlugin = plugin;
  47011. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  47012. if (onSuccess) {
  47013. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  47014. onSuccess(meshes, particleSystems, skeletons);
  47015. scene._removePendingData(loadingToken);
  47016. }
  47017. }, progressHandler, errorHandler);
  47018. }
  47019. }, progressHandler, errorHandler);
  47020. };
  47021. /**
  47022. * Load a scene
  47023. * @param rootUrl a string that defines the root url for scene and resources
  47024. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  47025. * @param engine is the instance of BABYLON.Engine to use to create the scene
  47026. * @param onSuccess a callback with the scene when import succeeds
  47027. * @param onProgress a callback with a progress event for each file being loaded
  47028. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  47029. */
  47030. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError) {
  47031. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError);
  47032. };
  47033. /**
  47034. * Append a scene
  47035. * @param rootUrl a string that defines the root url for scene and resources
  47036. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  47037. * @param scene is the instance of BABYLON.Scene to append to
  47038. * @param onSuccess a callback with the scene when import succeeds
  47039. * @param onProgress a callback with a progress event for each file being loaded
  47040. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  47041. */
  47042. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  47043. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  47044. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  47045. return;
  47046. }
  47047. if (SceneLoader.ShowLoadingScreen) {
  47048. scene.getEngine().displayLoadingUI();
  47049. }
  47050. var loadingToken = {};
  47051. scene._addPendingData(loadingToken);
  47052. var errorHandler = function (message, exception) {
  47053. if (onError) {
  47054. onError(scene, "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : ""));
  47055. }
  47056. scene._removePendingData(loadingToken);
  47057. scene.getEngine().hideLoadingUI();
  47058. };
  47059. var progressHandler = function (event) {
  47060. if (onProgress) {
  47061. onProgress(event);
  47062. }
  47063. };
  47064. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  47065. if (plugin.load) {
  47066. var syncedPlugin = plugin;
  47067. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  47068. return;
  47069. }
  47070. if (onSuccess) {
  47071. onSuccess(scene);
  47072. }
  47073. scene.loadingPluginName = plugin.name;
  47074. scene._removePendingData(loadingToken);
  47075. }
  47076. else {
  47077. var asyncedPlugin = plugin;
  47078. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  47079. if (onSuccess) {
  47080. onSuccess(scene);
  47081. }
  47082. scene.loadingPluginName = plugin.name;
  47083. scene._removePendingData(loadingToken);
  47084. }, progressHandler, errorHandler);
  47085. }
  47086. if (SceneLoader.ShowLoadingScreen) {
  47087. scene.executeWhenReady(function () {
  47088. scene.getEngine().hideLoadingUI();
  47089. });
  47090. }
  47091. }, progressHandler, errorHandler);
  47092. };
  47093. return SceneLoader;
  47094. }());
  47095. // Flags
  47096. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  47097. SceneLoader._ShowLoadingScreen = true;
  47098. SceneLoader._CleanBoneMatrixWeights = false;
  47099. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  47100. // Members
  47101. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  47102. SceneLoader._registeredPlugins = {};
  47103. BABYLON.SceneLoader = SceneLoader;
  47104. ;
  47105. })(BABYLON || (BABYLON = {}));
  47106. //# sourceMappingURL=babylon.sceneLoader.js.map
  47107. var BABYLON;
  47108. (function (BABYLON) {
  47109. var Internals;
  47110. (function (Internals) {
  47111. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  47112. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  47113. var parsedMaterial = parsedData.materials[index];
  47114. if (parsedMaterial.id === id) {
  47115. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  47116. }
  47117. }
  47118. return null;
  47119. };
  47120. var isDescendantOf = function (mesh, names, hierarchyIds) {
  47121. for (var i in names) {
  47122. if (mesh.name === names[i]) {
  47123. hierarchyIds.push(mesh.id);
  47124. return true;
  47125. }
  47126. }
  47127. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  47128. hierarchyIds.push(mesh.id);
  47129. return true;
  47130. }
  47131. return false;
  47132. };
  47133. var logOperation = function (operation, producer) {
  47134. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  47135. };
  47136. BABYLON.SceneLoader.RegisterPlugin({
  47137. name: "babylon.js",
  47138. extensions: ".babylon",
  47139. canDirectLoad: function (data) {
  47140. if (data.indexOf("babylon") !== -1) {
  47141. return true;
  47142. }
  47143. return false;
  47144. },
  47145. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  47146. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  47147. // when SceneLoader.debugLogging = true (default), or exception encountered.
  47148. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  47149. // and avoid problems with multiple concurrent .babylon loads.
  47150. var log = "importMesh has failed JSON parse";
  47151. try {
  47152. var parsedData = JSON.parse(data);
  47153. log = "";
  47154. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  47155. if (!meshesNames) {
  47156. meshesNames = null;
  47157. }
  47158. else if (!Array.isArray(meshesNames)) {
  47159. meshesNames = [meshesNames];
  47160. }
  47161. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  47162. var loadedSkeletonsIds = [];
  47163. var loadedMaterialsIds = [];
  47164. var hierarchyIds = [];
  47165. var index;
  47166. var cache;
  47167. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  47168. var parsedMesh = parsedData.meshes[index];
  47169. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  47170. if (meshesNames !== null) {
  47171. // Remove found mesh name from list.
  47172. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  47173. }
  47174. //Geometry?
  47175. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  47176. //does the file contain geometries?
  47177. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  47178. //find the correct geometry and add it to the scene
  47179. var found = false;
  47180. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  47181. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  47182. return;
  47183. }
  47184. else {
  47185. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  47186. if (parsedGeometryData.id === parsedMesh.geometryId) {
  47187. switch (geometryType) {
  47188. case "boxes":
  47189. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  47190. break;
  47191. case "spheres":
  47192. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  47193. break;
  47194. case "cylinders":
  47195. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  47196. break;
  47197. case "toruses":
  47198. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  47199. break;
  47200. case "grounds":
  47201. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  47202. break;
  47203. case "planes":
  47204. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  47205. break;
  47206. case "torusKnots":
  47207. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  47208. break;
  47209. case "vertexData":
  47210. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  47211. break;
  47212. }
  47213. found = true;
  47214. }
  47215. });
  47216. }
  47217. });
  47218. if (found === false) {
  47219. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  47220. }
  47221. }
  47222. }
  47223. // Material ?
  47224. if (parsedMesh.materialId) {
  47225. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  47226. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  47227. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  47228. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  47229. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  47230. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  47231. var subMatId = parsedMultiMaterial.materials[matIndex];
  47232. loadedMaterialsIds.push(subMatId);
  47233. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  47234. log += "\n\tMaterial " + mat.toString(fullDetails);
  47235. }
  47236. loadedMaterialsIds.push(parsedMultiMaterial.id);
  47237. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  47238. materialFound = true;
  47239. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  47240. break;
  47241. }
  47242. }
  47243. }
  47244. if (materialFound === false) {
  47245. loadedMaterialsIds.push(parsedMesh.materialId);
  47246. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  47247. if (!mat) {
  47248. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  47249. }
  47250. else {
  47251. log += "\n\tMaterial " + mat.toString(fullDetails);
  47252. }
  47253. }
  47254. }
  47255. // Skeleton ?
  47256. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  47257. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  47258. if (skeletonAlreadyLoaded === false) {
  47259. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  47260. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  47261. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  47262. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  47263. skeletons.push(skeleton);
  47264. loadedSkeletonsIds.push(parsedSkeleton.id);
  47265. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  47266. }
  47267. }
  47268. }
  47269. }
  47270. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  47271. meshes.push(mesh);
  47272. log += "\n\tMesh " + mesh.toString(fullDetails);
  47273. }
  47274. }
  47275. // Connecting parents
  47276. var currentMesh;
  47277. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  47278. currentMesh = scene.meshes[index];
  47279. if (currentMesh._waitingParentId) {
  47280. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  47281. currentMesh._waitingParentId = undefined;
  47282. }
  47283. }
  47284. // freeze and compute world matrix application
  47285. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  47286. currentMesh = scene.meshes[index];
  47287. if (currentMesh._waitingFreezeWorldMatrix) {
  47288. currentMesh.freezeWorldMatrix();
  47289. currentMesh._waitingFreezeWorldMatrix = undefined;
  47290. }
  47291. else {
  47292. currentMesh.computeWorldMatrix(true);
  47293. }
  47294. }
  47295. }
  47296. // Particles
  47297. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  47298. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  47299. var parsedParticleSystem = parsedData.particleSystems[index];
  47300. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  47301. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  47302. }
  47303. }
  47304. }
  47305. return true;
  47306. }
  47307. catch (err) {
  47308. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  47309. log = null;
  47310. throw err;
  47311. }
  47312. finally {
  47313. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  47314. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  47315. }
  47316. }
  47317. },
  47318. load: function (scene, data, rootUrl) {
  47319. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  47320. // when SceneLoader.debugLogging = true (default), or exception encountered.
  47321. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  47322. // and avoid problems with multiple concurrent .babylon loads.
  47323. var log = "importScene has failed JSON parse";
  47324. try {
  47325. var parsedData = JSON.parse(data);
  47326. log = "";
  47327. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  47328. // Scene
  47329. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  47330. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  47331. }
  47332. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  47333. scene.autoClear = parsedData.autoClear;
  47334. }
  47335. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  47336. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  47337. }
  47338. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  47339. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  47340. }
  47341. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  47342. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  47343. }
  47344. // Fog
  47345. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  47346. scene.fogMode = parsedData.fogMode;
  47347. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  47348. scene.fogStart = parsedData.fogStart;
  47349. scene.fogEnd = parsedData.fogEnd;
  47350. scene.fogDensity = parsedData.fogDensity;
  47351. log += "\tFog mode for scene: ";
  47352. switch (scene.fogMode) {
  47353. // getters not compiling, so using hardcoded
  47354. case 1:
  47355. log += "exp\n";
  47356. break;
  47357. case 2:
  47358. log += "exp2\n";
  47359. break;
  47360. case 3:
  47361. log += "linear\n";
  47362. break;
  47363. }
  47364. }
  47365. //Physics
  47366. if (parsedData.physicsEnabled) {
  47367. var physicsPlugin;
  47368. if (parsedData.physicsEngine === "cannon") {
  47369. physicsPlugin = new BABYLON.CannonJSPlugin();
  47370. }
  47371. else if (parsedData.physicsEngine === "oimo") {
  47372. physicsPlugin = new BABYLON.OimoJSPlugin();
  47373. }
  47374. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  47375. //else - default engine, which is currently oimo
  47376. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  47377. scene.enablePhysics(physicsGravity, physicsPlugin);
  47378. }
  47379. // Metadata
  47380. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  47381. scene.metadata = parsedData.metadata;
  47382. }
  47383. //collisions, if defined. otherwise, default is true
  47384. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  47385. scene.collisionsEnabled = parsedData.collisionsEnabled;
  47386. }
  47387. scene.workerCollisions = !!parsedData.workerCollisions;
  47388. var index;
  47389. var cache;
  47390. // Lights
  47391. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  47392. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  47393. var parsedLight = parsedData.lights[index];
  47394. var light = BABYLON.Light.Parse(parsedLight, scene);
  47395. log += (index === 0 ? "\n\tLights:" : "");
  47396. log += "\n\t\t" + light.toString(fullDetails);
  47397. }
  47398. }
  47399. // Animations
  47400. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  47401. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  47402. var parsedAnimation = parsedData.animations[index];
  47403. var animation = BABYLON.Animation.Parse(parsedAnimation);
  47404. scene.animations.push(animation);
  47405. log += (index === 0 ? "\n\tAnimations:" : "");
  47406. log += "\n\t\t" + animation.toString(fullDetails);
  47407. }
  47408. }
  47409. if (parsedData.autoAnimate) {
  47410. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  47411. }
  47412. // Materials
  47413. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  47414. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  47415. var parsedMaterial = parsedData.materials[index];
  47416. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  47417. log += (index === 0 ? "\n\tMaterials:" : "");
  47418. log += "\n\t\t" + mat.toString(fullDetails);
  47419. }
  47420. }
  47421. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  47422. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  47423. var parsedMultiMaterial = parsedData.multiMaterials[index];
  47424. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  47425. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  47426. log += "\n\t\t" + mmat.toString(fullDetails);
  47427. }
  47428. }
  47429. // Morph targets
  47430. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  47431. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  47432. var managerData = _a[_i];
  47433. var parsedManager = BABYLON.MorphTargetManager.Parse(managerData, scene);
  47434. }
  47435. }
  47436. // Skeletons
  47437. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  47438. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  47439. var parsedSkeleton = parsedData.skeletons[index];
  47440. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  47441. log += (index === 0 ? "\n\tSkeletons:" : "");
  47442. log += "\n\t\t" + skeleton.toString(fullDetails);
  47443. }
  47444. }
  47445. // Geometries
  47446. var geometries = parsedData.geometries;
  47447. if (geometries !== undefined && geometries !== null) {
  47448. // Boxes
  47449. var boxes = geometries.boxes;
  47450. if (boxes !== undefined && boxes !== null) {
  47451. for (index = 0, cache = boxes.length; index < cache; index++) {
  47452. var parsedBox = boxes[index];
  47453. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  47454. }
  47455. }
  47456. // Spheres
  47457. var spheres = geometries.spheres;
  47458. if (spheres !== undefined && spheres !== null) {
  47459. for (index = 0, cache = spheres.length; index < cache; index++) {
  47460. var parsedSphere = spheres[index];
  47461. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  47462. }
  47463. }
  47464. // Cylinders
  47465. var cylinders = geometries.cylinders;
  47466. if (cylinders !== undefined && cylinders !== null) {
  47467. for (index = 0, cache = cylinders.length; index < cache; index++) {
  47468. var parsedCylinder = cylinders[index];
  47469. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  47470. }
  47471. }
  47472. // Toruses
  47473. var toruses = geometries.toruses;
  47474. if (toruses !== undefined && toruses !== null) {
  47475. for (index = 0, cache = toruses.length; index < cache; index++) {
  47476. var parsedTorus = toruses[index];
  47477. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  47478. }
  47479. }
  47480. // Grounds
  47481. var grounds = geometries.grounds;
  47482. if (grounds !== undefined && grounds !== null) {
  47483. for (index = 0, cache = grounds.length; index < cache; index++) {
  47484. var parsedGround = grounds[index];
  47485. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  47486. }
  47487. }
  47488. // Planes
  47489. var planes = geometries.planes;
  47490. if (planes !== undefined && planes !== null) {
  47491. for (index = 0, cache = planes.length; index < cache; index++) {
  47492. var parsedPlane = planes[index];
  47493. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  47494. }
  47495. }
  47496. // TorusKnots
  47497. var torusKnots = geometries.torusKnots;
  47498. if (torusKnots !== undefined && torusKnots !== null) {
  47499. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  47500. var parsedTorusKnot = torusKnots[index];
  47501. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  47502. }
  47503. }
  47504. // VertexData
  47505. var vertexData = geometries.vertexData;
  47506. if (vertexData !== undefined && vertexData !== null) {
  47507. for (index = 0, cache = vertexData.length; index < cache; index++) {
  47508. var parsedVertexData = vertexData[index];
  47509. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  47510. }
  47511. }
  47512. }
  47513. // Meshes
  47514. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  47515. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  47516. var parsedMesh = parsedData.meshes[index];
  47517. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  47518. log += (index === 0 ? "\n\tMeshes:" : "");
  47519. log += "\n\t\t" + mesh.toString(fullDetails);
  47520. }
  47521. }
  47522. // Cameras
  47523. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  47524. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  47525. var parsedCamera = parsedData.cameras[index];
  47526. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  47527. log += (index === 0 ? "\n\tCameras:" : "");
  47528. log += "\n\t\t" + camera.toString(fullDetails);
  47529. }
  47530. }
  47531. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  47532. scene.setActiveCameraByID(parsedData.activeCameraID);
  47533. }
  47534. // Browsing all the graph to connect the dots
  47535. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  47536. var camera = scene.cameras[index];
  47537. if (camera._waitingParentId) {
  47538. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  47539. camera._waitingParentId = undefined;
  47540. }
  47541. }
  47542. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  47543. var light = scene.lights[index];
  47544. if (light._waitingParentId) {
  47545. light.parent = scene.getLastEntryByID(light._waitingParentId);
  47546. light._waitingParentId = undefined;
  47547. }
  47548. }
  47549. // Sounds
  47550. var loadedSounds = [];
  47551. var loadedSound;
  47552. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  47553. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  47554. var parsedSound = parsedData.sounds[index];
  47555. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  47556. if (!parsedSound.url)
  47557. parsedSound.url = parsedSound.name;
  47558. if (!loadedSounds[parsedSound.url]) {
  47559. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  47560. loadedSounds[parsedSound.url] = loadedSound;
  47561. }
  47562. else {
  47563. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  47564. }
  47565. }
  47566. else {
  47567. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  47568. }
  47569. }
  47570. }
  47571. loadedSounds = [];
  47572. // Connect parents & children and parse actions
  47573. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  47574. var mesh = scene.meshes[index];
  47575. if (mesh._waitingParentId) {
  47576. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  47577. mesh._waitingParentId = undefined;
  47578. }
  47579. if (mesh._waitingActions) {
  47580. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  47581. mesh._waitingActions = undefined;
  47582. }
  47583. }
  47584. // freeze world matrix application
  47585. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  47586. var currentMesh = scene.meshes[index];
  47587. if (currentMesh._waitingFreezeWorldMatrix) {
  47588. currentMesh.freezeWorldMatrix();
  47589. currentMesh._waitingFreezeWorldMatrix = undefined;
  47590. }
  47591. else {
  47592. currentMesh.computeWorldMatrix(true);
  47593. }
  47594. }
  47595. // Particles Systems
  47596. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  47597. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  47598. var parsedParticleSystem = parsedData.particleSystems[index];
  47599. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  47600. }
  47601. }
  47602. // Lens flares
  47603. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  47604. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  47605. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  47606. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  47607. }
  47608. }
  47609. // Shadows
  47610. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  47611. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  47612. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  47613. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  47614. }
  47615. }
  47616. // Lights exclusions / inclusions
  47617. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  47618. var light = scene.lights[index];
  47619. // Excluded check
  47620. if (light._excludedMeshesIds.length > 0) {
  47621. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  47622. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  47623. if (excludedMesh) {
  47624. light.excludedMeshes.push(excludedMesh);
  47625. }
  47626. }
  47627. light._excludedMeshesIds = [];
  47628. }
  47629. // Included check
  47630. if (light._includedOnlyMeshesIds.length > 0) {
  47631. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  47632. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  47633. if (includedOnlyMesh) {
  47634. light.includedOnlyMeshes.push(includedOnlyMesh);
  47635. }
  47636. }
  47637. light._includedOnlyMeshesIds = [];
  47638. }
  47639. }
  47640. // Actions (scene)
  47641. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  47642. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  47643. }
  47644. // Finish
  47645. return true;
  47646. }
  47647. catch (err) {
  47648. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  47649. log = null;
  47650. throw err;
  47651. }
  47652. finally {
  47653. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  47654. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  47655. }
  47656. }
  47657. }
  47658. });
  47659. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  47660. })(BABYLON || (BABYLON = {}));
  47661. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  47662. var BABYLON;
  47663. (function (BABYLON) {
  47664. var FilesInput = (function () {
  47665. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  47666. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  47667. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  47668. this._engine = p_engine;
  47669. this._canvas = p_canvas;
  47670. this._currentScene = p_scene;
  47671. this._sceneLoadedCallback = p_sceneLoadedCallback;
  47672. this._progressCallback = p_progressCallback;
  47673. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  47674. this._textureLoadingCallback = p_textureLoadingCallback;
  47675. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  47676. }
  47677. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  47678. var _this = this;
  47679. if (p_elementToMonitor) {
  47680. this._elementToMonitor = p_elementToMonitor;
  47681. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  47682. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  47683. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  47684. }
  47685. };
  47686. FilesInput.prototype.renderFunction = function () {
  47687. if (this._additionnalRenderLoopLogicCallback) {
  47688. this._additionnalRenderLoopLogicCallback();
  47689. }
  47690. if (this._currentScene) {
  47691. if (this._textureLoadingCallback) {
  47692. var remaining = this._currentScene.getWaitingItemsCount();
  47693. if (remaining > 0) {
  47694. this._textureLoadingCallback(remaining);
  47695. }
  47696. }
  47697. this._currentScene.render();
  47698. }
  47699. };
  47700. FilesInput.prototype.drag = function (e) {
  47701. e.stopPropagation();
  47702. e.preventDefault();
  47703. };
  47704. FilesInput.prototype.drop = function (eventDrop) {
  47705. eventDrop.stopPropagation();
  47706. eventDrop.preventDefault();
  47707. this.loadFiles(eventDrop);
  47708. };
  47709. FilesInput.prototype._handleFolderDrop = function (entry, files, callback) {
  47710. var reader = entry.createReader(), relativePath = entry.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  47711. reader.readEntries(function (fileEntries) {
  47712. var remaining = fileEntries.length;
  47713. for (var _i = 0, fileEntries_1 = fileEntries; _i < fileEntries_1.length; _i++) {
  47714. var fileEntry = fileEntries_1[_i];
  47715. if (fileEntry.isFile) {
  47716. fileEntry.file(function (file) {
  47717. file.correctName = relativePath + file.name;
  47718. files.push(file);
  47719. remaining--;
  47720. if (remaining === 0) {
  47721. callback();
  47722. }
  47723. });
  47724. }
  47725. else {
  47726. remaining--;
  47727. if (remaining === 0) {
  47728. callback();
  47729. }
  47730. }
  47731. }
  47732. });
  47733. };
  47734. FilesInput.prototype._processFiles = function (files) {
  47735. for (var i = 0; i < files.length; i++) {
  47736. var name = files[i].correctName.toLowerCase();
  47737. var extension = name.split('.').pop();
  47738. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  47739. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  47740. this._sceneFileToLoad = files[i];
  47741. }
  47742. else {
  47743. FilesInput.FilesToLoad[name] = files[i];
  47744. }
  47745. }
  47746. this.reload();
  47747. };
  47748. FilesInput.prototype.loadFiles = function (event) {
  47749. var _this = this;
  47750. if (this._startingProcessingFilesCallback)
  47751. this._startingProcessingFilesCallback();
  47752. // Handling data transfer via drag'n'drop
  47753. if (event && event.dataTransfer && event.dataTransfer.files) {
  47754. this._filesToLoad = event.dataTransfer.files;
  47755. }
  47756. // Handling files from input files
  47757. if (event && event.target && event.target.files) {
  47758. this._filesToLoad = event.target.files;
  47759. }
  47760. if (this._filesToLoad && this._filesToLoad.length > 0) {
  47761. var files_1 = [];
  47762. var folders = [];
  47763. for (var i = 0; i < this._filesToLoad.length; i++) {
  47764. var fileToLoad = this._filesToLoad[i];
  47765. var name_1 = fileToLoad.name.toLowerCase();
  47766. var type = fileToLoad.type;
  47767. var entry = void 0;
  47768. fileToLoad.correctName = name_1;
  47769. if (event.dataTransfer && event.dataTransfer.items) {
  47770. var item = event.dataTransfer.items[i];
  47771. if (item.getAsEntry) {
  47772. entry = item.getAsEntry();
  47773. }
  47774. else if (item.webkitGetAsEntry) {
  47775. entry = item.webkitGetAsEntry();
  47776. }
  47777. }
  47778. if (!entry) {
  47779. files_1.push(fileToLoad);
  47780. }
  47781. else {
  47782. if (entry.isDirectory) {
  47783. folders.push(entry);
  47784. }
  47785. else {
  47786. files_1.push(fileToLoad);
  47787. }
  47788. }
  47789. }
  47790. if (folders.length === 0) {
  47791. this._processFiles(files_1);
  47792. }
  47793. else {
  47794. var remaining = folders.length;
  47795. // Extract folder content
  47796. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  47797. var folder = folders_1[_i];
  47798. this._handleFolderDrop(folder, files_1, function () {
  47799. remaining--;
  47800. if (remaining === 0) {
  47801. _this._processFiles(files_1);
  47802. }
  47803. });
  47804. }
  47805. }
  47806. }
  47807. };
  47808. FilesInput.prototype.reload = function () {
  47809. var _this = this;
  47810. var that = this;
  47811. // If a ".babylon" file has been provided
  47812. if (this._sceneFileToLoad) {
  47813. if (this._currentScene) {
  47814. if (BABYLON.Tools.errorsCount > 0) {
  47815. BABYLON.Tools.ClearLogCache();
  47816. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  47817. }
  47818. this._engine.stopRenderLoop();
  47819. this._currentScene.dispose();
  47820. }
  47821. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  47822. that._currentScene = newScene;
  47823. // Wait for textures and shaders to be ready
  47824. that._currentScene.executeWhenReady(function () {
  47825. if (that._sceneLoadedCallback) {
  47826. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  47827. }
  47828. that._engine.runRenderLoop(function () { that.renderFunction(); });
  47829. });
  47830. }, function (progress) {
  47831. if (_this._progressCallback) {
  47832. _this._progressCallback(progress);
  47833. }
  47834. });
  47835. }
  47836. else {
  47837. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  47838. }
  47839. };
  47840. return FilesInput;
  47841. }());
  47842. FilesInput.FilesToLoad = new Array();
  47843. BABYLON.FilesInput = FilesInput;
  47844. })(BABYLON || (BABYLON = {}));
  47845. //# sourceMappingURL=babylon.filesInput.js.map
  47846. var BABYLON;
  47847. (function (BABYLON) {
  47848. /**
  47849. * This class implement a typical dictionary using a string as key and the generic type T as value.
  47850. * The underlying implementation relies on an associative array to ensure the best performances.
  47851. * The value can be anything including 'null' but except 'undefined'
  47852. */
  47853. var StringDictionary = (function () {
  47854. function StringDictionary() {
  47855. this._count = 0;
  47856. this._data = {};
  47857. }
  47858. /**
  47859. * This will clear this dictionary and copy the content from the 'source' one.
  47860. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  47861. * @param source the dictionary to take the content from and copy to this dictionary
  47862. */
  47863. StringDictionary.prototype.copyFrom = function (source) {
  47864. var _this = this;
  47865. this.clear();
  47866. source.forEach(function (t, v) { return _this.add(t, v); });
  47867. };
  47868. /**
  47869. * Get a value based from its key
  47870. * @param key the given key to get the matching value from
  47871. * @return the value if found, otherwise undefined is returned
  47872. */
  47873. StringDictionary.prototype.get = function (key) {
  47874. var val = this._data[key];
  47875. if (val !== undefined) {
  47876. return val;
  47877. }
  47878. return undefined;
  47879. };
  47880. /**
  47881. * Get a value from its key or add it if it doesn't exist.
  47882. * This method will ensure you that a given key/data will be present in the dictionary.
  47883. * @param key the given key to get the matching value from
  47884. * @param factory the factory that will create the value if the key is not present in the dictionary.
  47885. * The factory will only be invoked if there's no data for the given key.
  47886. * @return the value corresponding to the key.
  47887. */
  47888. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  47889. var val = this.get(key);
  47890. if (val !== undefined) {
  47891. return val;
  47892. }
  47893. val = factory(key);
  47894. if (val) {
  47895. this.add(key, val);
  47896. }
  47897. return val;
  47898. };
  47899. /**
  47900. * Get a value from its key if present in the dictionary otherwise add it
  47901. * @param key the key to get the value from
  47902. * @param val if there's no such key/value pair in the dictionary add it with this value
  47903. * @return the value corresponding to the key
  47904. */
  47905. StringDictionary.prototype.getOrAdd = function (key, val) {
  47906. var curVal = this.get(key);
  47907. if (curVal !== undefined) {
  47908. return curVal;
  47909. }
  47910. this.add(key, val);
  47911. return val;
  47912. };
  47913. /**
  47914. * Check if there's a given key in the dictionary
  47915. * @param key the key to check for
  47916. * @return true if the key is present, false otherwise
  47917. */
  47918. StringDictionary.prototype.contains = function (key) {
  47919. return this._data[key] !== undefined;
  47920. };
  47921. /**
  47922. * Add a new key and its corresponding value
  47923. * @param key the key to add
  47924. * @param value the value corresponding to the key
  47925. * @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
  47926. */
  47927. StringDictionary.prototype.add = function (key, value) {
  47928. if (this._data[key] !== undefined) {
  47929. return false;
  47930. }
  47931. this._data[key] = value;
  47932. ++this._count;
  47933. return true;
  47934. };
  47935. StringDictionary.prototype.set = function (key, value) {
  47936. if (this._data[key] === undefined) {
  47937. return false;
  47938. }
  47939. this._data[key] = value;
  47940. return true;
  47941. };
  47942. /**
  47943. * Get the element of the given key and remove it from the dictionary
  47944. * @param key
  47945. */
  47946. StringDictionary.prototype.getAndRemove = function (key) {
  47947. var val = this.get(key);
  47948. if (val !== undefined) {
  47949. delete this._data[key];
  47950. --this._count;
  47951. return val;
  47952. }
  47953. return null;
  47954. };
  47955. /**
  47956. * Remove a key/value from the dictionary.
  47957. * @param key the key to remove
  47958. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  47959. */
  47960. StringDictionary.prototype.remove = function (key) {
  47961. if (this.contains(key)) {
  47962. delete this._data[key];
  47963. --this._count;
  47964. return true;
  47965. }
  47966. return false;
  47967. };
  47968. /**
  47969. * Clear the whole content of the dictionary
  47970. */
  47971. StringDictionary.prototype.clear = function () {
  47972. this._data = {};
  47973. this._count = 0;
  47974. };
  47975. Object.defineProperty(StringDictionary.prototype, "count", {
  47976. get: function () {
  47977. return this._count;
  47978. },
  47979. enumerable: true,
  47980. configurable: true
  47981. });
  47982. /**
  47983. * Execute a callback on each key/val of the dictionary.
  47984. * Note that you can remove any element in this dictionary in the callback implementation
  47985. * @param callback the callback to execute on a given key/value pair
  47986. */
  47987. StringDictionary.prototype.forEach = function (callback) {
  47988. for (var cur in this._data) {
  47989. var val = this._data[cur];
  47990. callback(cur, val);
  47991. }
  47992. };
  47993. /**
  47994. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  47995. * If the callback returns null or undefined the method will iterate to the next key/value pair
  47996. * Note that you can remove any element in this dictionary in the callback implementation
  47997. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  47998. */
  47999. StringDictionary.prototype.first = function (callback) {
  48000. for (var cur in this._data) {
  48001. var val = this._data[cur];
  48002. var res = callback(cur, val);
  48003. if (res) {
  48004. return res;
  48005. }
  48006. }
  48007. return null;
  48008. };
  48009. return StringDictionary;
  48010. }());
  48011. BABYLON.StringDictionary = StringDictionary;
  48012. })(BABYLON || (BABYLON = {}));
  48013. //# sourceMappingURL=babylon.stringDictionary.js.map
  48014. var BABYLON;
  48015. (function (BABYLON) {
  48016. var Tags = (function () {
  48017. function Tags() {
  48018. }
  48019. Tags.EnableFor = function (obj) {
  48020. obj._tags = obj._tags || {};
  48021. obj.hasTags = function () {
  48022. return Tags.HasTags(obj);
  48023. };
  48024. obj.addTags = function (tagsString) {
  48025. return Tags.AddTagsTo(obj, tagsString);
  48026. };
  48027. obj.removeTags = function (tagsString) {
  48028. return Tags.RemoveTagsFrom(obj, tagsString);
  48029. };
  48030. obj.matchesTagsQuery = function (tagsQuery) {
  48031. return Tags.MatchesQuery(obj, tagsQuery);
  48032. };
  48033. };
  48034. Tags.DisableFor = function (obj) {
  48035. delete obj._tags;
  48036. delete obj.hasTags;
  48037. delete obj.addTags;
  48038. delete obj.removeTags;
  48039. delete obj.matchesTagsQuery;
  48040. };
  48041. Tags.HasTags = function (obj) {
  48042. if (!obj._tags) {
  48043. return false;
  48044. }
  48045. return !BABYLON.Tools.IsEmpty(obj._tags);
  48046. };
  48047. Tags.GetTags = function (obj, asString) {
  48048. if (asString === void 0) { asString = true; }
  48049. if (!obj._tags) {
  48050. return null;
  48051. }
  48052. if (asString) {
  48053. var tagsArray = [];
  48054. for (var tag in obj._tags) {
  48055. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  48056. tagsArray.push(tag);
  48057. }
  48058. }
  48059. return tagsArray.join(" ");
  48060. }
  48061. else {
  48062. return obj._tags;
  48063. }
  48064. };
  48065. // the tags 'true' and 'false' are reserved and cannot be used as tags
  48066. // a tag cannot start with '||', '&&', and '!'
  48067. // it cannot contain whitespaces
  48068. Tags.AddTagsTo = function (obj, tagsString) {
  48069. if (!tagsString) {
  48070. return;
  48071. }
  48072. if (typeof tagsString !== "string") {
  48073. return;
  48074. }
  48075. var tags = tagsString.split(" ");
  48076. tags.forEach(function (tag, index, array) {
  48077. Tags._AddTagTo(obj, tag);
  48078. });
  48079. };
  48080. Tags._AddTagTo = function (obj, tag) {
  48081. tag = tag.trim();
  48082. if (tag === "" || tag === "true" || tag === "false") {
  48083. return;
  48084. }
  48085. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  48086. return;
  48087. }
  48088. Tags.EnableFor(obj);
  48089. obj._tags[tag] = true;
  48090. };
  48091. Tags.RemoveTagsFrom = function (obj, tagsString) {
  48092. if (!Tags.HasTags(obj)) {
  48093. return;
  48094. }
  48095. var tags = tagsString.split(" ");
  48096. for (var t in tags) {
  48097. Tags._RemoveTagFrom(obj, tags[t]);
  48098. }
  48099. };
  48100. Tags._RemoveTagFrom = function (obj, tag) {
  48101. delete obj._tags[tag];
  48102. };
  48103. Tags.MatchesQuery = function (obj, tagsQuery) {
  48104. if (tagsQuery === undefined) {
  48105. return true;
  48106. }
  48107. if (tagsQuery === "") {
  48108. return Tags.HasTags(obj);
  48109. }
  48110. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  48111. };
  48112. return Tags;
  48113. }());
  48114. BABYLON.Tags = Tags;
  48115. })(BABYLON || (BABYLON = {}));
  48116. //# sourceMappingURL=babylon.tags.js.map
  48117. var BABYLON;
  48118. (function (BABYLON) {
  48119. var Internals;
  48120. (function (Internals) {
  48121. var AndOrNotEvaluator = (function () {
  48122. function AndOrNotEvaluator() {
  48123. }
  48124. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  48125. if (!query.match(/\([^\(\)]*\)/g)) {
  48126. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  48127. }
  48128. else {
  48129. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  48130. // remove parenthesis
  48131. r = r.slice(1, r.length - 1);
  48132. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  48133. });
  48134. }
  48135. if (query === "true") {
  48136. return true;
  48137. }
  48138. if (query === "false") {
  48139. return false;
  48140. }
  48141. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  48142. };
  48143. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  48144. evaluateCallback = evaluateCallback || (function (r) {
  48145. return r === "true" ? true : false;
  48146. });
  48147. var result;
  48148. var or = parenthesisContent.split("||");
  48149. for (var i in or) {
  48150. if (or.hasOwnProperty(i)) {
  48151. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  48152. var and = ori.split("&&");
  48153. if (and.length > 1) {
  48154. for (var j = 0; j < and.length; ++j) {
  48155. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  48156. if (andj !== "true" && andj !== "false") {
  48157. if (andj[0] === "!") {
  48158. result = !evaluateCallback(andj.substring(1));
  48159. }
  48160. else {
  48161. result = evaluateCallback(andj);
  48162. }
  48163. }
  48164. else {
  48165. result = andj === "true" ? true : false;
  48166. }
  48167. if (!result) {
  48168. ori = "false";
  48169. break;
  48170. }
  48171. }
  48172. }
  48173. if (result || ori === "true") {
  48174. result = true;
  48175. break;
  48176. }
  48177. // result equals false (or undefined)
  48178. if (ori !== "true" && ori !== "false") {
  48179. if (ori[0] === "!") {
  48180. result = !evaluateCallback(ori.substring(1));
  48181. }
  48182. else {
  48183. result = evaluateCallback(ori);
  48184. }
  48185. }
  48186. else {
  48187. result = ori === "true" ? true : false;
  48188. }
  48189. }
  48190. }
  48191. // the whole parenthesis scope is replaced by 'true' or 'false'
  48192. return result ? "true" : "false";
  48193. };
  48194. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  48195. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  48196. // remove whitespaces
  48197. r = r.replace(/[\s]/g, function () { return ""; });
  48198. return r.length % 2 ? "!" : "";
  48199. });
  48200. booleanString = booleanString.trim();
  48201. if (booleanString === "!true") {
  48202. booleanString = "false";
  48203. }
  48204. else if (booleanString === "!false") {
  48205. booleanString = "true";
  48206. }
  48207. return booleanString;
  48208. };
  48209. return AndOrNotEvaluator;
  48210. }());
  48211. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  48212. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48213. })(BABYLON || (BABYLON = {}));
  48214. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  48215. var BABYLON;
  48216. (function (BABYLON) {
  48217. var Database = (function () {
  48218. function Database(urlToScene, callbackManifestChecked) {
  48219. // Handling various flavors of prefixed version of IndexedDB
  48220. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  48221. this.callbackManifestChecked = callbackManifestChecked;
  48222. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  48223. this.db = null;
  48224. this.enableSceneOffline = false;
  48225. this.enableTexturesOffline = false;
  48226. this.manifestVersionFound = 0;
  48227. this.mustUpdateRessources = false;
  48228. this.hasReachedQuota = false;
  48229. if (!Database.IDBStorageEnabled) {
  48230. this.callbackManifestChecked(true);
  48231. }
  48232. else {
  48233. this.checkManifestFile();
  48234. }
  48235. }
  48236. Database.prototype.checkManifestFile = function () {
  48237. var _this = this;
  48238. function noManifestFile() {
  48239. that.enableSceneOffline = false;
  48240. that.enableTexturesOffline = false;
  48241. that.callbackManifestChecked(false);
  48242. }
  48243. var that = this;
  48244. var timeStampUsed = false;
  48245. var manifestURL = this.currentSceneUrl + ".manifest";
  48246. var xhr = new XMLHttpRequest();
  48247. if (navigator.onLine) {
  48248. // Adding a timestamp to by-pass browsers' cache
  48249. timeStampUsed = true;
  48250. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  48251. }
  48252. xhr.open("GET", manifestURL, true);
  48253. xhr.addEventListener("load", function () {
  48254. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  48255. try {
  48256. var manifestFile = JSON.parse(xhr.response);
  48257. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  48258. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  48259. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  48260. _this.manifestVersionFound = manifestFile.version;
  48261. }
  48262. if (_this.callbackManifestChecked) {
  48263. _this.callbackManifestChecked(true);
  48264. }
  48265. }
  48266. catch (ex) {
  48267. noManifestFile();
  48268. }
  48269. }
  48270. else {
  48271. noManifestFile();
  48272. }
  48273. }, false);
  48274. xhr.addEventListener("error", function (event) {
  48275. if (timeStampUsed) {
  48276. timeStampUsed = false;
  48277. // Let's retry without the timeStamp
  48278. // It could fail when coupled with HTML5 Offline API
  48279. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  48280. xhr.open("GET", retryManifestURL, true);
  48281. xhr.send();
  48282. }
  48283. else {
  48284. noManifestFile();
  48285. }
  48286. }, false);
  48287. try {
  48288. xhr.send();
  48289. }
  48290. catch (ex) {
  48291. BABYLON.Tools.Error("Error on XHR send request.");
  48292. that.callbackManifestChecked(false);
  48293. }
  48294. };
  48295. Database.prototype.openAsync = function (successCallback, errorCallback) {
  48296. var _this = this;
  48297. function handleError() {
  48298. that.isSupported = false;
  48299. if (errorCallback)
  48300. errorCallback();
  48301. }
  48302. var that = this;
  48303. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  48304. // Your browser doesn't support IndexedDB
  48305. this.isSupported = false;
  48306. if (errorCallback)
  48307. errorCallback();
  48308. }
  48309. else {
  48310. // If the DB hasn't been opened or created yet
  48311. if (!this.db) {
  48312. this.hasReachedQuota = false;
  48313. this.isSupported = true;
  48314. var request = this.idbFactory.open("babylonjs", 1);
  48315. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  48316. request.onerror = function (event) {
  48317. handleError();
  48318. };
  48319. // executes when a version change transaction cannot complete due to other active transactions
  48320. request.onblocked = function (event) {
  48321. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  48322. handleError();
  48323. };
  48324. // DB has been opened successfully
  48325. request.onsuccess = function (event) {
  48326. _this.db = request.result;
  48327. successCallback();
  48328. };
  48329. // Initialization of the DB. Creating Scenes & Textures stores
  48330. request.onupgradeneeded = function (event) {
  48331. _this.db = (event.target).result;
  48332. try {
  48333. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  48334. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  48335. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  48336. }
  48337. catch (ex) {
  48338. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  48339. handleError();
  48340. }
  48341. };
  48342. }
  48343. else {
  48344. if (successCallback)
  48345. successCallback();
  48346. }
  48347. }
  48348. };
  48349. Database.prototype.loadImageFromDB = function (url, image) {
  48350. var _this = this;
  48351. var completeURL = Database.ReturnFullUrlLocation(url);
  48352. var saveAndLoadImage = function () {
  48353. if (!_this.hasReachedQuota && _this.db !== null) {
  48354. // the texture is not yet in the DB, let's try to save it
  48355. _this._saveImageIntoDBAsync(completeURL, image);
  48356. }
  48357. else {
  48358. image.src = url;
  48359. }
  48360. };
  48361. if (!this.mustUpdateRessources) {
  48362. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  48363. }
  48364. else {
  48365. saveAndLoadImage();
  48366. }
  48367. };
  48368. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  48369. if (this.isSupported && this.db !== null) {
  48370. var texture;
  48371. var transaction = this.db.transaction(["textures"]);
  48372. transaction.onabort = function (event) {
  48373. image.src = url;
  48374. };
  48375. transaction.oncomplete = function (event) {
  48376. var blobTextureURL;
  48377. if (texture) {
  48378. var URL = window.URL || window.webkitURL;
  48379. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  48380. image.onerror = function () {
  48381. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  48382. image.src = url;
  48383. };
  48384. image.src = blobTextureURL;
  48385. }
  48386. else {
  48387. notInDBCallback();
  48388. }
  48389. };
  48390. var getRequest = transaction.objectStore("textures").get(url);
  48391. getRequest.onsuccess = function (event) {
  48392. texture = (event.target).result;
  48393. };
  48394. getRequest.onerror = function (event) {
  48395. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  48396. image.src = url;
  48397. };
  48398. }
  48399. else {
  48400. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  48401. image.src = url;
  48402. }
  48403. };
  48404. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  48405. var _this = this;
  48406. if (this.isSupported) {
  48407. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  48408. var generateBlobUrl = function () {
  48409. var blobTextureURL;
  48410. if (blob) {
  48411. var URL = window.URL || window.webkitURL;
  48412. try {
  48413. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  48414. }
  48415. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  48416. catch (ex) {
  48417. blobTextureURL = URL.createObjectURL(blob);
  48418. }
  48419. }
  48420. image.src = blobTextureURL;
  48421. };
  48422. if (Database.IsUASupportingBlobStorage) {
  48423. var xhr = new XMLHttpRequest(), blob;
  48424. xhr.open("GET", url, true);
  48425. xhr.responseType = "blob";
  48426. xhr.addEventListener("load", function () {
  48427. if (xhr.status === 200) {
  48428. // Blob as response (XHR2)
  48429. blob = xhr.response;
  48430. var transaction = _this.db.transaction(["textures"], "readwrite");
  48431. // the transaction could abort because of a QuotaExceededError error
  48432. transaction.onabort = function (event) {
  48433. try {
  48434. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  48435. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  48436. _this.hasReachedQuota = true;
  48437. }
  48438. }
  48439. catch (ex) { }
  48440. generateBlobUrl();
  48441. };
  48442. transaction.oncomplete = function (event) {
  48443. generateBlobUrl();
  48444. };
  48445. var newTexture = { textureUrl: url, data: blob };
  48446. try {
  48447. // Put the blob into the dabase
  48448. var addRequest = transaction.objectStore("textures").put(newTexture);
  48449. addRequest.onsuccess = function (event) {
  48450. };
  48451. addRequest.onerror = function (event) {
  48452. generateBlobUrl();
  48453. };
  48454. }
  48455. catch (ex) {
  48456. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  48457. if (ex.code === 25) {
  48458. Database.IsUASupportingBlobStorage = false;
  48459. }
  48460. image.src = url;
  48461. }
  48462. }
  48463. else {
  48464. image.src = url;
  48465. }
  48466. }, false);
  48467. xhr.addEventListener("error", function (event) {
  48468. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  48469. image.src = url;
  48470. }, false);
  48471. xhr.send();
  48472. }
  48473. else {
  48474. image.src = url;
  48475. }
  48476. }
  48477. else {
  48478. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  48479. image.src = url;
  48480. }
  48481. };
  48482. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  48483. var _this = this;
  48484. var updateVersion = function (event) {
  48485. // the version is not yet in the DB or we need to update it
  48486. _this._saveVersionIntoDBAsync(url, versionLoaded);
  48487. };
  48488. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  48489. };
  48490. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  48491. var _this = this;
  48492. if (this.isSupported) {
  48493. var version;
  48494. try {
  48495. var transaction = this.db.transaction(["versions"]);
  48496. transaction.oncomplete = function (event) {
  48497. if (version) {
  48498. // If the version in the JSON file is > than the version in DB
  48499. if (_this.manifestVersionFound > version.data) {
  48500. _this.mustUpdateRessources = true;
  48501. updateInDBCallback();
  48502. }
  48503. else {
  48504. callback(version.data);
  48505. }
  48506. }
  48507. else {
  48508. _this.mustUpdateRessources = true;
  48509. updateInDBCallback();
  48510. }
  48511. };
  48512. transaction.onabort = function (event) {
  48513. callback(-1);
  48514. };
  48515. var getRequest = transaction.objectStore("versions").get(url);
  48516. getRequest.onsuccess = function (event) {
  48517. version = (event.target).result;
  48518. };
  48519. getRequest.onerror = function (event) {
  48520. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  48521. callback(-1);
  48522. };
  48523. }
  48524. catch (ex) {
  48525. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  48526. callback(-1);
  48527. }
  48528. }
  48529. else {
  48530. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  48531. callback(-1);
  48532. }
  48533. };
  48534. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  48535. var _this = this;
  48536. if (this.isSupported && !this.hasReachedQuota) {
  48537. try {
  48538. // Open a transaction to the database
  48539. var transaction = this.db.transaction(["versions"], "readwrite");
  48540. // the transaction could abort because of a QuotaExceededError error
  48541. transaction.onabort = function (event) {
  48542. try {
  48543. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  48544. _this.hasReachedQuota = true;
  48545. }
  48546. }
  48547. catch (ex) { }
  48548. callback(-1);
  48549. };
  48550. transaction.oncomplete = function (event) {
  48551. callback(_this.manifestVersionFound);
  48552. };
  48553. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  48554. // Put the scene into the database
  48555. var addRequest = transaction.objectStore("versions").put(newVersion);
  48556. addRequest.onsuccess = function (event) {
  48557. };
  48558. addRequest.onerror = function (event) {
  48559. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  48560. };
  48561. }
  48562. catch (ex) {
  48563. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  48564. callback(-1);
  48565. }
  48566. }
  48567. else {
  48568. callback(-1);
  48569. }
  48570. };
  48571. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  48572. var _this = this;
  48573. var completeUrl = Database.ReturnFullUrlLocation(url);
  48574. var saveAndLoadFile = function (event) {
  48575. // the scene is not yet in the DB, let's try to save it
  48576. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  48577. };
  48578. this._checkVersionFromDB(completeUrl, function (version) {
  48579. if (version !== -1) {
  48580. if (!_this.mustUpdateRessources) {
  48581. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  48582. }
  48583. else {
  48584. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  48585. }
  48586. }
  48587. else {
  48588. errorCallback();
  48589. }
  48590. });
  48591. };
  48592. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  48593. if (this.isSupported) {
  48594. var targetStore;
  48595. if (url.indexOf(".babylon") !== -1) {
  48596. targetStore = "scenes";
  48597. }
  48598. else {
  48599. targetStore = "textures";
  48600. }
  48601. var file;
  48602. var transaction = this.db.transaction([targetStore]);
  48603. transaction.oncomplete = function (event) {
  48604. if (file) {
  48605. callback(file.data);
  48606. }
  48607. else {
  48608. notInDBCallback();
  48609. }
  48610. };
  48611. transaction.onabort = function (event) {
  48612. notInDBCallback();
  48613. };
  48614. var getRequest = transaction.objectStore(targetStore).get(url);
  48615. getRequest.onsuccess = function (event) {
  48616. file = (event.target).result;
  48617. };
  48618. getRequest.onerror = function (event) {
  48619. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  48620. notInDBCallback();
  48621. };
  48622. }
  48623. else {
  48624. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  48625. callback();
  48626. }
  48627. };
  48628. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  48629. var _this = this;
  48630. if (this.isSupported) {
  48631. var targetStore;
  48632. if (url.indexOf(".babylon") !== -1) {
  48633. targetStore = "scenes";
  48634. }
  48635. else {
  48636. targetStore = "textures";
  48637. }
  48638. // Create XHR
  48639. var xhr = new XMLHttpRequest(), fileData;
  48640. xhr.open("GET", url, true);
  48641. if (useArrayBuffer) {
  48642. xhr.responseType = "arraybuffer";
  48643. }
  48644. xhr.onprogress = progressCallback;
  48645. xhr.addEventListener("load", function () {
  48646. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  48647. // Blob as response (XHR2)
  48648. //fileData = xhr.responseText;
  48649. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  48650. if (!_this.hasReachedQuota) {
  48651. // Open a transaction to the database
  48652. var transaction = _this.db.transaction([targetStore], "readwrite");
  48653. // the transaction could abort because of a QuotaExceededError error
  48654. transaction.onabort = function (event) {
  48655. try {
  48656. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  48657. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  48658. _this.hasReachedQuota = true;
  48659. }
  48660. }
  48661. catch (ex) { }
  48662. callback(fileData);
  48663. };
  48664. transaction.oncomplete = function (event) {
  48665. callback(fileData);
  48666. };
  48667. var newFile;
  48668. if (targetStore === "scenes") {
  48669. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  48670. }
  48671. else {
  48672. newFile = { textureUrl: url, data: fileData };
  48673. }
  48674. try {
  48675. // Put the scene into the database
  48676. var addRequest = transaction.objectStore(targetStore).put(newFile);
  48677. addRequest.onsuccess = function (event) {
  48678. };
  48679. addRequest.onerror = function (event) {
  48680. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  48681. };
  48682. }
  48683. catch (ex) {
  48684. callback(fileData);
  48685. }
  48686. }
  48687. else {
  48688. callback(fileData);
  48689. }
  48690. }
  48691. else {
  48692. callback();
  48693. }
  48694. }, false);
  48695. xhr.addEventListener("error", function (event) {
  48696. BABYLON.Tools.Error("error on XHR request.");
  48697. callback();
  48698. }, false);
  48699. xhr.send();
  48700. }
  48701. else {
  48702. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  48703. callback();
  48704. }
  48705. };
  48706. return Database;
  48707. }());
  48708. Database.IsUASupportingBlobStorage = true;
  48709. Database.IDBStorageEnabled = true;
  48710. Database.parseURL = function (url) {
  48711. var a = document.createElement('a');
  48712. a.href = url;
  48713. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  48714. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  48715. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  48716. return absLocation;
  48717. };
  48718. Database.ReturnFullUrlLocation = function (url) {
  48719. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  48720. return (Database.parseURL(window.location.href) + url);
  48721. }
  48722. else {
  48723. return url;
  48724. }
  48725. };
  48726. BABYLON.Database = Database;
  48727. })(BABYLON || (BABYLON = {}));
  48728. //# sourceMappingURL=babylon.database.js.map
  48729. var BABYLON;
  48730. (function (BABYLON) {
  48731. var FresnelParameters = (function () {
  48732. function FresnelParameters() {
  48733. this._isEnabled = true;
  48734. this.leftColor = BABYLON.Color3.White();
  48735. this.rightColor = BABYLON.Color3.Black();
  48736. this.bias = 0;
  48737. this.power = 1;
  48738. }
  48739. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  48740. get: function () {
  48741. return this._isEnabled;
  48742. },
  48743. set: function (value) {
  48744. if (this._isEnabled === value) {
  48745. return;
  48746. }
  48747. this._isEnabled = value;
  48748. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  48749. },
  48750. enumerable: true,
  48751. configurable: true
  48752. });
  48753. FresnelParameters.prototype.clone = function () {
  48754. var newFresnelParameters = new FresnelParameters();
  48755. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  48756. return newFresnelParameters;
  48757. };
  48758. FresnelParameters.prototype.serialize = function () {
  48759. var serializationObject = {};
  48760. serializationObject.isEnabled = this.isEnabled;
  48761. serializationObject.leftColor = this.leftColor;
  48762. serializationObject.rightColor = this.rightColor;
  48763. serializationObject.bias = this.bias;
  48764. serializationObject.power = this.power;
  48765. return serializationObject;
  48766. };
  48767. FresnelParameters.Parse = function (parsedFresnelParameters) {
  48768. var fresnelParameters = new FresnelParameters();
  48769. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  48770. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  48771. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  48772. fresnelParameters.bias = parsedFresnelParameters.bias;
  48773. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  48774. return fresnelParameters;
  48775. };
  48776. return FresnelParameters;
  48777. }());
  48778. BABYLON.FresnelParameters = FresnelParameters;
  48779. })(BABYLON || (BABYLON = {}));
  48780. //# sourceMappingURL=babylon.fresnelParameters.js.map
  48781. var BABYLON;
  48782. (function (BABYLON) {
  48783. var MultiMaterial = (function (_super) {
  48784. __extends(MultiMaterial, _super);
  48785. function MultiMaterial(name, scene) {
  48786. var _this = _super.call(this, name, scene, true) || this;
  48787. scene.multiMaterials.push(_this);
  48788. _this.subMaterials = new Array();
  48789. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  48790. return _this;
  48791. }
  48792. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  48793. get: function () {
  48794. return this._subMaterials;
  48795. },
  48796. set: function (value) {
  48797. this._subMaterials = value;
  48798. this._hookArray(value);
  48799. },
  48800. enumerable: true,
  48801. configurable: true
  48802. });
  48803. MultiMaterial.prototype._hookArray = function (array) {
  48804. var _this = this;
  48805. var oldPush = array.push;
  48806. array.push = function () {
  48807. var items = [];
  48808. for (var _i = 0; _i < arguments.length; _i++) {
  48809. items[_i] = arguments[_i];
  48810. }
  48811. var result = oldPush.apply(array, items);
  48812. _this._markAllSubMeshesAsTexturesDirty();
  48813. return result;
  48814. };
  48815. var oldSplice = array.splice;
  48816. array.splice = function (index, deleteCount) {
  48817. var deleted = oldSplice.apply(array, [index, deleteCount]);
  48818. _this._markAllSubMeshesAsTexturesDirty();
  48819. return deleted;
  48820. };
  48821. };
  48822. // Properties
  48823. MultiMaterial.prototype.getSubMaterial = function (index) {
  48824. if (index < 0 || index >= this.subMaterials.length) {
  48825. return this.getScene().defaultMaterial;
  48826. }
  48827. return this.subMaterials[index];
  48828. };
  48829. MultiMaterial.prototype.getActiveTextures = function () {
  48830. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) { return subMaterial.getActiveTextures(); }));
  48831. var _a;
  48832. };
  48833. // Methods
  48834. MultiMaterial.prototype.getClassName = function () {
  48835. return "MultiMaterial";
  48836. };
  48837. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  48838. for (var index = 0; index < this.subMaterials.length; index++) {
  48839. var subMaterial = this.subMaterials[index];
  48840. if (subMaterial) {
  48841. if (this.subMaterials[index].storeEffectOnSubMeshes) {
  48842. if (!this.subMaterials[index].isReadyForSubMesh(mesh, subMesh, useInstances)) {
  48843. return false;
  48844. }
  48845. continue;
  48846. }
  48847. if (!this.subMaterials[index].isReady(mesh)) {
  48848. return false;
  48849. }
  48850. }
  48851. }
  48852. return true;
  48853. };
  48854. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  48855. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  48856. for (var index = 0; index < this.subMaterials.length; index++) {
  48857. var subMaterial = null;
  48858. if (cloneChildren) {
  48859. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  48860. }
  48861. else {
  48862. subMaterial = this.subMaterials[index];
  48863. }
  48864. newMultiMaterial.subMaterials.push(subMaterial);
  48865. }
  48866. return newMultiMaterial;
  48867. };
  48868. MultiMaterial.prototype.serialize = function () {
  48869. var serializationObject = {};
  48870. serializationObject.name = this.name;
  48871. serializationObject.id = this.id;
  48872. serializationObject.tags = BABYLON.Tags.GetTags(this);
  48873. serializationObject.materials = [];
  48874. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  48875. var subMat = this.subMaterials[matIndex];
  48876. if (subMat) {
  48877. serializationObject.materials.push(subMat.id);
  48878. }
  48879. else {
  48880. serializationObject.materials.push(null);
  48881. }
  48882. }
  48883. return serializationObject;
  48884. };
  48885. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  48886. var scene = this.getScene();
  48887. if (!scene) {
  48888. return;
  48889. }
  48890. var index = scene.multiMaterials.indexOf(this);
  48891. if (index >= 0) {
  48892. scene.multiMaterials.splice(index, 1);
  48893. }
  48894. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  48895. };
  48896. return MultiMaterial;
  48897. }(BABYLON.Material));
  48898. BABYLON.MultiMaterial = MultiMaterial;
  48899. })(BABYLON || (BABYLON = {}));
  48900. //# sourceMappingURL=babylon.multiMaterial.js.map
  48901. var BABYLON;
  48902. (function (BABYLON) {
  48903. var FreeCameraTouchInput = (function () {
  48904. function FreeCameraTouchInput() {
  48905. this._offsetX = null;
  48906. this._offsetY = null;
  48907. this._pointerCount = 0;
  48908. this._pointerPressed = [];
  48909. this.touchAngularSensibility = 200000.0;
  48910. this.touchMoveSensibility = 250.0;
  48911. }
  48912. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  48913. var _this = this;
  48914. var previousPosition;
  48915. if (this._pointerInput === undefined) {
  48916. this._onLostFocus = function (evt) {
  48917. _this._offsetX = null;
  48918. _this._offsetY = null;
  48919. };
  48920. this._pointerInput = function (p, s) {
  48921. var evt = p.event;
  48922. if (evt.pointerType === "mouse") {
  48923. return;
  48924. }
  48925. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  48926. if (!noPreventDefault) {
  48927. evt.preventDefault();
  48928. }
  48929. _this._pointerPressed.push(evt.pointerId);
  48930. if (_this._pointerPressed.length !== 1) {
  48931. return;
  48932. }
  48933. previousPosition = {
  48934. x: evt.clientX,
  48935. y: evt.clientY
  48936. };
  48937. }
  48938. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  48939. if (!noPreventDefault) {
  48940. evt.preventDefault();
  48941. }
  48942. var index = _this._pointerPressed.indexOf(evt.pointerId);
  48943. if (index === -1) {
  48944. return;
  48945. }
  48946. _this._pointerPressed.splice(index, 1);
  48947. if (index != 0) {
  48948. return;
  48949. }
  48950. previousPosition = null;
  48951. _this._offsetX = null;
  48952. _this._offsetY = null;
  48953. }
  48954. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48955. if (!noPreventDefault) {
  48956. evt.preventDefault();
  48957. }
  48958. if (!previousPosition) {
  48959. return;
  48960. }
  48961. var index = _this._pointerPressed.indexOf(evt.pointerId);
  48962. if (index != 0) {
  48963. return;
  48964. }
  48965. _this._offsetX = evt.clientX - previousPosition.x;
  48966. _this._offsetY = -(evt.clientY - previousPosition.y);
  48967. }
  48968. };
  48969. }
  48970. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  48971. element.addEventListener("blur", this._onLostFocus);
  48972. };
  48973. FreeCameraTouchInput.prototype.detachControl = function (element) {
  48974. if (this._pointerInput && element) {
  48975. this.camera.getScene().onPointerObservable.remove(this._observer);
  48976. this._observer = null;
  48977. element.removeEventListener("blur", this._onLostFocus);
  48978. this._onLostFocus = null;
  48979. this._pointerPressed = [];
  48980. this._offsetX = null;
  48981. this._offsetY = null;
  48982. this._pointerCount = 0;
  48983. }
  48984. };
  48985. FreeCameraTouchInput.prototype.checkInputs = function () {
  48986. if (this._offsetX) {
  48987. var camera = this.camera;
  48988. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  48989. if (this._pointerPressed.length > 1) {
  48990. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  48991. }
  48992. else {
  48993. var speed = camera._computeLocalCameraSpeed();
  48994. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  48995. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  48996. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  48997. }
  48998. }
  48999. };
  49000. FreeCameraTouchInput.prototype.getClassName = function () {
  49001. return "FreeCameraTouchInput";
  49002. };
  49003. FreeCameraTouchInput.prototype.getSimpleName = function () {
  49004. return "touch";
  49005. };
  49006. return FreeCameraTouchInput;
  49007. }());
  49008. __decorate([
  49009. BABYLON.serialize()
  49010. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  49011. __decorate([
  49012. BABYLON.serialize()
  49013. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  49014. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  49015. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  49016. })(BABYLON || (BABYLON = {}));
  49017. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  49018. /// <reference path="babylon.freeCamera.ts" />
  49019. var BABYLON;
  49020. (function (BABYLON) {
  49021. // We're mainly based on the logic defined into the FreeCamera code
  49022. var TouchCamera = (function (_super) {
  49023. __extends(TouchCamera, _super);
  49024. //-- end properties for backward compatibility for inputs
  49025. function TouchCamera(name, position, scene) {
  49026. var _this = _super.call(this, name, position, scene) || this;
  49027. _this.inputs.addTouch();
  49028. _this._setupInputs();
  49029. return _this;
  49030. }
  49031. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  49032. //-- Begin properties for backward compatibility for inputs
  49033. get: function () {
  49034. var touch = this.inputs.attached["touch"];
  49035. if (touch)
  49036. return touch.touchAngularSensibility;
  49037. },
  49038. set: function (value) {
  49039. var touch = this.inputs.attached["touch"];
  49040. if (touch)
  49041. touch.touchAngularSensibility = value;
  49042. },
  49043. enumerable: true,
  49044. configurable: true
  49045. });
  49046. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  49047. get: function () {
  49048. var touch = this.inputs.attached["touch"];
  49049. if (touch)
  49050. return touch.touchMoveSensibility;
  49051. },
  49052. set: function (value) {
  49053. var touch = this.inputs.attached["touch"];
  49054. if (touch)
  49055. touch.touchMoveSensibility = value;
  49056. },
  49057. enumerable: true,
  49058. configurable: true
  49059. });
  49060. TouchCamera.prototype.getClassName = function () {
  49061. return "TouchCamera";
  49062. };
  49063. TouchCamera.prototype._setupInputs = function () {
  49064. var mouse = this.inputs.attached["mouse"];
  49065. if (mouse) {
  49066. mouse.touchEnabled = false;
  49067. }
  49068. };
  49069. return TouchCamera;
  49070. }(BABYLON.FreeCamera));
  49071. BABYLON.TouchCamera = TouchCamera;
  49072. })(BABYLON || (BABYLON = {}));
  49073. //# sourceMappingURL=babylon.touchCamera.js.map
  49074. var BABYLON;
  49075. (function (BABYLON) {
  49076. var ProceduralTexture = (function (_super) {
  49077. __extends(ProceduralTexture, _super);
  49078. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  49079. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49080. if (isCube === void 0) { isCube = false; }
  49081. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  49082. _this.isCube = isCube;
  49083. _this.isEnabled = true;
  49084. _this._currentRefreshId = -1;
  49085. _this._refreshRate = 1;
  49086. _this._vertexBuffers = {};
  49087. _this._uniforms = new Array();
  49088. _this._samplers = new Array();
  49089. _this._textures = new Array();
  49090. _this._floats = new Array();
  49091. _this._floatsArrays = {};
  49092. _this._colors3 = new Array();
  49093. _this._colors4 = new Array();
  49094. _this._vectors2 = new Array();
  49095. _this._vectors3 = new Array();
  49096. _this._matrices = new Array();
  49097. _this._fallbackTextureUsed = false;
  49098. scene._proceduralTextures.push(_this);
  49099. _this.name = name;
  49100. _this.isRenderTarget = true;
  49101. _this._size = size;
  49102. _this._generateMipMaps = generateMipMaps;
  49103. _this.setFragment(fragment);
  49104. _this._fallbackTexture = fallbackTexture;
  49105. var engine = scene.getEngine();
  49106. if (isCube) {
  49107. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  49108. _this.setFloat("face", 0);
  49109. }
  49110. else {
  49111. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  49112. }
  49113. // VBO
  49114. var vertices = [];
  49115. vertices.push(1, 1);
  49116. vertices.push(-1, 1);
  49117. vertices.push(-1, -1);
  49118. vertices.push(1, -1);
  49119. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  49120. // Indices
  49121. var indices = [];
  49122. indices.push(0);
  49123. indices.push(1);
  49124. indices.push(2);
  49125. indices.push(0);
  49126. indices.push(2);
  49127. indices.push(3);
  49128. _this._indexBuffer = engine.createIndexBuffer(indices);
  49129. return _this;
  49130. }
  49131. ProceduralTexture.prototype.reset = function () {
  49132. if (this._effect === undefined) {
  49133. return;
  49134. }
  49135. var engine = this.getScene().getEngine();
  49136. engine._releaseEffect(this._effect);
  49137. };
  49138. ProceduralTexture.prototype.isReady = function () {
  49139. var _this = this;
  49140. var engine = this.getScene().getEngine();
  49141. var shaders;
  49142. if (!this._fragment) {
  49143. return false;
  49144. }
  49145. if (this._fallbackTextureUsed) {
  49146. return true;
  49147. }
  49148. if (this._fragment.fragmentElement !== undefined) {
  49149. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  49150. }
  49151. else {
  49152. shaders = { vertex: "procedural", fragment: this._fragment };
  49153. }
  49154. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  49155. _this.releaseInternalTexture();
  49156. if (_this._fallbackTexture) {
  49157. _this._texture = _this._fallbackTexture._texture;
  49158. _this._texture.references++;
  49159. }
  49160. _this._fallbackTextureUsed = true;
  49161. });
  49162. return this._effect.isReady();
  49163. };
  49164. ProceduralTexture.prototype.resetRefreshCounter = function () {
  49165. this._currentRefreshId = -1;
  49166. };
  49167. ProceduralTexture.prototype.setFragment = function (fragment) {
  49168. this._fragment = fragment;
  49169. };
  49170. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  49171. get: function () {
  49172. return this._refreshRate;
  49173. },
  49174. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  49175. set: function (value) {
  49176. this._refreshRate = value;
  49177. this.resetRefreshCounter();
  49178. },
  49179. enumerable: true,
  49180. configurable: true
  49181. });
  49182. ProceduralTexture.prototype._shouldRender = function () {
  49183. if (!this.isEnabled || !this.isReady() || !this._texture) {
  49184. return false;
  49185. }
  49186. if (this._fallbackTextureUsed) {
  49187. return false;
  49188. }
  49189. if (this._currentRefreshId === -1) {
  49190. this._currentRefreshId = 1;
  49191. return true;
  49192. }
  49193. if (this.refreshRate === this._currentRefreshId) {
  49194. this._currentRefreshId = 1;
  49195. return true;
  49196. }
  49197. this._currentRefreshId++;
  49198. return false;
  49199. };
  49200. ProceduralTexture.prototype.getRenderSize = function () {
  49201. return this._size;
  49202. };
  49203. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  49204. if (this._fallbackTextureUsed) {
  49205. return;
  49206. }
  49207. this.releaseInternalTexture();
  49208. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  49209. };
  49210. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  49211. if (this._uniforms.indexOf(uniformName) === -1) {
  49212. this._uniforms.push(uniformName);
  49213. }
  49214. };
  49215. ProceduralTexture.prototype.setTexture = function (name, texture) {
  49216. if (this._samplers.indexOf(name) === -1) {
  49217. this._samplers.push(name);
  49218. }
  49219. this._textures[name] = texture;
  49220. return this;
  49221. };
  49222. ProceduralTexture.prototype.setFloat = function (name, value) {
  49223. this._checkUniform(name);
  49224. this._floats[name] = value;
  49225. return this;
  49226. };
  49227. ProceduralTexture.prototype.setFloats = function (name, value) {
  49228. this._checkUniform(name);
  49229. this._floatsArrays[name] = value;
  49230. return this;
  49231. };
  49232. ProceduralTexture.prototype.setColor3 = function (name, value) {
  49233. this._checkUniform(name);
  49234. this._colors3[name] = value;
  49235. return this;
  49236. };
  49237. ProceduralTexture.prototype.setColor4 = function (name, value) {
  49238. this._checkUniform(name);
  49239. this._colors4[name] = value;
  49240. return this;
  49241. };
  49242. ProceduralTexture.prototype.setVector2 = function (name, value) {
  49243. this._checkUniform(name);
  49244. this._vectors2[name] = value;
  49245. return this;
  49246. };
  49247. ProceduralTexture.prototype.setVector3 = function (name, value) {
  49248. this._checkUniform(name);
  49249. this._vectors3[name] = value;
  49250. return this;
  49251. };
  49252. ProceduralTexture.prototype.setMatrix = function (name, value) {
  49253. this._checkUniform(name);
  49254. this._matrices[name] = value;
  49255. return this;
  49256. };
  49257. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  49258. var scene = this.getScene();
  49259. var engine = scene.getEngine();
  49260. // Render
  49261. engine.enableEffect(this._effect);
  49262. engine.setState(false);
  49263. // Texture
  49264. for (var name in this._textures) {
  49265. this._effect.setTexture(name, this._textures[name]);
  49266. }
  49267. // Float
  49268. for (name in this._floats) {
  49269. this._effect.setFloat(name, this._floats[name]);
  49270. }
  49271. // Floats
  49272. for (name in this._floatsArrays) {
  49273. this._effect.setArray(name, this._floatsArrays[name]);
  49274. }
  49275. // Color3
  49276. for (name in this._colors3) {
  49277. this._effect.setColor3(name, this._colors3[name]);
  49278. }
  49279. // Color4
  49280. for (name in this._colors4) {
  49281. var color = this._colors4[name];
  49282. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  49283. }
  49284. // Vector2
  49285. for (name in this._vectors2) {
  49286. this._effect.setVector2(name, this._vectors2[name]);
  49287. }
  49288. // Vector3
  49289. for (name in this._vectors3) {
  49290. this._effect.setVector3(name, this._vectors3[name]);
  49291. }
  49292. // Matrix
  49293. for (name in this._matrices) {
  49294. this._effect.setMatrix(name, this._matrices[name]);
  49295. }
  49296. if (this.isCube) {
  49297. for (var face = 0; face < 6; face++) {
  49298. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  49299. // VBOs
  49300. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  49301. this._effect.setFloat("face", face);
  49302. // Clear
  49303. engine.clear(scene.clearColor, true, true, true);
  49304. // Draw order
  49305. engine.draw(true, 0, 6);
  49306. // Mipmaps
  49307. if (face === 5) {
  49308. engine.generateMipMapsForCubemap(this._texture);
  49309. }
  49310. }
  49311. }
  49312. else {
  49313. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  49314. // VBOs
  49315. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  49316. // Clear
  49317. engine.clear(scene.clearColor, true, true, true);
  49318. // Draw order
  49319. engine.draw(true, 0, 6);
  49320. }
  49321. // Unbind
  49322. engine.unBindFramebuffer(this._texture, this.isCube);
  49323. if (this.onGenerated) {
  49324. this.onGenerated();
  49325. }
  49326. };
  49327. ProceduralTexture.prototype.clone = function () {
  49328. var textureSize = this.getSize();
  49329. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  49330. // Base texture
  49331. newTexture.hasAlpha = this.hasAlpha;
  49332. newTexture.level = this.level;
  49333. // RenderTarget Texture
  49334. newTexture.coordinatesMode = this.coordinatesMode;
  49335. return newTexture;
  49336. };
  49337. ProceduralTexture.prototype.dispose = function () {
  49338. var index = this.getScene()._proceduralTextures.indexOf(this);
  49339. if (index >= 0) {
  49340. this.getScene()._proceduralTextures.splice(index, 1);
  49341. }
  49342. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  49343. if (vertexBuffer) {
  49344. vertexBuffer.dispose();
  49345. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  49346. }
  49347. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  49348. this._indexBuffer = null;
  49349. }
  49350. _super.prototype.dispose.call(this);
  49351. };
  49352. return ProceduralTexture;
  49353. }(BABYLON.Texture));
  49354. BABYLON.ProceduralTexture = ProceduralTexture;
  49355. })(BABYLON || (BABYLON = {}));
  49356. //# sourceMappingURL=babylon.proceduralTexture.js.map
  49357. /// <reference path="babylon.proceduralTexture.ts" />
  49358. var BABYLON;
  49359. (function (BABYLON) {
  49360. var CustomProceduralTexture = (function (_super) {
  49361. __extends(CustomProceduralTexture, _super);
  49362. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  49363. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  49364. _this._animate = true;
  49365. _this._time = 0;
  49366. _this._texturePath = texturePath;
  49367. //Try to load json
  49368. _this.loadJson(texturePath);
  49369. _this.refreshRate = 1;
  49370. return _this;
  49371. }
  49372. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  49373. var _this = this;
  49374. var that = this;
  49375. function noConfigFile() {
  49376. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  49377. try {
  49378. that.setFragment(that._texturePath);
  49379. }
  49380. catch (ex) {
  49381. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  49382. }
  49383. }
  49384. var configFileUrl = jsonUrl + "/config.json";
  49385. var xhr = new XMLHttpRequest();
  49386. xhr.open("GET", configFileUrl, true);
  49387. xhr.addEventListener("load", function () {
  49388. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  49389. try {
  49390. _this._config = JSON.parse(xhr.response);
  49391. _this.updateShaderUniforms();
  49392. _this.updateTextures();
  49393. _this.setFragment(_this._texturePath + "/custom");
  49394. _this._animate = _this._config.animate;
  49395. _this.refreshRate = _this._config.refreshrate;
  49396. }
  49397. catch (ex) {
  49398. noConfigFile();
  49399. }
  49400. }
  49401. else {
  49402. noConfigFile();
  49403. }
  49404. }, false);
  49405. xhr.addEventListener("error", function () {
  49406. noConfigFile();
  49407. }, false);
  49408. try {
  49409. xhr.send();
  49410. }
  49411. catch (ex) {
  49412. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  49413. }
  49414. };
  49415. CustomProceduralTexture.prototype.isReady = function () {
  49416. if (!_super.prototype.isReady.call(this)) {
  49417. return false;
  49418. }
  49419. for (var name in this._textures) {
  49420. var texture = this._textures[name];
  49421. if (!texture.isReady()) {
  49422. return false;
  49423. }
  49424. }
  49425. return true;
  49426. };
  49427. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  49428. if (this._animate) {
  49429. this._time += this.getScene().getAnimationRatio() * 0.03;
  49430. this.updateShaderUniforms();
  49431. }
  49432. _super.prototype.render.call(this, useCameraPostProcess);
  49433. };
  49434. CustomProceduralTexture.prototype.updateTextures = function () {
  49435. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  49436. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  49437. }
  49438. };
  49439. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  49440. if (this._config) {
  49441. for (var j = 0; j < this._config.uniforms.length; j++) {
  49442. var uniform = this._config.uniforms[j];
  49443. switch (uniform.type) {
  49444. case "float":
  49445. this.setFloat(uniform.name, uniform.value);
  49446. break;
  49447. case "color3":
  49448. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  49449. break;
  49450. case "color4":
  49451. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  49452. break;
  49453. case "vector2":
  49454. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  49455. break;
  49456. case "vector3":
  49457. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  49458. break;
  49459. }
  49460. }
  49461. }
  49462. this.setFloat("time", this._time);
  49463. };
  49464. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  49465. get: function () {
  49466. return this._animate;
  49467. },
  49468. set: function (value) {
  49469. this._animate = value;
  49470. },
  49471. enumerable: true,
  49472. configurable: true
  49473. });
  49474. return CustomProceduralTexture;
  49475. }(BABYLON.ProceduralTexture));
  49476. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  49477. })(BABYLON || (BABYLON = {}));
  49478. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  49479. var BABYLON;
  49480. (function (BABYLON) {
  49481. var FreeCameraGamepadInput = (function () {
  49482. function FreeCameraGamepadInput() {
  49483. this.gamepadAngularSensibility = 200;
  49484. this.gamepadMoveSensibility = 40;
  49485. // private members
  49486. this._cameraTransform = BABYLON.Matrix.Identity();
  49487. this._deltaTransform = BABYLON.Vector3.Zero();
  49488. this._vector3 = BABYLON.Vector3.Zero();
  49489. this._vector2 = BABYLON.Vector2.Zero();
  49490. }
  49491. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  49492. var _this = this;
  49493. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  49494. };
  49495. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  49496. if (this._gamepads) {
  49497. this._gamepads.dispose();
  49498. }
  49499. this.gamepad = null;
  49500. };
  49501. FreeCameraGamepadInput.prototype.checkInputs = function () {
  49502. if (this.gamepad && this.gamepad.leftStick) {
  49503. var camera = this.camera;
  49504. var LSValues = this.gamepad.leftStick;
  49505. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  49506. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  49507. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  49508. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  49509. var RSValues = this.gamepad.rightStick;
  49510. if (RSValues) {
  49511. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  49512. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  49513. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  49514. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  49515. }
  49516. else {
  49517. RSValues = { x: 0, y: 0 };
  49518. }
  49519. if (!camera.rotationQuaternion) {
  49520. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  49521. }
  49522. else {
  49523. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  49524. }
  49525. var speed = camera._computeLocalCameraSpeed() * 50.0;
  49526. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  49527. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  49528. camera.cameraDirection.addInPlace(this._deltaTransform);
  49529. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  49530. camera.cameraRotation.addInPlace(this._vector2);
  49531. }
  49532. };
  49533. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  49534. // Only the first gamepad found can control the camera
  49535. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  49536. // prioritize XBOX gamepads.
  49537. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  49538. this.gamepad = gamepad;
  49539. }
  49540. }
  49541. };
  49542. FreeCameraGamepadInput.prototype.getClassName = function () {
  49543. return "FreeCameraGamepadInput";
  49544. };
  49545. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  49546. return "gamepad";
  49547. };
  49548. return FreeCameraGamepadInput;
  49549. }());
  49550. __decorate([
  49551. BABYLON.serialize()
  49552. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  49553. __decorate([
  49554. BABYLON.serialize()
  49555. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  49556. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  49557. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  49558. })(BABYLON || (BABYLON = {}));
  49559. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  49560. var BABYLON;
  49561. (function (BABYLON) {
  49562. var ArcRotateCameraGamepadInput = (function () {
  49563. function ArcRotateCameraGamepadInput() {
  49564. this.gamepadRotationSensibility = 80;
  49565. this.gamepadMoveSensibility = 40;
  49566. }
  49567. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  49568. var _this = this;
  49569. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  49570. };
  49571. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  49572. if (this._gamepads) {
  49573. this._gamepads.dispose();
  49574. }
  49575. this.gamepad = null;
  49576. };
  49577. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  49578. if (this.gamepad) {
  49579. var camera = this.camera;
  49580. var RSValues = this.gamepad.rightStick;
  49581. if (RSValues) {
  49582. if (RSValues.x != 0) {
  49583. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  49584. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  49585. camera.inertialAlphaOffset += normalizedRX;
  49586. }
  49587. }
  49588. if (RSValues.y != 0) {
  49589. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  49590. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  49591. camera.inertialBetaOffset += normalizedRY;
  49592. }
  49593. }
  49594. }
  49595. var LSValues = this.gamepad.leftStick;
  49596. if (LSValues && LSValues.y != 0) {
  49597. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  49598. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  49599. this.camera.inertialRadiusOffset -= normalizedLY;
  49600. }
  49601. }
  49602. }
  49603. };
  49604. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  49605. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  49606. // prioritize XBOX gamepads.
  49607. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  49608. this.gamepad = gamepad;
  49609. }
  49610. }
  49611. };
  49612. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  49613. return "ArcRotateCameraGamepadInput";
  49614. };
  49615. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  49616. return "gamepad";
  49617. };
  49618. return ArcRotateCameraGamepadInput;
  49619. }());
  49620. __decorate([
  49621. BABYLON.serialize()
  49622. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  49623. __decorate([
  49624. BABYLON.serialize()
  49625. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  49626. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  49627. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  49628. })(BABYLON || (BABYLON = {}));
  49629. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  49630. var BABYLON;
  49631. (function (BABYLON) {
  49632. var Gamepads = (function () {
  49633. function Gamepads(ongamedpadconnected, ongamedpaddisconnected) {
  49634. var _this = this;
  49635. this.babylonGamepads = [];
  49636. this.oneGamepadConnected = false;
  49637. this.isMonitoring = false;
  49638. this.gamepadEventSupported = 'GamepadEvent' in window;
  49639. this.gamepadSupport = (navigator.getGamepads ||
  49640. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  49641. this._callbackGamepadConnected = ongamedpadconnected;
  49642. this._callbackGamepadDisconnected = ongamedpaddisconnected;
  49643. if (this.gamepadSupport) {
  49644. //first add already-connected gamepads
  49645. this._updateGamepadObjects();
  49646. if (this.babylonGamepads.length) {
  49647. this._startMonitoringGamepads();
  49648. }
  49649. // Checking if the gamepad connected event is supported (like in Firefox)
  49650. if (this.gamepadEventSupported) {
  49651. this._onGamepadConnectedEvent = function (evt) {
  49652. _this._onGamepadConnected(evt.gamepad);
  49653. };
  49654. this._onGamepadDisonnectedEvent = function (evt) {
  49655. _this._onGamepadDisconnected(evt.gamepad);
  49656. };
  49657. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  49658. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  49659. }
  49660. else {
  49661. this._startMonitoringGamepads();
  49662. }
  49663. }
  49664. }
  49665. Gamepads.prototype.dispose = function () {
  49666. if (this._onGamepadConnectedEvent) {
  49667. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  49668. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  49669. this._onGamepadConnectedEvent = null;
  49670. this._onGamepadDisonnectedEvent = null;
  49671. }
  49672. this.oneGamepadConnected = false;
  49673. this._stopMonitoringGamepads();
  49674. this.babylonGamepads = [];
  49675. };
  49676. Gamepads.prototype._onGamepadConnected = function (gamepad) {
  49677. // Protection code for Chrome which has a very buggy gamepad implementation...
  49678. // And raises a connected event on disconnection for instance
  49679. if (gamepad.index in this.babylonGamepads) {
  49680. return;
  49681. }
  49682. var newGamepad = this._addNewGamepad(gamepad);
  49683. if (this._callbackGamepadConnected)
  49684. this._callbackGamepadConnected(newGamepad);
  49685. this._startMonitoringGamepads();
  49686. };
  49687. Gamepads.prototype._addNewGamepad = function (gamepad) {
  49688. if (!this.oneGamepadConnected) {
  49689. this.oneGamepadConnected = true;
  49690. }
  49691. var newGamepad;
  49692. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  49693. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  49694. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  49695. }
  49696. else if (gamepad.pose) {
  49697. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  49698. }
  49699. else {
  49700. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  49701. }
  49702. this.babylonGamepads.push(newGamepad);
  49703. return newGamepad;
  49704. };
  49705. Gamepads.prototype._onGamepadDisconnected = function (gamepad) {
  49706. // Remove the gamepad from the list of gamepads to monitor.
  49707. for (var i in this.babylonGamepads) {
  49708. if (this.babylonGamepads[i].index == gamepad.index) {
  49709. this.babylonGamepads.splice(+i, 1);
  49710. break;
  49711. }
  49712. }
  49713. // If no gamepads are left, stop the polling loop.
  49714. if (this.babylonGamepads.length == 0) {
  49715. this._stopMonitoringGamepads();
  49716. this.oneGamepadConnected = false;
  49717. }
  49718. if (this._callbackGamepadDisconnected)
  49719. this._callbackGamepadDisconnected(gamepad);
  49720. };
  49721. Gamepads.prototype._startMonitoringGamepads = function () {
  49722. if (!this.isMonitoring) {
  49723. this.isMonitoring = true;
  49724. this._checkGamepadsStatus();
  49725. }
  49726. };
  49727. Gamepads.prototype._stopMonitoringGamepads = function () {
  49728. this.isMonitoring = false;
  49729. };
  49730. Gamepads.prototype._checkGamepadsStatus = function () {
  49731. var _this = this;
  49732. // Hack to be compatible Chrome
  49733. this._updateGamepadObjects();
  49734. for (var i in this.babylonGamepads) {
  49735. this.babylonGamepads[i].update();
  49736. }
  49737. if (this.isMonitoring) {
  49738. if (window.requestAnimationFrame) {
  49739. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  49740. }
  49741. else if (window.mozRequestAnimationFrame) {
  49742. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  49743. }
  49744. else if (window.webkitRequestAnimationFrame) {
  49745. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  49746. }
  49747. }
  49748. };
  49749. // This function is called only on Chrome, which does not properly support
  49750. // connection/disconnection events and forces you to recopy again the gamepad object
  49751. Gamepads.prototype._updateGamepadObjects = function () {
  49752. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  49753. for (var i = 0; i < gamepads.length; i++) {
  49754. if (gamepads[i]) {
  49755. if (!(gamepads[i].index in this.babylonGamepads)) {
  49756. var newGamepad = this._addNewGamepad(gamepads[i]);
  49757. if (this._callbackGamepadConnected) {
  49758. this._callbackGamepadConnected(newGamepad);
  49759. }
  49760. }
  49761. else {
  49762. // Forced to copy again this object for Chrome for unknown reason
  49763. this.babylonGamepads[i].browserGamepad = gamepads[i];
  49764. }
  49765. }
  49766. }
  49767. };
  49768. return Gamepads;
  49769. }());
  49770. BABYLON.Gamepads = Gamepads;
  49771. var StickValues = (function () {
  49772. function StickValues(x, y) {
  49773. this.x = x;
  49774. this.y = y;
  49775. }
  49776. return StickValues;
  49777. }());
  49778. BABYLON.StickValues = StickValues;
  49779. var Gamepad = (function () {
  49780. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  49781. if (leftStickX === void 0) { leftStickX = 0; }
  49782. if (leftStickY === void 0) { leftStickY = 1; }
  49783. if (rightStickX === void 0) { rightStickX = 2; }
  49784. if (rightStickY === void 0) { rightStickY = 3; }
  49785. this.id = id;
  49786. this.index = index;
  49787. this.browserGamepad = browserGamepad;
  49788. this.type = Gamepad.GAMEPAD;
  49789. this._leftStickAxisX = leftStickX;
  49790. this._leftStickAxisY = leftStickY;
  49791. this._rightStickAxisX = rightStickX;
  49792. this._rightStickAxisY = rightStickY;
  49793. if (this.browserGamepad.axes.length >= 2) {
  49794. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  49795. }
  49796. if (this.browserGamepad.axes.length >= 4) {
  49797. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  49798. }
  49799. }
  49800. Gamepad.prototype.onleftstickchanged = function (callback) {
  49801. this._onleftstickchanged = callback;
  49802. };
  49803. Gamepad.prototype.onrightstickchanged = function (callback) {
  49804. this._onrightstickchanged = callback;
  49805. };
  49806. Object.defineProperty(Gamepad.prototype, "leftStick", {
  49807. get: function () {
  49808. return this._leftStick;
  49809. },
  49810. set: function (newValues) {
  49811. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  49812. this._onleftstickchanged(newValues);
  49813. }
  49814. this._leftStick = newValues;
  49815. },
  49816. enumerable: true,
  49817. configurable: true
  49818. });
  49819. Object.defineProperty(Gamepad.prototype, "rightStick", {
  49820. get: function () {
  49821. return this._rightStick;
  49822. },
  49823. set: function (newValues) {
  49824. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  49825. this._onrightstickchanged(newValues);
  49826. }
  49827. this._rightStick = newValues;
  49828. },
  49829. enumerable: true,
  49830. configurable: true
  49831. });
  49832. Gamepad.prototype.update = function () {
  49833. if (this._leftStick) {
  49834. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  49835. }
  49836. if (this._rightStick) {
  49837. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  49838. }
  49839. };
  49840. return Gamepad;
  49841. }());
  49842. Gamepad.GAMEPAD = 0;
  49843. Gamepad.GENERIC = 1;
  49844. Gamepad.XBOX = 2;
  49845. Gamepad.POSE_ENABLED = 3;
  49846. BABYLON.Gamepad = Gamepad;
  49847. var GenericPad = (function (_super) {
  49848. __extends(GenericPad, _super);
  49849. function GenericPad(id, index, browserGamepad) {
  49850. var _this = _super.call(this, id, index, browserGamepad) || this;
  49851. _this.type = Gamepad.GENERIC;
  49852. _this._buttons = new Array(browserGamepad.buttons.length);
  49853. return _this;
  49854. }
  49855. GenericPad.prototype.onbuttondown = function (callback) {
  49856. this._onbuttondown = callback;
  49857. };
  49858. GenericPad.prototype.onbuttonup = function (callback) {
  49859. this._onbuttonup = callback;
  49860. };
  49861. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  49862. if (newValue !== currentValue) {
  49863. if (this._onbuttondown && newValue === 1) {
  49864. this._onbuttondown(buttonIndex);
  49865. }
  49866. if (this._onbuttonup && newValue === 0) {
  49867. this._onbuttonup(buttonIndex);
  49868. }
  49869. }
  49870. return newValue;
  49871. };
  49872. GenericPad.prototype.update = function () {
  49873. _super.prototype.update.call(this);
  49874. for (var index = 0; index < this._buttons.length; index++) {
  49875. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  49876. }
  49877. };
  49878. return GenericPad;
  49879. }(Gamepad));
  49880. BABYLON.GenericPad = GenericPad;
  49881. var Xbox360Button;
  49882. (function (Xbox360Button) {
  49883. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  49884. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  49885. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  49886. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  49887. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  49888. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  49889. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  49890. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  49891. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  49892. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  49893. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  49894. var Xbox360Dpad;
  49895. (function (Xbox360Dpad) {
  49896. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  49897. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  49898. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  49899. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  49900. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  49901. var Xbox360Pad = (function (_super) {
  49902. __extends(Xbox360Pad, _super);
  49903. function Xbox360Pad(id, index, gamepad, xboxOne) {
  49904. if (xboxOne === void 0) { xboxOne = false; }
  49905. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  49906. _this._leftTrigger = 0;
  49907. _this._rightTrigger = 0;
  49908. _this._buttonA = 0;
  49909. _this._buttonB = 0;
  49910. _this._buttonX = 0;
  49911. _this._buttonY = 0;
  49912. _this._buttonBack = 0;
  49913. _this._buttonStart = 0;
  49914. _this._buttonLB = 0;
  49915. _this._buttonRB = 0;
  49916. _this._buttonLeftStick = 0;
  49917. _this._buttonRightStick = 0;
  49918. _this._dPadUp = 0;
  49919. _this._dPadDown = 0;
  49920. _this._dPadLeft = 0;
  49921. _this._dPadRight = 0;
  49922. _this._isXboxOnePad = false;
  49923. _this.type = Gamepad.XBOX;
  49924. _this._isXboxOnePad = xboxOne;
  49925. return _this;
  49926. }
  49927. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  49928. this._onlefttriggerchanged = callback;
  49929. };
  49930. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  49931. this._onrighttriggerchanged = callback;
  49932. };
  49933. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  49934. get: function () {
  49935. return this._leftTrigger;
  49936. },
  49937. set: function (newValue) {
  49938. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  49939. this._onlefttriggerchanged(newValue);
  49940. }
  49941. this._leftTrigger = newValue;
  49942. },
  49943. enumerable: true,
  49944. configurable: true
  49945. });
  49946. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  49947. get: function () {
  49948. return this._rightTrigger;
  49949. },
  49950. set: function (newValue) {
  49951. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  49952. this._onrighttriggerchanged(newValue);
  49953. }
  49954. this._rightTrigger = newValue;
  49955. },
  49956. enumerable: true,
  49957. configurable: true
  49958. });
  49959. Xbox360Pad.prototype.onbuttondown = function (callback) {
  49960. this._onbuttondown = callback;
  49961. };
  49962. Xbox360Pad.prototype.onbuttonup = function (callback) {
  49963. this._onbuttonup = callback;
  49964. };
  49965. Xbox360Pad.prototype.ondpaddown = function (callback) {
  49966. this._ondpaddown = callback;
  49967. };
  49968. Xbox360Pad.prototype.ondpadup = function (callback) {
  49969. this._ondpadup = callback;
  49970. };
  49971. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  49972. if (newValue !== currentValue) {
  49973. if (this._onbuttondown && newValue === 1) {
  49974. this._onbuttondown(buttonType);
  49975. }
  49976. if (this._onbuttonup && newValue === 0) {
  49977. this._onbuttonup(buttonType);
  49978. }
  49979. }
  49980. return newValue;
  49981. };
  49982. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  49983. if (newValue !== currentValue) {
  49984. if (this._ondpaddown && newValue === 1) {
  49985. this._ondpaddown(buttonType);
  49986. }
  49987. if (this._ondpadup && newValue === 0) {
  49988. this._ondpadup(buttonType);
  49989. }
  49990. }
  49991. return newValue;
  49992. };
  49993. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  49994. get: function () {
  49995. return this._buttonA;
  49996. },
  49997. set: function (value) {
  49998. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  49999. },
  50000. enumerable: true,
  50001. configurable: true
  50002. });
  50003. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  50004. get: function () {
  50005. return this._buttonB;
  50006. },
  50007. set: function (value) {
  50008. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  50009. },
  50010. enumerable: true,
  50011. configurable: true
  50012. });
  50013. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  50014. get: function () {
  50015. return this._buttonX;
  50016. },
  50017. set: function (value) {
  50018. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  50019. },
  50020. enumerable: true,
  50021. configurable: true
  50022. });
  50023. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  50024. get: function () {
  50025. return this._buttonY;
  50026. },
  50027. set: function (value) {
  50028. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  50029. },
  50030. enumerable: true,
  50031. configurable: true
  50032. });
  50033. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  50034. get: function () {
  50035. return this._buttonStart;
  50036. },
  50037. set: function (value) {
  50038. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  50039. },
  50040. enumerable: true,
  50041. configurable: true
  50042. });
  50043. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  50044. get: function () {
  50045. return this._buttonBack;
  50046. },
  50047. set: function (value) {
  50048. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  50049. },
  50050. enumerable: true,
  50051. configurable: true
  50052. });
  50053. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  50054. get: function () {
  50055. return this._buttonLB;
  50056. },
  50057. set: function (value) {
  50058. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  50059. },
  50060. enumerable: true,
  50061. configurable: true
  50062. });
  50063. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  50064. get: function () {
  50065. return this._buttonRB;
  50066. },
  50067. set: function (value) {
  50068. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  50069. },
  50070. enumerable: true,
  50071. configurable: true
  50072. });
  50073. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  50074. get: function () {
  50075. return this._buttonLeftStick;
  50076. },
  50077. set: function (value) {
  50078. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  50079. },
  50080. enumerable: true,
  50081. configurable: true
  50082. });
  50083. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  50084. get: function () {
  50085. return this._buttonRightStick;
  50086. },
  50087. set: function (value) {
  50088. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  50089. },
  50090. enumerable: true,
  50091. configurable: true
  50092. });
  50093. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  50094. get: function () {
  50095. return this._dPadUp;
  50096. },
  50097. set: function (value) {
  50098. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  50099. },
  50100. enumerable: true,
  50101. configurable: true
  50102. });
  50103. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  50104. get: function () {
  50105. return this._dPadDown;
  50106. },
  50107. set: function (value) {
  50108. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  50109. },
  50110. enumerable: true,
  50111. configurable: true
  50112. });
  50113. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  50114. get: function () {
  50115. return this._dPadLeft;
  50116. },
  50117. set: function (value) {
  50118. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  50119. },
  50120. enumerable: true,
  50121. configurable: true
  50122. });
  50123. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  50124. get: function () {
  50125. return this._dPadRight;
  50126. },
  50127. set: function (value) {
  50128. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  50129. },
  50130. enumerable: true,
  50131. configurable: true
  50132. });
  50133. Xbox360Pad.prototype.update = function () {
  50134. _super.prototype.update.call(this);
  50135. if (this._isXboxOnePad) {
  50136. this.buttonA = this.browserGamepad.buttons[0].value;
  50137. this.buttonB = this.browserGamepad.buttons[1].value;
  50138. this.buttonX = this.browserGamepad.buttons[2].value;
  50139. this.buttonY = this.browserGamepad.buttons[3].value;
  50140. this.buttonLB = this.browserGamepad.buttons[4].value;
  50141. this.buttonRB = this.browserGamepad.buttons[5].value;
  50142. this.leftTrigger = this.browserGamepad.axes[2];
  50143. this.rightTrigger = this.browserGamepad.axes[5];
  50144. this.buttonBack = this.browserGamepad.buttons[9].value;
  50145. this.buttonStart = this.browserGamepad.buttons[8].value;
  50146. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  50147. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  50148. this.dPadUp = this.browserGamepad.buttons[11].value;
  50149. this.dPadDown = this.browserGamepad.buttons[12].value;
  50150. this.dPadLeft = this.browserGamepad.buttons[13].value;
  50151. this.dPadRight = this.browserGamepad.buttons[14].value;
  50152. }
  50153. else {
  50154. this.buttonA = this.browserGamepad.buttons[0].value;
  50155. this.buttonB = this.browserGamepad.buttons[1].value;
  50156. this.buttonX = this.browserGamepad.buttons[2].value;
  50157. this.buttonY = this.browserGamepad.buttons[3].value;
  50158. this.buttonLB = this.browserGamepad.buttons[4].value;
  50159. this.buttonRB = this.browserGamepad.buttons[5].value;
  50160. this.leftTrigger = this.browserGamepad.buttons[6].value;
  50161. this.rightTrigger = this.browserGamepad.buttons[7].value;
  50162. this.buttonBack = this.browserGamepad.buttons[8].value;
  50163. this.buttonStart = this.browserGamepad.buttons[9].value;
  50164. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  50165. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  50166. this.dPadUp = this.browserGamepad.buttons[12].value;
  50167. this.dPadDown = this.browserGamepad.buttons[13].value;
  50168. this.dPadLeft = this.browserGamepad.buttons[14].value;
  50169. this.dPadRight = this.browserGamepad.buttons[15].value;
  50170. }
  50171. };
  50172. return Xbox360Pad;
  50173. }(Gamepad));
  50174. BABYLON.Xbox360Pad = Xbox360Pad;
  50175. })(BABYLON || (BABYLON = {}));
  50176. //# sourceMappingURL=babylon.gamepads.js.map
  50177. var BABYLON;
  50178. (function (BABYLON) {
  50179. var PoseEnabledControllerType;
  50180. (function (PoseEnabledControllerType) {
  50181. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  50182. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  50183. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  50184. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 3] = "GENERIC";
  50185. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  50186. var PoseEnabledControllerHelper = (function () {
  50187. function PoseEnabledControllerHelper() {
  50188. }
  50189. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  50190. // Oculus Touch
  50191. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  50192. return new OculusTouchController(vrGamepad);
  50193. }
  50194. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  50195. return new ViveController(vrGamepad);
  50196. }
  50197. else {
  50198. return new GenericController(vrGamepad);
  50199. }
  50200. };
  50201. return PoseEnabledControllerHelper;
  50202. }());
  50203. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  50204. var PoseEnabledController = (function (_super) {
  50205. __extends(PoseEnabledController, _super);
  50206. function PoseEnabledController(vrGamepad) {
  50207. var _this = _super.call(this, vrGamepad.id, vrGamepad.index, vrGamepad) || this;
  50208. _this.vrGamepad = vrGamepad;
  50209. _this.deviceScaleFactor = 1;
  50210. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  50211. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  50212. _this.controllerType = PoseEnabledControllerType.GENERIC;
  50213. _this.position = BABYLON.Vector3.Zero();
  50214. _this.rotationQuaternion = new BABYLON.Quaternion();
  50215. _this.devicePosition = BABYLON.Vector3.Zero();
  50216. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  50217. _this._calculatedPosition = BABYLON.Vector3.Zero();
  50218. _this._calculatedRotation = new BABYLON.Quaternion();
  50219. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  50220. return _this;
  50221. }
  50222. PoseEnabledController.prototype.update = function () {
  50223. _super.prototype.update.call(this);
  50224. var pose = this.vrGamepad.pose;
  50225. this.updateFromDevice(pose);
  50226. if (this._mesh) {
  50227. this._mesh.position.copyFrom(this._calculatedPosition);
  50228. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  50229. }
  50230. };
  50231. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  50232. if (poseData) {
  50233. this.rawPose = poseData;
  50234. if (poseData.position) {
  50235. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  50236. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  50237. this.devicePosition.z *= -1;
  50238. }
  50239. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  50240. this._calculatedPosition.addInPlace(this.position);
  50241. }
  50242. if (poseData.orientation) {
  50243. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  50244. if (this._mesh) {
  50245. if (this._mesh.getScene().useRightHandedSystem) {
  50246. this.deviceRotationQuaternion.z *= -1;
  50247. this.deviceRotationQuaternion.w *= -1;
  50248. }
  50249. else {
  50250. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  50251. }
  50252. }
  50253. // if the camera is set, rotate to the camera's rotation
  50254. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  50255. }
  50256. }
  50257. };
  50258. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  50259. if (this._mesh) {
  50260. this._mesh.parent = undefined;
  50261. }
  50262. this._mesh = mesh;
  50263. if (this._poseControlledCamera) {
  50264. this._mesh.parent = this._poseControlledCamera;
  50265. }
  50266. if (!this._mesh.rotationQuaternion) {
  50267. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  50268. }
  50269. };
  50270. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  50271. this._poseControlledCamera = camera;
  50272. if (this._mesh) {
  50273. this._mesh.parent = this._poseControlledCamera;
  50274. }
  50275. };
  50276. PoseEnabledController.prototype.detachMesh = function () {
  50277. this._mesh = undefined;
  50278. };
  50279. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  50280. get: function () {
  50281. return this._mesh;
  50282. },
  50283. enumerable: true,
  50284. configurable: true
  50285. });
  50286. PoseEnabledController.prototype.getForwardRay = function (length) {
  50287. if (length === void 0) { length = 100; }
  50288. if (!this.mesh) {
  50289. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  50290. }
  50291. var m = this.mesh.getWorldMatrix();
  50292. var origin = m.getTranslation();
  50293. var forward = new BABYLON.Vector3(0, 0, -1);
  50294. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  50295. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  50296. return new BABYLON.Ray(origin, direction, length);
  50297. };
  50298. return PoseEnabledController;
  50299. }(BABYLON.Gamepad));
  50300. BABYLON.PoseEnabledController = PoseEnabledController;
  50301. var WebVRController = (function (_super) {
  50302. __extends(WebVRController, _super);
  50303. function WebVRController(vrGamepad) {
  50304. var _this = _super.call(this, vrGamepad) || this;
  50305. //public onTriggerStateChangedObservable = new Observable<{ state: ExtendedGamepadButton, changes: GamepadButtonChanges }>();
  50306. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  50307. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  50308. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  50309. _this.onPadStateChangedObservable = new BABYLON.Observable();
  50310. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  50311. _this.pad = { x: 0, y: 0 };
  50312. // avoid GC, store state in a tmp object
  50313. _this._changes = {
  50314. pressChanged: false,
  50315. touchChanged: false,
  50316. valueChanged: false,
  50317. changed: false
  50318. };
  50319. _this._buttons = new Array(vrGamepad.buttons.length);
  50320. _this.hand = vrGamepad.hand;
  50321. return _this;
  50322. }
  50323. WebVRController.prototype.onButtonStateChange = function (callback) {
  50324. this._onButtonStateChange = callback;
  50325. };
  50326. WebVRController.prototype.update = function () {
  50327. _super.prototype.update.call(this);
  50328. for (var index = 0; index < this._buttons.length; index++) {
  50329. this._setButtonValue(this.vrGamepad.buttons[index], this._buttons[index], index);
  50330. }
  50331. ;
  50332. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  50333. this.pad.x = this.leftStick.x;
  50334. this.pad.y = this.leftStick.y;
  50335. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  50336. }
  50337. };
  50338. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  50339. if (!newState) {
  50340. newState = {
  50341. pressed: false,
  50342. touched: false,
  50343. value: 0
  50344. };
  50345. }
  50346. if (!currentState) {
  50347. this._buttons[buttonIndex] = {
  50348. pressed: newState.pressed,
  50349. touched: newState.touched,
  50350. value: newState.value
  50351. };
  50352. return;
  50353. }
  50354. this._checkChanges(newState, currentState);
  50355. if (this._changes.changed) {
  50356. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  50357. this.handleButtonChange(buttonIndex, newState, this._changes);
  50358. }
  50359. this._buttons[buttonIndex].pressed = newState.pressed;
  50360. this._buttons[buttonIndex].touched = newState.touched;
  50361. // oculus triggers are never 0, thou not touched.
  50362. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  50363. };
  50364. WebVRController.prototype._checkChanges = function (newState, currentState) {
  50365. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  50366. this._changes.touchChanged = newState.touched !== currentState.touched;
  50367. this._changes.valueChanged = newState.value !== currentState.value;
  50368. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  50369. return this._changes;
  50370. };
  50371. return WebVRController;
  50372. }(PoseEnabledController));
  50373. BABYLON.WebVRController = WebVRController;
  50374. var OculusTouchController = (function (_super) {
  50375. __extends(OculusTouchController, _super);
  50376. function OculusTouchController(vrGamepad) {
  50377. var _this = _super.call(this, vrGamepad) || this;
  50378. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  50379. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  50380. _this.controllerType = PoseEnabledControllerType.OCULUS;
  50381. return _this;
  50382. }
  50383. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  50384. var _this = this;
  50385. var meshName = this.hand === 'right' ? 'RightTouch.babylon' : 'LeftTouch.babylon';
  50386. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", meshName, scene, function (newMeshes) {
  50387. /*
  50388. Parent Mesh name: oculus_touch_left
  50389. - body
  50390. - trigger
  50391. - thumbstick
  50392. - grip
  50393. - button_y
  50394. - button_x
  50395. - button_enter
  50396. */
  50397. _this._defaultModel = newMeshes[1];
  50398. if (meshLoaded) {
  50399. meshLoaded(_this._defaultModel);
  50400. }
  50401. _this.attachToMesh(_this._defaultModel);
  50402. });
  50403. };
  50404. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  50405. // helper getters for left and right hand.
  50406. get: function () {
  50407. if (this.hand === 'right') {
  50408. return this.onMainButtonStateChangedObservable;
  50409. }
  50410. else {
  50411. throw new Error('No A button on left hand');
  50412. }
  50413. },
  50414. enumerable: true,
  50415. configurable: true
  50416. });
  50417. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  50418. get: function () {
  50419. if (this.hand === 'right') {
  50420. return this.onSecondaryButtonStateChangedObservable;
  50421. }
  50422. else {
  50423. throw new Error('No B button on left hand');
  50424. }
  50425. },
  50426. enumerable: true,
  50427. configurable: true
  50428. });
  50429. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  50430. get: function () {
  50431. if (this.hand === 'left') {
  50432. return this.onMainButtonStateChangedObservable;
  50433. }
  50434. else {
  50435. throw new Error('No X button on right hand');
  50436. }
  50437. },
  50438. enumerable: true,
  50439. configurable: true
  50440. });
  50441. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  50442. get: function () {
  50443. if (this.hand === 'left') {
  50444. return this.onSecondaryButtonStateChangedObservable;
  50445. }
  50446. else {
  50447. throw new Error('No Y button on right hand');
  50448. }
  50449. },
  50450. enumerable: true,
  50451. configurable: true
  50452. });
  50453. /*
  50454. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  50455. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  50456. 2) secondary trigger (same)
  50457. 3) A (right) X (left), touch, pressed = value
  50458. 4) B / Y
  50459. 5) thumb rest
  50460. */
  50461. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  50462. var notifyObject = state; //{ state: state, changes: changes };
  50463. var triggerDirection = this.hand === 'right' ? -1 : 1;
  50464. switch (buttonIdx) {
  50465. case 0:
  50466. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  50467. return;
  50468. case 1:
  50469. if (this._defaultModel) {
  50470. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  50471. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  50472. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  50473. }
  50474. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  50475. return;
  50476. case 2:
  50477. if (this._defaultModel) {
  50478. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  50479. }
  50480. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  50481. return;
  50482. case 3:
  50483. if (this._defaultModel) {
  50484. if (notifyObject.pressed) {
  50485. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  50486. }
  50487. else {
  50488. (this._defaultModel.getChildren()[1]).position.y = 0;
  50489. }
  50490. }
  50491. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  50492. return;
  50493. case 4:
  50494. if (this._defaultModel) {
  50495. if (notifyObject.pressed) {
  50496. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  50497. }
  50498. else {
  50499. (this._defaultModel.getChildren()[2]).position.y = 0;
  50500. }
  50501. }
  50502. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  50503. return;
  50504. case 5:
  50505. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  50506. return;
  50507. }
  50508. };
  50509. return OculusTouchController;
  50510. }(WebVRController));
  50511. BABYLON.OculusTouchController = OculusTouchController;
  50512. var ViveController = (function (_super) {
  50513. __extends(ViveController, _super);
  50514. function ViveController(vrGamepad) {
  50515. var _this = _super.call(this, vrGamepad) || this;
  50516. _this.controllerType = PoseEnabledControllerType.VIVE;
  50517. return _this;
  50518. }
  50519. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  50520. var _this = this;
  50521. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", "ViveWand.babylon", scene, function (newMeshes) {
  50522. /*
  50523. Parent Mesh name: ViveWand
  50524. - body
  50525. - r_gripper
  50526. - l_gripper
  50527. - menu_button
  50528. - system_button
  50529. - trackpad
  50530. - trigger
  50531. - LED
  50532. */
  50533. _this._defaultModel = newMeshes[1];
  50534. if (meshLoaded) {
  50535. meshLoaded(_this._defaultModel);
  50536. }
  50537. _this.attachToMesh(_this._defaultModel);
  50538. });
  50539. };
  50540. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  50541. get: function () {
  50542. return this.onMainButtonStateChangedObservable;
  50543. },
  50544. enumerable: true,
  50545. configurable: true
  50546. });
  50547. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  50548. get: function () {
  50549. return this.onMainButtonStateChangedObservable;
  50550. },
  50551. enumerable: true,
  50552. configurable: true
  50553. });
  50554. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  50555. get: function () {
  50556. return this.onSecondaryButtonStateChangedObservable;
  50557. },
  50558. enumerable: true,
  50559. configurable: true
  50560. });
  50561. /**
  50562. * Vive mapping:
  50563. * 0: touchpad
  50564. * 1: trigger
  50565. * 2: left AND right buttons
  50566. * 3: menu button
  50567. */
  50568. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  50569. var notifyObject = state; //{ state: state, changes: changes };
  50570. switch (buttonIdx) {
  50571. case 0:
  50572. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  50573. return;
  50574. case 1:
  50575. if (this._defaultModel) {
  50576. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  50577. }
  50578. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  50579. return;
  50580. case 2:
  50581. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  50582. return;
  50583. case 3:
  50584. if (this._defaultModel) {
  50585. if (notifyObject.pressed) {
  50586. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  50587. }
  50588. else {
  50589. (this._defaultModel.getChildren()[2]).position.y = 0;
  50590. }
  50591. }
  50592. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  50593. return;
  50594. }
  50595. };
  50596. return ViveController;
  50597. }(WebVRController));
  50598. BABYLON.ViveController = ViveController;
  50599. var GenericController = (function (_super) {
  50600. __extends(GenericController, _super);
  50601. function GenericController(vrGamepad) {
  50602. return _super.call(this, vrGamepad) || this;
  50603. }
  50604. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  50605. var _this = this;
  50606. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", "genericvrcontroller.babylon", scene, function (newMeshes) {
  50607. _this._defaultModel = newMeshes[1];
  50608. if (meshLoaded) {
  50609. meshLoaded(_this._defaultModel);
  50610. }
  50611. _this.attachToMesh(_this._defaultModel);
  50612. });
  50613. };
  50614. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  50615. console.log("Button id: " + buttonIdx + "state: ");
  50616. console.dir(state);
  50617. };
  50618. return GenericController;
  50619. }(WebVRController));
  50620. BABYLON.GenericController = GenericController;
  50621. })(BABYLON || (BABYLON = {}));
  50622. //# sourceMappingURL=babylon.extendedGamepad.js.map
  50623. /// <reference path="babylon.targetCamera.ts" />
  50624. var BABYLON;
  50625. (function (BABYLON) {
  50626. var FollowCamera = (function (_super) {
  50627. __extends(FollowCamera, _super);
  50628. function FollowCamera(name, position, scene, lockedTarget) {
  50629. var _this = _super.call(this, name, position, scene) || this;
  50630. _this.radius = 12;
  50631. _this.rotationOffset = 0;
  50632. _this.heightOffset = 4;
  50633. _this.cameraAcceleration = 0.05;
  50634. _this.maxCameraSpeed = 20;
  50635. _this.lockedTarget = lockedTarget;
  50636. return _this;
  50637. }
  50638. FollowCamera.prototype.getRadians = function (degrees) {
  50639. return degrees * Math.PI / 180;
  50640. };
  50641. FollowCamera.prototype.follow = function (cameraTarget) {
  50642. if (!cameraTarget)
  50643. return;
  50644. var yRotation;
  50645. if (cameraTarget.rotationQuaternion) {
  50646. var rotMatrix = new BABYLON.Matrix();
  50647. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  50648. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  50649. }
  50650. else {
  50651. yRotation = cameraTarget.rotation.y;
  50652. }
  50653. var radians = this.getRadians(this.rotationOffset) + yRotation;
  50654. var targetPosition = cameraTarget.getAbsolutePosition();
  50655. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  50656. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  50657. var dx = targetX - this.position.x;
  50658. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  50659. var dz = (targetZ) - this.position.z;
  50660. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  50661. var vy = dy * this.cameraAcceleration;
  50662. var vz = dz * this.cameraAcceleration * 2;
  50663. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  50664. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  50665. }
  50666. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  50667. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  50668. }
  50669. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  50670. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  50671. }
  50672. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  50673. this.setTarget(targetPosition);
  50674. };
  50675. FollowCamera.prototype._checkInputs = function () {
  50676. _super.prototype._checkInputs.call(this);
  50677. this.follow(this.lockedTarget);
  50678. };
  50679. FollowCamera.prototype.getClassName = function () {
  50680. return "FollowCamera";
  50681. };
  50682. return FollowCamera;
  50683. }(BABYLON.TargetCamera));
  50684. __decorate([
  50685. BABYLON.serialize()
  50686. ], FollowCamera.prototype, "radius", void 0);
  50687. __decorate([
  50688. BABYLON.serialize()
  50689. ], FollowCamera.prototype, "rotationOffset", void 0);
  50690. __decorate([
  50691. BABYLON.serialize()
  50692. ], FollowCamera.prototype, "heightOffset", void 0);
  50693. __decorate([
  50694. BABYLON.serialize()
  50695. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  50696. __decorate([
  50697. BABYLON.serialize()
  50698. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  50699. __decorate([
  50700. BABYLON.serializeAsMeshReference("lockedTargetId")
  50701. ], FollowCamera.prototype, "lockedTarget", void 0);
  50702. BABYLON.FollowCamera = FollowCamera;
  50703. var ArcFollowCamera = (function (_super) {
  50704. __extends(ArcFollowCamera, _super);
  50705. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  50706. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  50707. _this.alpha = alpha;
  50708. _this.beta = beta;
  50709. _this.radius = radius;
  50710. _this.target = target;
  50711. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  50712. _this.follow();
  50713. return _this;
  50714. }
  50715. ArcFollowCamera.prototype.follow = function () {
  50716. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  50717. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  50718. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  50719. var targetPosition = this.target.getAbsolutePosition();
  50720. this.position = targetPosition.add(this._cartesianCoordinates);
  50721. this.setTarget(targetPosition);
  50722. };
  50723. ArcFollowCamera.prototype._checkInputs = function () {
  50724. _super.prototype._checkInputs.call(this);
  50725. this.follow();
  50726. };
  50727. ArcFollowCamera.prototype.getClassName = function () {
  50728. return "ArcFollowCamera";
  50729. };
  50730. return ArcFollowCamera;
  50731. }(BABYLON.TargetCamera));
  50732. BABYLON.ArcFollowCamera = ArcFollowCamera;
  50733. })(BABYLON || (BABYLON = {}));
  50734. //# sourceMappingURL=babylon.followCamera.js.map
  50735. /// <reference path="babylon.touchCamera.ts" />
  50736. var BABYLON;
  50737. (function (BABYLON) {
  50738. // We're mainly based on the logic defined into the FreeCamera code
  50739. var UniversalCamera = (function (_super) {
  50740. __extends(UniversalCamera, _super);
  50741. //-- end properties for backward compatibility for inputs
  50742. function UniversalCamera(name, position, scene) {
  50743. var _this = _super.call(this, name, position, scene) || this;
  50744. _this.inputs.addGamepad();
  50745. return _this;
  50746. }
  50747. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  50748. //-- Begin properties for backward compatibility for inputs
  50749. get: function () {
  50750. var gamepad = this.inputs.attached["gamepad"];
  50751. if (gamepad)
  50752. return gamepad.gamepadAngularSensibility;
  50753. },
  50754. set: function (value) {
  50755. var gamepad = this.inputs.attached["gamepad"];
  50756. if (gamepad)
  50757. gamepad.gamepadAngularSensibility = value;
  50758. },
  50759. enumerable: true,
  50760. configurable: true
  50761. });
  50762. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  50763. get: function () {
  50764. var gamepad = this.inputs.attached["gamepad"];
  50765. if (gamepad)
  50766. return gamepad.gamepadMoveSensibility;
  50767. },
  50768. set: function (value) {
  50769. var gamepad = this.inputs.attached["gamepad"];
  50770. if (gamepad)
  50771. gamepad.gamepadMoveSensibility = value;
  50772. },
  50773. enumerable: true,
  50774. configurable: true
  50775. });
  50776. UniversalCamera.prototype.getClassName = function () {
  50777. return "UniversalCamera";
  50778. };
  50779. return UniversalCamera;
  50780. }(BABYLON.TouchCamera));
  50781. BABYLON.UniversalCamera = UniversalCamera;
  50782. })(BABYLON || (BABYLON = {}));
  50783. //# sourceMappingURL=babylon.universalCamera.js.map
  50784. /// <reference path="babylon.universalCamera.ts" />
  50785. var BABYLON;
  50786. (function (BABYLON) {
  50787. // We're mainly based on the logic defined into the FreeCamera code
  50788. var GamepadCamera = (function (_super) {
  50789. __extends(GamepadCamera, _super);
  50790. //-- end properties for backward compatibility for inputs
  50791. function GamepadCamera(name, position, scene) {
  50792. return _super.call(this, name, position, scene) || this;
  50793. }
  50794. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  50795. //-- Begin properties for backward compatibility for inputs
  50796. get: function () {
  50797. var gamepad = this.inputs.attached["gamepad"];
  50798. if (gamepad)
  50799. return gamepad.gamepadAngularSensibility;
  50800. },
  50801. set: function (value) {
  50802. var gamepad = this.inputs.attached["gamepad"];
  50803. if (gamepad)
  50804. gamepad.gamepadAngularSensibility = value;
  50805. },
  50806. enumerable: true,
  50807. configurable: true
  50808. });
  50809. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  50810. get: function () {
  50811. var gamepad = this.inputs.attached["gamepad"];
  50812. if (gamepad)
  50813. return gamepad.gamepadMoveSensibility;
  50814. },
  50815. set: function (value) {
  50816. var gamepad = this.inputs.attached["gamepad"];
  50817. if (gamepad)
  50818. gamepad.gamepadMoveSensibility = value;
  50819. },
  50820. enumerable: true,
  50821. configurable: true
  50822. });
  50823. GamepadCamera.prototype.getClassName = function () {
  50824. return "GamepadCamera";
  50825. };
  50826. return GamepadCamera;
  50827. }(BABYLON.UniversalCamera));
  50828. BABYLON.GamepadCamera = GamepadCamera;
  50829. })(BABYLON || (BABYLON = {}));
  50830. //# sourceMappingURL=babylon.gamepadCamera.js.map
  50831. var BABYLON;
  50832. (function (BABYLON) {
  50833. var PostProcessRenderPipelineManager = (function () {
  50834. function PostProcessRenderPipelineManager() {
  50835. this._renderPipelines = {};
  50836. }
  50837. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  50838. this._renderPipelines[renderPipeline._name] = renderPipeline;
  50839. };
  50840. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  50841. var renderPipeline = this._renderPipelines[renderPipelineName];
  50842. if (!renderPipeline) {
  50843. return;
  50844. }
  50845. renderPipeline._attachCameras(cameras, unique);
  50846. };
  50847. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  50848. var renderPipeline = this._renderPipelines[renderPipelineName];
  50849. if (!renderPipeline) {
  50850. return;
  50851. }
  50852. renderPipeline._detachCameras(cameras);
  50853. };
  50854. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  50855. var renderPipeline = this._renderPipelines[renderPipelineName];
  50856. if (!renderPipeline) {
  50857. return;
  50858. }
  50859. renderPipeline._enableEffect(renderEffectName, cameras);
  50860. };
  50861. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  50862. var renderPipeline = this._renderPipelines[renderPipelineName];
  50863. if (!renderPipeline) {
  50864. return;
  50865. }
  50866. renderPipeline._disableEffect(renderEffectName, cameras);
  50867. };
  50868. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  50869. var renderPipeline = this._renderPipelines[renderPipelineName];
  50870. if (!renderPipeline) {
  50871. return;
  50872. }
  50873. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  50874. };
  50875. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  50876. var renderPipeline = this._renderPipelines[renderPipelineName];
  50877. if (!renderPipeline) {
  50878. return;
  50879. }
  50880. renderPipeline._disableDisplayOnlyPass(cameras);
  50881. };
  50882. PostProcessRenderPipelineManager.prototype.update = function () {
  50883. for (var renderPipelineName in this._renderPipelines) {
  50884. var pipeline = this._renderPipelines[renderPipelineName];
  50885. if (!pipeline.isSupported) {
  50886. pipeline.dispose();
  50887. delete this._renderPipelines[renderPipelineName];
  50888. }
  50889. else {
  50890. pipeline._update();
  50891. }
  50892. }
  50893. };
  50894. return PostProcessRenderPipelineManager;
  50895. }());
  50896. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  50897. })(BABYLON || (BABYLON = {}));
  50898. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  50899. var BABYLON;
  50900. (function (BABYLON) {
  50901. var PostProcessRenderPass = (function () {
  50902. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  50903. this._enabled = true;
  50904. this._refCount = 0;
  50905. this._name = name;
  50906. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  50907. this.setRenderList(renderList);
  50908. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  50909. this._renderTexture.onAfterRenderObservable.add(afterRender);
  50910. this._scene = scene;
  50911. this._renderList = renderList;
  50912. }
  50913. // private
  50914. PostProcessRenderPass.prototype._incRefCount = function () {
  50915. if (this._refCount === 0) {
  50916. this._scene.customRenderTargets.push(this._renderTexture);
  50917. }
  50918. return ++this._refCount;
  50919. };
  50920. PostProcessRenderPass.prototype._decRefCount = function () {
  50921. this._refCount--;
  50922. if (this._refCount <= 0) {
  50923. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  50924. }
  50925. return this._refCount;
  50926. };
  50927. PostProcessRenderPass.prototype._update = function () {
  50928. this.setRenderList(this._renderList);
  50929. };
  50930. // public
  50931. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  50932. this._renderTexture.renderList = renderList;
  50933. };
  50934. PostProcessRenderPass.prototype.getRenderTexture = function () {
  50935. return this._renderTexture;
  50936. };
  50937. return PostProcessRenderPass;
  50938. }());
  50939. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  50940. })(BABYLON || (BABYLON = {}));
  50941. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  50942. var BABYLON;
  50943. (function (BABYLON) {
  50944. var PostProcessRenderEffect = (function () {
  50945. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  50946. this._engine = engine;
  50947. this._name = name;
  50948. this._singleInstance = singleInstance || true;
  50949. this._getPostProcess = getPostProcess;
  50950. this._cameras = [];
  50951. this._indicesForCamera = [];
  50952. this._postProcesses = {};
  50953. this._renderPasses = {};
  50954. this._renderEffectAsPasses = {};
  50955. }
  50956. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  50957. get: function () {
  50958. for (var index in this._postProcesses) {
  50959. if (!this._postProcesses[index].isSupported) {
  50960. return false;
  50961. }
  50962. }
  50963. return true;
  50964. },
  50965. enumerable: true,
  50966. configurable: true
  50967. });
  50968. PostProcessRenderEffect.prototype._update = function () {
  50969. for (var renderPassName in this._renderPasses) {
  50970. this._renderPasses[renderPassName]._update();
  50971. }
  50972. };
  50973. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  50974. this._renderPasses[renderPass._name] = renderPass;
  50975. this._linkParameters();
  50976. };
  50977. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  50978. delete this._renderPasses[renderPass._name];
  50979. this._linkParameters();
  50980. };
  50981. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  50982. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  50983. this._linkParameters();
  50984. };
  50985. PostProcessRenderEffect.prototype.getPass = function (passName) {
  50986. for (var renderPassName in this._renderPasses) {
  50987. if (renderPassName === passName) {
  50988. return this._renderPasses[passName];
  50989. }
  50990. }
  50991. };
  50992. PostProcessRenderEffect.prototype.emptyPasses = function () {
  50993. this._renderPasses = {};
  50994. this._linkParameters();
  50995. };
  50996. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  50997. var cameraKey;
  50998. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  50999. for (var i = 0; i < _cam.length; i++) {
  51000. var camera = _cam[i];
  51001. var cameraName = camera.name;
  51002. if (this._singleInstance) {
  51003. cameraKey = 0;
  51004. }
  51005. else {
  51006. cameraKey = cameraName;
  51007. }
  51008. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  51009. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  51010. if (!this._indicesForCamera[cameraName]) {
  51011. this._indicesForCamera[cameraName] = [];
  51012. }
  51013. this._indicesForCamera[cameraName].push(index);
  51014. if (this._cameras.indexOf(camera) === -1) {
  51015. this._cameras[cameraName] = camera;
  51016. }
  51017. for (var passName in this._renderPasses) {
  51018. this._renderPasses[passName]._incRefCount();
  51019. }
  51020. }
  51021. this._linkParameters();
  51022. };
  51023. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  51024. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  51025. for (var i = 0; i < _cam.length; i++) {
  51026. var camera = _cam[i];
  51027. var cameraName = camera.name;
  51028. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  51029. var index = this._cameras.indexOf(cameraName);
  51030. this._indicesForCamera.splice(index, 1);
  51031. this._cameras.splice(index, 1);
  51032. for (var passName in this._renderPasses) {
  51033. this._renderPasses[passName]._decRefCount();
  51034. }
  51035. }
  51036. };
  51037. PostProcessRenderEffect.prototype._enable = function (cameras) {
  51038. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  51039. for (var i = 0; i < _cam.length; i++) {
  51040. var camera = _cam[i];
  51041. var cameraName = camera.name;
  51042. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  51043. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  51044. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  51045. }
  51046. }
  51047. for (var passName in this._renderPasses) {
  51048. this._renderPasses[passName]._incRefCount();
  51049. }
  51050. }
  51051. };
  51052. PostProcessRenderEffect.prototype._disable = function (cameras) {
  51053. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  51054. for (var i = 0; i < _cam.length; i++) {
  51055. var camera = _cam[i];
  51056. var cameraName = camera.Name;
  51057. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  51058. for (var passName in this._renderPasses) {
  51059. this._renderPasses[passName]._decRefCount();
  51060. }
  51061. }
  51062. };
  51063. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  51064. if (this._singleInstance) {
  51065. return this._postProcesses[0];
  51066. }
  51067. else {
  51068. return this._postProcesses[camera.name];
  51069. }
  51070. };
  51071. PostProcessRenderEffect.prototype._linkParameters = function () {
  51072. var _this = this;
  51073. for (var index in this._postProcesses) {
  51074. if (this.applyParameters) {
  51075. this.applyParameters(this._postProcesses[index]);
  51076. }
  51077. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  51078. _this._linkTextures(effect);
  51079. });
  51080. }
  51081. };
  51082. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  51083. for (var renderPassName in this._renderPasses) {
  51084. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  51085. }
  51086. for (var renderEffectName in this._renderEffectAsPasses) {
  51087. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  51088. }
  51089. };
  51090. return PostProcessRenderEffect;
  51091. }());
  51092. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  51093. })(BABYLON || (BABYLON = {}));
  51094. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  51095. var BABYLON;
  51096. (function (BABYLON) {
  51097. var PostProcessRenderPipeline = (function () {
  51098. function PostProcessRenderPipeline(engine, name) {
  51099. this._engine = engine;
  51100. this._name = name;
  51101. this._renderEffects = new Array();
  51102. this._renderEffectsForIsolatedPass = new Array();
  51103. this._cameras = [];
  51104. }
  51105. PostProcessRenderPipeline.prototype.getClassName = function () {
  51106. return "PostProcessRenderPipeline";
  51107. };
  51108. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  51109. get: function () {
  51110. for (var renderEffectName in this._renderEffects) {
  51111. if (!this._renderEffects[renderEffectName].isSupported) {
  51112. return false;
  51113. }
  51114. }
  51115. return true;
  51116. },
  51117. enumerable: true,
  51118. configurable: true
  51119. });
  51120. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  51121. this._renderEffects[renderEffect._name] = renderEffect;
  51122. };
  51123. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  51124. var renderEffects = this._renderEffects[renderEffectName];
  51125. if (!renderEffects) {
  51126. return;
  51127. }
  51128. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  51129. };
  51130. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  51131. var renderEffects = this._renderEffects[renderEffectName];
  51132. if (!renderEffects) {
  51133. return;
  51134. }
  51135. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  51136. };
  51137. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  51138. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  51139. var indicesToDelete = [];
  51140. var i;
  51141. for (i = 0; i < _cam.length; i++) {
  51142. var camera = _cam[i];
  51143. var cameraName = camera.name;
  51144. if (this._cameras.indexOf(camera) === -1) {
  51145. this._cameras[cameraName] = camera;
  51146. }
  51147. else if (unique) {
  51148. indicesToDelete.push(i);
  51149. }
  51150. }
  51151. for (i = 0; i < indicesToDelete.length; i++) {
  51152. cameras.splice(indicesToDelete[i], 1);
  51153. }
  51154. for (var renderEffectName in this._renderEffects) {
  51155. this._renderEffects[renderEffectName]._attachCameras(_cam);
  51156. }
  51157. };
  51158. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  51159. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  51160. for (var renderEffectName in this._renderEffects) {
  51161. this._renderEffects[renderEffectName]._detachCameras(_cam);
  51162. }
  51163. for (var i = 0; i < _cam.length; i++) {
  51164. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  51165. }
  51166. };
  51167. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  51168. var _this = this;
  51169. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  51170. var pass = null;
  51171. var renderEffectName;
  51172. for (renderEffectName in this._renderEffects) {
  51173. pass = this._renderEffects[renderEffectName].getPass(passName);
  51174. if (pass != null) {
  51175. break;
  51176. }
  51177. }
  51178. if (pass === null) {
  51179. return;
  51180. }
  51181. for (renderEffectName in this._renderEffects) {
  51182. this._renderEffects[renderEffectName]._disable(_cam);
  51183. }
  51184. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  51185. for (var i = 0; i < _cam.length; i++) {
  51186. var camera = _cam[i];
  51187. var cameraName = camera.name;
  51188. 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); });
  51189. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  51190. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  51191. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  51192. }
  51193. };
  51194. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  51195. var _this = this;
  51196. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  51197. for (var i = 0; i < _cam.length; i++) {
  51198. var camera = _cam[i];
  51199. var cameraName = camera.name;
  51200. 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); });
  51201. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  51202. }
  51203. for (var renderEffectName in this._renderEffects) {
  51204. this._renderEffects[renderEffectName]._enable(_cam);
  51205. }
  51206. };
  51207. PostProcessRenderPipeline.prototype._update = function () {
  51208. for (var renderEffectName in this._renderEffects) {
  51209. this._renderEffects[renderEffectName]._update();
  51210. }
  51211. for (var i = 0; i < this._cameras.length; i++) {
  51212. var cameraName = this._cameras[i].name;
  51213. if (this._renderEffectsForIsolatedPass[cameraName]) {
  51214. this._renderEffectsForIsolatedPass[cameraName]._update();
  51215. }
  51216. }
  51217. };
  51218. PostProcessRenderPipeline.prototype._reset = function () {
  51219. this._renderEffects = new Array();
  51220. this._renderEffectsForIsolatedPass = new Array();
  51221. };
  51222. PostProcessRenderPipeline.prototype.dispose = function () {
  51223. // Must be implemented by children
  51224. };
  51225. return PostProcessRenderPipeline;
  51226. }());
  51227. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  51228. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  51229. __decorate([
  51230. BABYLON.serialize()
  51231. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  51232. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  51233. })(BABYLON || (BABYLON = {}));
  51234. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  51235. var BABYLON;
  51236. (function (BABYLON) {
  51237. var DepthRenderer = (function () {
  51238. function DepthRenderer(scene, type) {
  51239. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  51240. var _this = this;
  51241. this._viewMatrix = BABYLON.Matrix.Zero();
  51242. this._projectionMatrix = BABYLON.Matrix.Zero();
  51243. this._transformMatrix = BABYLON.Matrix.Zero();
  51244. this._worldViewProjection = BABYLON.Matrix.Zero();
  51245. this._scene = scene;
  51246. var engine = scene.getEngine();
  51247. // Render target
  51248. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  51249. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51250. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51251. this._depthMap.refreshRate = 1;
  51252. this._depthMap.renderParticles = false;
  51253. this._depthMap.renderList = null;
  51254. // set default depth value to 1.0 (far away)
  51255. this._depthMap.onClearObservable.add(function (engine) {
  51256. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  51257. });
  51258. // Custom render function
  51259. var renderSubMesh = function (subMesh) {
  51260. var mesh = subMesh.getRenderingMesh();
  51261. var scene = _this._scene;
  51262. var engine = scene.getEngine();
  51263. // Culling
  51264. engine.setState(subMesh.getMaterial().backFaceCulling);
  51265. // Managing instances
  51266. var batch = mesh._getInstancesRenderList(subMesh._id);
  51267. if (batch.mustReturn) {
  51268. return;
  51269. }
  51270. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  51271. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  51272. engine.enableEffect(_this._effect);
  51273. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  51274. var material = subMesh.getMaterial();
  51275. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  51276. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  51277. // Alpha test
  51278. if (material && material.needAlphaTesting()) {
  51279. var alphaTexture = material.getAlphaTestTexture();
  51280. _this._effect.setTexture("diffuseSampler", alphaTexture);
  51281. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  51282. }
  51283. // Bones
  51284. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51285. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  51286. }
  51287. // Draw
  51288. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  51289. }
  51290. };
  51291. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  51292. var index;
  51293. for (index = 0; index < opaqueSubMeshes.length; index++) {
  51294. renderSubMesh(opaqueSubMeshes.data[index]);
  51295. }
  51296. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  51297. renderSubMesh(alphaTestSubMeshes.data[index]);
  51298. }
  51299. };
  51300. }
  51301. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  51302. var material = subMesh.getMaterial();
  51303. if (material.disableDepthWrite) {
  51304. return false;
  51305. }
  51306. var defines = [];
  51307. var attribs = [BABYLON.VertexBuffer.PositionKind];
  51308. var mesh = subMesh.getMesh();
  51309. var scene = mesh.getScene();
  51310. // Alpha test
  51311. if (material && material.needAlphaTesting()) {
  51312. defines.push("#define ALPHATEST");
  51313. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  51314. attribs.push(BABYLON.VertexBuffer.UVKind);
  51315. defines.push("#define UV1");
  51316. }
  51317. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  51318. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  51319. defines.push("#define UV2");
  51320. }
  51321. }
  51322. // Bones
  51323. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51324. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  51325. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  51326. if (mesh.numBoneInfluencers > 4) {
  51327. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  51328. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  51329. }
  51330. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  51331. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  51332. }
  51333. else {
  51334. defines.push("#define NUM_BONE_INFLUENCERS 0");
  51335. }
  51336. // Instances
  51337. if (useInstances) {
  51338. defines.push("#define INSTANCES");
  51339. attribs.push("world0");
  51340. attribs.push("world1");
  51341. attribs.push("world2");
  51342. attribs.push("world3");
  51343. }
  51344. // Get correct effect
  51345. var join = defines.join("\n");
  51346. if (this._cachedDefines !== join) {
  51347. this._cachedDefines = join;
  51348. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  51349. }
  51350. return this._effect.isReady();
  51351. };
  51352. DepthRenderer.prototype.getDepthMap = function () {
  51353. return this._depthMap;
  51354. };
  51355. // Methods
  51356. DepthRenderer.prototype.dispose = function () {
  51357. this._depthMap.dispose();
  51358. };
  51359. return DepthRenderer;
  51360. }());
  51361. BABYLON.DepthRenderer = DepthRenderer;
  51362. })(BABYLON || (BABYLON = {}));
  51363. //# sourceMappingURL=babylon.depthRenderer.js.map
  51364. var BABYLON;
  51365. (function (BABYLON) {
  51366. var SSAORenderingPipeline = (function (_super) {
  51367. __extends(SSAORenderingPipeline, _super);
  51368. /**
  51369. * @constructor
  51370. * @param {string} name - The rendering pipeline name
  51371. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  51372. * @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 }
  51373. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  51374. */
  51375. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  51376. var _this = _super.call(this, scene.getEngine(), name) || this;
  51377. // Members
  51378. /**
  51379. * The PassPostProcess id in the pipeline that contains the original scene color
  51380. * @type {string}
  51381. */
  51382. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  51383. /**
  51384. * The SSAO PostProcess id in the pipeline
  51385. * @type {string}
  51386. */
  51387. _this.SSAORenderEffect = "SSAORenderEffect";
  51388. /**
  51389. * The horizontal blur PostProcess id in the pipeline
  51390. * @type {string}
  51391. */
  51392. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  51393. /**
  51394. * The vertical blur PostProcess id in the pipeline
  51395. * @type {string}
  51396. */
  51397. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  51398. /**
  51399. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  51400. * @type {string}
  51401. */
  51402. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  51403. /**
  51404. * The output strength of the SSAO post-process. Default value is 1.0.
  51405. * @type {number}
  51406. */
  51407. _this.totalStrength = 1.0;
  51408. /**
  51409. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  51410. * @type {number}
  51411. */
  51412. _this.radius = 0.0001;
  51413. /**
  51414. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  51415. * Must not be equal to fallOff and superior to fallOff.
  51416. * Default value is 0.975
  51417. * @type {number}
  51418. */
  51419. _this.area = 0.0075;
  51420. /**
  51421. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  51422. * Must not be equal to area and inferior to area.
  51423. * Default value is 0.0
  51424. * @type {number}
  51425. */
  51426. _this.fallOff = 0.000001;
  51427. /**
  51428. * The base color of the SSAO post-process
  51429. * The final result is "base + ssao" between [0, 1]
  51430. * @type {number}
  51431. */
  51432. _this.base = 0.5;
  51433. _this._firstUpdate = true;
  51434. _this._scene = scene;
  51435. // Set up assets
  51436. _this._createRandomTexture();
  51437. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  51438. var ssaoRatio = ratio.ssaoRatio || ratio;
  51439. var combineRatio = ratio.combineRatio || ratio;
  51440. _this._ratio = {
  51441. ssaoRatio: ssaoRatio,
  51442. combineRatio: combineRatio
  51443. };
  51444. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  51445. _this._createSSAOPostProcess(ssaoRatio);
  51446. _this._createBlurPostProcess(ssaoRatio);
  51447. _this._createSSAOCombinePostProcess(combineRatio);
  51448. // Set up pipeline
  51449. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  51450. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  51451. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  51452. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  51453. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  51454. // Finish
  51455. scene.postProcessRenderPipelineManager.addPipeline(_this);
  51456. if (cameras)
  51457. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  51458. return _this;
  51459. }
  51460. // Public Methods
  51461. /**
  51462. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  51463. */
  51464. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  51465. if (disableDepthRender === void 0) { disableDepthRender = false; }
  51466. for (var i = 0; i < this._scene.cameras.length; i++) {
  51467. var camera = this._scene.cameras[i];
  51468. this._originalColorPostProcess.dispose(camera);
  51469. this._ssaoPostProcess.dispose(camera);
  51470. this._blurHPostProcess.dispose(camera);
  51471. this._blurVPostProcess.dispose(camera);
  51472. this._ssaoCombinePostProcess.dispose(camera);
  51473. }
  51474. this._randomTexture.dispose();
  51475. if (disableDepthRender)
  51476. this._scene.disableDepthRenderer();
  51477. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  51478. _super.prototype.dispose.call(this);
  51479. };
  51480. // Private Methods
  51481. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  51482. var _this = this;
  51483. /*
  51484. var samplerOffsets = [
  51485. -8.0, -6.0, -4.0, -2.0,
  51486. 0.0,
  51487. 2.0, 4.0, 6.0, 8.0
  51488. ];
  51489. */
  51490. var samples = 16;
  51491. var samplerOffsets = [];
  51492. for (var i = -8; i < 8; i++) {
  51493. samplerOffsets.push(i * 2);
  51494. }
  51495. 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");
  51496. this._blurHPostProcess.onApply = function (effect) {
  51497. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  51498. effect.setTexture("depthSampler", _this._depthTexture);
  51499. if (_this._firstUpdate) {
  51500. effect.setArray("samplerOffsets", samplerOffsets);
  51501. }
  51502. };
  51503. 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");
  51504. this._blurVPostProcess.onApply = function (effect) {
  51505. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  51506. effect.setTexture("depthSampler", _this._depthTexture);
  51507. if (_this._firstUpdate) {
  51508. effect.setArray("samplerOffsets", samplerOffsets);
  51509. _this._firstUpdate = false;
  51510. }
  51511. };
  51512. };
  51513. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  51514. var _this = this;
  51515. var numSamples = 16;
  51516. var sampleSphere = [
  51517. 0.5381, 0.1856, -0.4319,
  51518. 0.1379, 0.2486, 0.4430,
  51519. 0.3371, 0.5679, -0.0057,
  51520. -0.6999, -0.0451, -0.0019,
  51521. 0.0689, -0.1598, -0.8547,
  51522. 0.0560, 0.0069, -0.1843,
  51523. -0.0146, 0.1402, 0.0762,
  51524. 0.0100, -0.1924, -0.0344,
  51525. -0.3577, -0.5301, -0.4358,
  51526. -0.3169, 0.1063, 0.0158,
  51527. 0.0103, -0.5869, 0.0046,
  51528. -0.0897, -0.4940, 0.3287,
  51529. 0.7119, -0.0154, -0.0918,
  51530. -0.0533, 0.0596, -0.5411,
  51531. 0.0352, -0.0631, 0.5460,
  51532. -0.4776, 0.2847, -0.0271
  51533. ];
  51534. var samplesFactor = 1.0 / numSamples;
  51535. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  51536. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  51537. "area", "fallOff", "base", "range", "viewport"
  51538. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  51539. var viewport = new BABYLON.Vector2(0, 0);
  51540. this._ssaoPostProcess.onApply = function (effect) {
  51541. if (_this._firstUpdate) {
  51542. effect.setArray3("sampleSphere", sampleSphere);
  51543. effect.setFloat("samplesFactor", samplesFactor);
  51544. effect.setFloat("randTextureTiles", 4.0);
  51545. }
  51546. effect.setFloat("totalStrength", _this.totalStrength);
  51547. effect.setFloat("radius", _this.radius);
  51548. effect.setFloat("area", _this.area);
  51549. effect.setFloat("fallOff", _this.fallOff);
  51550. effect.setFloat("base", _this.base);
  51551. effect.setTexture("textureSampler", _this._depthTexture);
  51552. effect.setTexture("randomSampler", _this._randomTexture);
  51553. };
  51554. };
  51555. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  51556. var _this = this;
  51557. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  51558. this._ssaoCombinePostProcess.onApply = function (effect) {
  51559. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  51560. };
  51561. };
  51562. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  51563. var size = 512;
  51564. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  51565. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  51566. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  51567. var context = this._randomTexture.getContext();
  51568. var rand = function (min, max) {
  51569. return Math.random() * (max - min) + min;
  51570. };
  51571. var randVector = BABYLON.Vector3.Zero();
  51572. for (var x = 0; x < size; x++) {
  51573. for (var y = 0; y < size; y++) {
  51574. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  51575. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  51576. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  51577. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  51578. context.fillRect(x, y, 1, 1);
  51579. }
  51580. }
  51581. this._randomTexture.update(false);
  51582. };
  51583. return SSAORenderingPipeline;
  51584. }(BABYLON.PostProcessRenderPipeline));
  51585. __decorate([
  51586. BABYLON.serialize()
  51587. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  51588. __decorate([
  51589. BABYLON.serialize()
  51590. ], SSAORenderingPipeline.prototype, "radius", void 0);
  51591. __decorate([
  51592. BABYLON.serialize()
  51593. ], SSAORenderingPipeline.prototype, "area", void 0);
  51594. __decorate([
  51595. BABYLON.serialize()
  51596. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  51597. __decorate([
  51598. BABYLON.serialize()
  51599. ], SSAORenderingPipeline.prototype, "base", void 0);
  51600. __decorate([
  51601. BABYLON.serialize()
  51602. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  51603. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  51604. })(BABYLON || (BABYLON = {}));
  51605. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  51606. var BABYLON;
  51607. (function (BABYLON) {
  51608. var SSAO2RenderingPipeline = (function (_super) {
  51609. __extends(SSAO2RenderingPipeline, _super);
  51610. /**
  51611. * @constructor
  51612. * @param {string} name - The rendering pipeline name
  51613. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  51614. * @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 }
  51615. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  51616. */
  51617. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  51618. var _this = _super.call(this, scene.getEngine(), name) || this;
  51619. // Members
  51620. /**
  51621. * The PassPostProcess id in the pipeline that contains the original scene color
  51622. * @type {string}
  51623. */
  51624. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  51625. /**
  51626. * The SSAO PostProcess id in the pipeline
  51627. * @type {string}
  51628. */
  51629. _this.SSAORenderEffect = "SSAORenderEffect";
  51630. /**
  51631. * The horizontal blur PostProcess id in the pipeline
  51632. * @type {string}
  51633. */
  51634. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  51635. /**
  51636. * The vertical blur PostProcess id in the pipeline
  51637. * @type {string}
  51638. */
  51639. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  51640. /**
  51641. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  51642. * @type {string}
  51643. */
  51644. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  51645. /**
  51646. * The output strength of the SSAO post-process. Default value is 1.0.
  51647. * @type {number}
  51648. */
  51649. _this.totalStrength = 1.0;
  51650. /**
  51651. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  51652. * @type {number}
  51653. */
  51654. _this.maxZ = 100.0;
  51655. /**
  51656. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  51657. * @type {number}
  51658. */
  51659. _this.minZAspect = 0.2;
  51660. /**
  51661. * Number of samples used for the SSAO calculations. Default value is 8
  51662. * @type {number}
  51663. */
  51664. _this._samples = 8;
  51665. /**
  51666. * Are we using bilateral blur ?
  51667. * @type {boolean}
  51668. */
  51669. _this._expensiveBlur = true;
  51670. /**
  51671. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  51672. * @type {number}
  51673. */
  51674. _this.radius = 2.0;
  51675. /**
  51676. * The base color of the SSAO post-process
  51677. * The final result is "base + ssao" between [0, 1]
  51678. * @type {number}
  51679. */
  51680. _this.base = 0.1;
  51681. _this._firstUpdate = true;
  51682. _this._scene = scene;
  51683. if (!_this.isSupported) {
  51684. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  51685. return _this;
  51686. }
  51687. var ssaoRatio = ratio.ssaoRatio || ratio;
  51688. var blurRatio = ratio.blurRatio || ratio;
  51689. _this._ratio = {
  51690. ssaoRatio: ssaoRatio,
  51691. blurRatio: blurRatio
  51692. };
  51693. // Set up assets
  51694. _this._createRandomTexture();
  51695. _this._depthTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[0];
  51696. _this._normalTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[1];
  51697. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  51698. _this._createSSAOPostProcess(1.0);
  51699. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  51700. _this._createSSAOCombinePostProcess(blurRatio);
  51701. // Set up pipeline
  51702. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  51703. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  51704. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  51705. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  51706. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  51707. // Finish
  51708. scene.postProcessRenderPipelineManager.addPipeline(_this);
  51709. if (cameras)
  51710. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  51711. return _this;
  51712. }
  51713. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  51714. get: function () {
  51715. return this._samples;
  51716. },
  51717. set: function (n) {
  51718. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  51719. this._samples = n;
  51720. this._sampleSphere = this._generateHemisphere();
  51721. this._firstUpdate = true;
  51722. },
  51723. enumerable: true,
  51724. configurable: true
  51725. });
  51726. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  51727. get: function () {
  51728. return this._expensiveBlur;
  51729. },
  51730. set: function (b) {
  51731. 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"]);
  51732. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  51733. this._expensiveBlur = b;
  51734. this._firstUpdate = true;
  51735. },
  51736. enumerable: true,
  51737. configurable: true
  51738. });
  51739. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  51740. /**
  51741. * Support test.
  51742. * @type {boolean}
  51743. */
  51744. get: function () {
  51745. var engine = BABYLON.Engine.LastCreatedEngine;
  51746. return engine.webGLVersion > 1;
  51747. },
  51748. enumerable: true,
  51749. configurable: true
  51750. });
  51751. // Public Methods
  51752. /**
  51753. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  51754. */
  51755. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  51756. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  51757. for (var i = 0; i < this._scene.cameras.length; i++) {
  51758. var camera = this._scene.cameras[i];
  51759. this._originalColorPostProcess.dispose(camera);
  51760. this._ssaoPostProcess.dispose(camera);
  51761. this._blurHPostProcess.dispose(camera);
  51762. this._blurVPostProcess.dispose(camera);
  51763. this._ssaoCombinePostProcess.dispose(camera);
  51764. }
  51765. this._randomTexture.dispose();
  51766. if (disableGeometryBufferRenderer)
  51767. this._scene.disableGeometryBufferRenderer();
  51768. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  51769. _super.prototype.dispose.call(this);
  51770. };
  51771. // Private Methods
  51772. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  51773. var _this = this;
  51774. var samples = 16;
  51775. this._samplerOffsets = [];
  51776. var expensive = this.expensiveBlur;
  51777. for (var i = -8; i < 8; i++) {
  51778. this._samplerOffsets.push(i * 2 + 0.5);
  51779. }
  51780. 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");
  51781. this._blurHPostProcess.onApply = function (effect) {
  51782. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  51783. effect.setFloat("near", _this._scene.activeCamera.minZ);
  51784. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  51785. effect.setFloat("radius", _this.radius);
  51786. effect.setTexture("depthSampler", _this._depthTexture);
  51787. if (_this._firstUpdate) {
  51788. effect.setArray("samplerOffsets", _this._samplerOffsets);
  51789. }
  51790. };
  51791. 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");
  51792. this._blurVPostProcess.onApply = function (effect) {
  51793. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  51794. effect.setFloat("near", _this._scene.activeCamera.minZ);
  51795. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  51796. effect.setFloat("radius", _this.radius);
  51797. effect.setTexture("depthSampler", _this._depthTexture);
  51798. if (_this._firstUpdate) {
  51799. effect.setArray("samplerOffsets", _this._samplerOffsets);
  51800. _this._firstUpdate = false;
  51801. }
  51802. };
  51803. };
  51804. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  51805. var numSamples = this.samples;
  51806. var result = [];
  51807. var vector, scale;
  51808. var rand = function (min, max) {
  51809. return Math.random() * (max - min) + min;
  51810. };
  51811. var lerp = function (start, end, percent) {
  51812. return (start + percent * (end - start));
  51813. };
  51814. var i = 0;
  51815. var normal = new BABYLON.Vector3(0, 0, 1);
  51816. while (i < numSamples) {
  51817. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  51818. vector.normalize();
  51819. scale = i / numSamples;
  51820. scale = lerp(0.1, 1.0, scale * scale);
  51821. vector.scaleInPlace(scale);
  51822. result.push(vector.x, vector.y, vector.z);
  51823. i++;
  51824. }
  51825. return result;
  51826. };
  51827. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  51828. var _this = this;
  51829. var numSamples = this.samples;
  51830. this._sampleSphere = this._generateHemisphere();
  51831. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  51832. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  51833. "base", "range", "projection", "near", "far", "texelSize",
  51834. "xViewport", "yViewport", "maxZ", "minZAspect"
  51835. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  51836. this._ssaoPostProcess.onApply = function (effect) {
  51837. if (_this._firstUpdate) {
  51838. effect.setArray3("sampleSphere", _this._sampleSphere);
  51839. effect.setFloat("randTextureTiles", 4.0);
  51840. }
  51841. effect.setFloat("samplesFactor", 1 / _this.samples);
  51842. effect.setFloat("totalStrength", _this.totalStrength);
  51843. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  51844. effect.setFloat("radius", _this.radius);
  51845. effect.setFloat("maxZ", _this.maxZ);
  51846. effect.setFloat("minZAspect", _this.minZAspect);
  51847. effect.setFloat("base", _this.base);
  51848. effect.setFloat("near", _this._scene.activeCamera.minZ);
  51849. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  51850. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  51851. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  51852. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  51853. effect.setTexture("textureSampler", _this._depthTexture);
  51854. effect.setTexture("normalSampler", _this._normalTexture);
  51855. effect.setTexture("randomSampler", _this._randomTexture);
  51856. };
  51857. };
  51858. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  51859. var _this = this;
  51860. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  51861. this._ssaoCombinePostProcess.onApply = function (effect) {
  51862. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  51863. };
  51864. };
  51865. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  51866. var size = 512;
  51867. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  51868. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  51869. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  51870. var context = this._randomTexture.getContext();
  51871. var rand = function (min, max) {
  51872. return Math.random() * (max - min) + min;
  51873. };
  51874. var randVector = BABYLON.Vector3.Zero();
  51875. for (var x = 0; x < size; x++) {
  51876. for (var y = 0; y < size; y++) {
  51877. randVector.x = rand(0.0, 1.0);
  51878. randVector.y = rand(0.0, 1.0);
  51879. randVector.z = 0.0;
  51880. randVector.normalize();
  51881. randVector.scaleInPlace(255);
  51882. randVector.x = Math.floor(randVector.x);
  51883. randVector.y = Math.floor(randVector.y);
  51884. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  51885. context.fillRect(x, y, 1, 1);
  51886. }
  51887. }
  51888. this._randomTexture.update(false);
  51889. };
  51890. return SSAO2RenderingPipeline;
  51891. }(BABYLON.PostProcessRenderPipeline));
  51892. __decorate([
  51893. BABYLON.serialize()
  51894. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  51895. __decorate([
  51896. BABYLON.serialize()
  51897. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  51898. __decorate([
  51899. BABYLON.serialize()
  51900. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  51901. __decorate([
  51902. BABYLON.serialize("samples")
  51903. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  51904. __decorate([
  51905. BABYLON.serialize("expensiveBlur")
  51906. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  51907. __decorate([
  51908. BABYLON.serialize()
  51909. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  51910. __decorate([
  51911. BABYLON.serialize()
  51912. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  51913. __decorate([
  51914. BABYLON.serialize()
  51915. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  51916. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  51917. })(BABYLON || (BABYLON = {}));
  51918. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  51919. // BABYLON.JS Chromatic Aberration GLSL Shader
  51920. // Author: Olivier Guyot
  51921. // Separates very slightly R, G and B colors on the edges of the screen
  51922. // Inspired by Francois Tarlier & Martins Upitis
  51923. var BABYLON;
  51924. (function (BABYLON) {
  51925. var LensRenderingPipeline = (function (_super) {
  51926. __extends(LensRenderingPipeline, _super);
  51927. /**
  51928. * @constructor
  51929. *
  51930. * Effect parameters are as follow:
  51931. * {
  51932. * chromatic_aberration: number; // from 0 to x (1 for realism)
  51933. * edge_blur: number; // from 0 to x (1 for realism)
  51934. * distortion: number; // from 0 to x (1 for realism)
  51935. * grain_amount: number; // from 0 to 1
  51936. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  51937. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  51938. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  51939. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  51940. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  51941. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  51942. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  51943. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  51944. * }
  51945. * Note: if an effect parameter is unset, effect is disabled
  51946. *
  51947. * @param {string} name - The rendering pipeline name
  51948. * @param {object} parameters - An object containing all parameters (see above)
  51949. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  51950. * @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)
  51951. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  51952. */
  51953. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  51954. if (ratio === void 0) { ratio = 1.0; }
  51955. var _this = _super.call(this, scene.getEngine(), name) || this;
  51956. // Lens effects can be of the following:
  51957. // - chromatic aberration (slight shift of RGB colors)
  51958. // - blur on the edge of the lens
  51959. // - lens distortion
  51960. // - depth-of-field blur & highlights enhancing
  51961. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  51962. // - grain effect (noise or custom texture)
  51963. // Two additional texture samplers are needed:
  51964. // - depth map (for depth-of-field)
  51965. // - grain texture
  51966. /**
  51967. * The chromatic aberration PostProcess id in the pipeline
  51968. * @type {string}
  51969. */
  51970. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  51971. /**
  51972. * The highlights enhancing PostProcess id in the pipeline
  51973. * @type {string}
  51974. */
  51975. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  51976. /**
  51977. * The depth-of-field PostProcess id in the pipeline
  51978. * @type {string}
  51979. */
  51980. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  51981. _this._scene = scene;
  51982. // Fetch texture samplers
  51983. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  51984. if (parameters.grain_texture) {
  51985. _this._grainTexture = parameters.grain_texture;
  51986. }
  51987. else {
  51988. _this._createGrainTexture();
  51989. }
  51990. // save parameters
  51991. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  51992. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  51993. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  51994. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  51995. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  51996. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  51997. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  51998. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  51999. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  52000. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  52001. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  52002. // Create effects
  52003. _this._createChromaticAberrationPostProcess(ratio);
  52004. _this._createHighlightsPostProcess(ratio);
  52005. _this._createDepthOfFieldPostProcess(ratio / 4);
  52006. // Set up pipeline
  52007. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  52008. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  52009. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  52010. if (_this._highlightsGain === -1) {
  52011. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  52012. }
  52013. // Finish
  52014. scene.postProcessRenderPipelineManager.addPipeline(_this);
  52015. if (cameras) {
  52016. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  52017. }
  52018. return _this;
  52019. }
  52020. // public methods (self explanatory)
  52021. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  52022. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  52023. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  52024. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  52025. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  52026. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  52027. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  52028. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  52029. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  52030. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  52031. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  52032. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  52033. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  52034. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  52035. };
  52036. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  52037. this._highlightsPostProcess.updateEffect();
  52038. };
  52039. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  52040. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  52041. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  52042. this._highlightsGain = amount;
  52043. };
  52044. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  52045. if (this._highlightsGain === -1) {
  52046. this._highlightsGain = 1.0;
  52047. }
  52048. this._highlightsThreshold = amount;
  52049. };
  52050. LensRenderingPipeline.prototype.disableHighlights = function () {
  52051. this._highlightsGain = -1;
  52052. };
  52053. /**
  52054. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  52055. */
  52056. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  52057. if (disableDepthRender === void 0) { disableDepthRender = false; }
  52058. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  52059. this._chromaticAberrationPostProcess = undefined;
  52060. this._highlightsPostProcess = undefined;
  52061. this._depthOfFieldPostProcess = undefined;
  52062. this._grainTexture.dispose();
  52063. if (disableDepthRender)
  52064. this._scene.disableDepthRenderer();
  52065. };
  52066. // colors shifting and distortion
  52067. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  52068. var _this = this;
  52069. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  52070. [], // samplers
  52071. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  52072. this._chromaticAberrationPostProcess.onApply = function (effect) {
  52073. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  52074. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  52075. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  52076. };
  52077. };
  52078. // highlights enhancing
  52079. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  52080. var _this = this;
  52081. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  52082. [], // samplers
  52083. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  52084. this._highlightsPostProcess.onApply = function (effect) {
  52085. effect.setFloat('gain', _this._highlightsGain);
  52086. effect.setFloat('threshold', _this._highlightsThreshold);
  52087. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  52088. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  52089. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  52090. };
  52091. };
  52092. // colors shifting and distortion
  52093. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  52094. var _this = this;
  52095. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  52096. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  52097. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  52098. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  52099. this._depthOfFieldPostProcess.onApply = function (effect) {
  52100. effect.setTexture("depthSampler", _this._depthTexture);
  52101. effect.setTexture("grainSampler", _this._grainTexture);
  52102. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  52103. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  52104. effect.setFloat('grain_amount', _this._grainAmount);
  52105. effect.setBool('blur_noise', _this._blurNoise);
  52106. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  52107. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  52108. effect.setFloat('distortion', _this._distortion);
  52109. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  52110. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  52111. effect.setFloat('aperture', _this._dofAperture);
  52112. effect.setFloat('darken', _this._dofDarken);
  52113. effect.setFloat('edge_blur', _this._edgeBlur);
  52114. effect.setBool('highlights', (_this._highlightsGain !== -1));
  52115. effect.setFloat('near', _this._scene.activeCamera.minZ);
  52116. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  52117. };
  52118. };
  52119. // creates a black and white random noise texture, 512x512
  52120. LensRenderingPipeline.prototype._createGrainTexture = function () {
  52121. var size = 512;
  52122. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52123. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52124. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52125. var context = this._grainTexture.getContext();
  52126. var rand = function (min, max) {
  52127. return Math.random() * (max - min) + min;
  52128. };
  52129. var value;
  52130. for (var x = 0; x < size; x++) {
  52131. for (var y = 0; y < size; y++) {
  52132. value = Math.floor(rand(0.42, 0.58) * 255);
  52133. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  52134. context.fillRect(x, y, 1, 1);
  52135. }
  52136. }
  52137. this._grainTexture.update(false);
  52138. };
  52139. return LensRenderingPipeline;
  52140. }(BABYLON.PostProcessRenderPipeline));
  52141. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  52142. })(BABYLON || (BABYLON = {}));
  52143. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  52144. var BABYLON;
  52145. (function (BABYLON) {
  52146. var StandardRenderingPipeline = (function (_super) {
  52147. __extends(StandardRenderingPipeline, _super);
  52148. /**
  52149. * @constructor
  52150. * @param {string} name - The rendering pipeline name
  52151. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  52152. * @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)
  52153. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  52154. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  52155. */
  52156. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  52157. if (originalPostProcess === void 0) { originalPostProcess = null; }
  52158. var _this = _super.call(this, scene.getEngine(), name) || this;
  52159. _this.downSampleX4PostProcess = null;
  52160. _this.brightPassPostProcess = null;
  52161. _this.blurHPostProcesses = [];
  52162. _this.blurVPostProcesses = [];
  52163. _this.textureAdderPostProcess = null;
  52164. _this.volumetricLightPostProcess = null;
  52165. _this.volumetricLightSmoothXPostProcess = null;
  52166. _this.volumetricLightSmoothYPostProcess = null;
  52167. _this.volumetricLightMergePostProces = null;
  52168. _this.volumetricLightFinalPostProcess = null;
  52169. _this.luminancePostProcess = null;
  52170. _this.luminanceDownSamplePostProcesses = [];
  52171. _this.hdrPostProcess = null;
  52172. _this.textureAdderFinalPostProcess = null;
  52173. _this.lensFlareFinalPostProcess = null;
  52174. _this.hdrFinalPostProcess = null;
  52175. _this.lensFlarePostProcess = null;
  52176. _this.lensFlareComposePostProcess = null;
  52177. _this.motionBlurPostProcess = null;
  52178. _this.depthOfFieldPostProcess = null;
  52179. // Values
  52180. _this.brightThreshold = 1.0;
  52181. _this.blurWidth = 512.0;
  52182. _this.horizontalBlur = false;
  52183. _this.exposure = 1.0;
  52184. _this.lensTexture = null;
  52185. _this.volumetricLightCoefficient = 0.2;
  52186. _this.volumetricLightPower = 4.0;
  52187. _this.volumetricLightBlurScale = 64.0;
  52188. _this.sourceLight = null;
  52189. _this.hdrMinimumLuminance = 1.0;
  52190. _this.hdrDecreaseRate = 0.5;
  52191. _this.hdrIncreaseRate = 0.5;
  52192. _this.lensColorTexture = null;
  52193. _this.lensFlareStrength = 20.0;
  52194. _this.lensFlareGhostDispersal = 1.4;
  52195. _this.lensFlareHaloWidth = 0.7;
  52196. _this.lensFlareDistortionStrength = 16.0;
  52197. _this.lensStarTexture = null;
  52198. _this.lensFlareDirtTexture = null;
  52199. _this.depthOfFieldDistance = 10.0;
  52200. _this.depthOfFieldBlurWidth = 64.0;
  52201. _this.motionStrength = 1.0;
  52202. // IAnimatable
  52203. _this.animations = [];
  52204. _this._currentDepthOfFieldSource = null;
  52205. _this._hdrCurrentLuminance = 1.0;
  52206. // Getters and setters
  52207. _this._bloomEnabled = true;
  52208. _this._depthOfFieldEnabled = false;
  52209. _this._vlsEnabled = false;
  52210. _this._lensFlareEnabled = false;
  52211. _this._hdrEnabled = false;
  52212. _this._motionBlurEnabled = false;
  52213. _this._motionBlurSamples = 64.0;
  52214. _this._volumetricLightStepsCount = 50.0;
  52215. _this._cameras = cameras || [];
  52216. // Initialize
  52217. _this._scene = scene;
  52218. _this._basePostProcess = originalPostProcess;
  52219. _this._ratio = ratio;
  52220. // Misc
  52221. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  52222. // Finish
  52223. scene.postProcessRenderPipelineManager.addPipeline(_this);
  52224. _this._buildPipeline();
  52225. return _this;
  52226. }
  52227. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  52228. get: function () {
  52229. return this._bloomEnabled;
  52230. },
  52231. set: function (enabled) {
  52232. if (this._bloomEnabled === enabled) {
  52233. return;
  52234. }
  52235. this._bloomEnabled = enabled;
  52236. this._buildPipeline();
  52237. },
  52238. enumerable: true,
  52239. configurable: true
  52240. });
  52241. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  52242. get: function () {
  52243. return this._depthOfFieldEnabled;
  52244. },
  52245. set: function (enabled) {
  52246. if (this._depthOfFieldEnabled === enabled) {
  52247. return;
  52248. }
  52249. this._depthOfFieldEnabled = enabled;
  52250. this._buildPipeline();
  52251. },
  52252. enumerable: true,
  52253. configurable: true
  52254. });
  52255. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  52256. get: function () {
  52257. return this._lensFlareEnabled;
  52258. },
  52259. set: function (enabled) {
  52260. if (this._lensFlareEnabled === enabled) {
  52261. return;
  52262. }
  52263. this._lensFlareEnabled = enabled;
  52264. this._buildPipeline();
  52265. },
  52266. enumerable: true,
  52267. configurable: true
  52268. });
  52269. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  52270. get: function () {
  52271. return this._hdrEnabled;
  52272. },
  52273. set: function (enabled) {
  52274. if (this._hdrEnabled === enabled) {
  52275. return;
  52276. }
  52277. this._hdrEnabled = enabled;
  52278. this._buildPipeline();
  52279. },
  52280. enumerable: true,
  52281. configurable: true
  52282. });
  52283. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  52284. get: function () {
  52285. return this._vlsEnabled;
  52286. },
  52287. set: function (enabled) {
  52288. if (this._vlsEnabled === enabled) {
  52289. return;
  52290. }
  52291. if (enabled) {
  52292. var geometry = this._scene.enableGeometryBufferRenderer();
  52293. if (!geometry) {
  52294. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  52295. return;
  52296. }
  52297. }
  52298. this._vlsEnabled = enabled;
  52299. this._buildPipeline();
  52300. },
  52301. enumerable: true,
  52302. configurable: true
  52303. });
  52304. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  52305. get: function () {
  52306. return this._motionBlurEnabled;
  52307. },
  52308. set: function (enabled) {
  52309. if (this._motionBlurEnabled === enabled) {
  52310. return;
  52311. }
  52312. this._motionBlurEnabled = enabled;
  52313. this._buildPipeline();
  52314. },
  52315. enumerable: true,
  52316. configurable: true
  52317. });
  52318. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  52319. get: function () {
  52320. return this._volumetricLightStepsCount;
  52321. },
  52322. set: function (count) {
  52323. if (this.volumetricLightPostProcess) {
  52324. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  52325. }
  52326. this._volumetricLightStepsCount = count;
  52327. },
  52328. enumerable: true,
  52329. configurable: true
  52330. });
  52331. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  52332. get: function () {
  52333. return this._motionBlurSamples;
  52334. },
  52335. set: function (samples) {
  52336. if (this.motionBlurPostProcess) {
  52337. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  52338. }
  52339. this._motionBlurSamples = samples;
  52340. },
  52341. enumerable: true,
  52342. configurable: true
  52343. });
  52344. StandardRenderingPipeline.prototype._buildPipeline = function () {
  52345. var _this = this;
  52346. var ratio = this._ratio;
  52347. var scene = this._scene;
  52348. this._disposePostProcesses();
  52349. this._reset();
  52350. // Create pass post-process
  52351. if (!this._basePostProcess) {
  52352. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  52353. this.originalPostProcess.onApply = function (effect) {
  52354. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  52355. };
  52356. }
  52357. else {
  52358. this.originalPostProcess = this._basePostProcess;
  52359. }
  52360. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  52361. this._currentDepthOfFieldSource = this.originalPostProcess;
  52362. if (this._vlsEnabled) {
  52363. // Create volumetric light
  52364. this._createVolumetricLightPostProcess(scene, ratio);
  52365. // Create volumetric light final post-process
  52366. 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);
  52367. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  52368. }
  52369. if (this._bloomEnabled) {
  52370. // Create down sample X4 post-process
  52371. this._createDownSampleX4PostProcess(scene, ratio / 2);
  52372. // Create bright pass post-process
  52373. this._createBrightPassPostProcess(scene, ratio / 2);
  52374. // Create gaussian blur post-processes (down sampling blurs)
  52375. this._createBlurPostProcesses(scene, ratio / 4, 1);
  52376. // Create texture adder post-process
  52377. this._createTextureAdderPostProcess(scene, ratio);
  52378. // Create depth-of-field source post-process
  52379. 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);
  52380. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  52381. }
  52382. if (this._lensFlareEnabled) {
  52383. // Create lens flare post-process
  52384. this._createLensFlarePostProcess(scene, ratio);
  52385. // Create depth-of-field source post-process post lens-flare and disable it now
  52386. 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);
  52387. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  52388. }
  52389. if (this._hdrEnabled) {
  52390. // Create luminance
  52391. this._createLuminancePostProcesses(scene, this._floatTextureType);
  52392. // Create HDR
  52393. this._createHdrPostProcess(scene, ratio);
  52394. // Create depth-of-field source post-process post hdr and disable it now
  52395. 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);
  52396. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  52397. }
  52398. if (this._depthOfFieldEnabled) {
  52399. // Create gaussian blur used by depth-of-field
  52400. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  52401. // Create depth-of-field post-process
  52402. this._createDepthOfFieldPostProcess(scene, ratio);
  52403. }
  52404. if (this._motionBlurEnabled) {
  52405. // Create motion blur post-process
  52406. this._createMotionBlurPostProcess(scene, ratio);
  52407. }
  52408. if (this._cameras !== null) {
  52409. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  52410. }
  52411. };
  52412. // Down Sample X4 Post-Processs
  52413. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  52414. var _this = this;
  52415. var downSampleX4Offsets = new Array(32);
  52416. 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);
  52417. this.downSampleX4PostProcess.onApply = function (effect) {
  52418. var id = 0;
  52419. for (var i = -2; i < 2; i++) {
  52420. for (var j = -2; j < 2; j++) {
  52421. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  52422. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  52423. id += 2;
  52424. }
  52425. }
  52426. effect.setArray2("dsOffsets", downSampleX4Offsets);
  52427. };
  52428. // Add to pipeline
  52429. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  52430. };
  52431. // Brightpass Post-Process
  52432. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  52433. var _this = this;
  52434. var brightOffsets = new Array(8);
  52435. 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);
  52436. this.brightPassPostProcess.onApply = function (effect) {
  52437. var sU = (1.0 / _this.brightPassPostProcess.width);
  52438. var sV = (1.0 / _this.brightPassPostProcess.height);
  52439. brightOffsets[0] = -0.5 * sU;
  52440. brightOffsets[1] = 0.5 * sV;
  52441. brightOffsets[2] = 0.5 * sU;
  52442. brightOffsets[3] = 0.5 * sV;
  52443. brightOffsets[4] = -0.5 * sU;
  52444. brightOffsets[5] = -0.5 * sV;
  52445. brightOffsets[6] = 0.5 * sU;
  52446. brightOffsets[7] = -0.5 * sV;
  52447. effect.setArray2("dsOffsets", brightOffsets);
  52448. effect.setFloat("brightThreshold", _this.brightThreshold);
  52449. };
  52450. // Add to pipeline
  52451. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  52452. };
  52453. // Create blur H&V post-processes
  52454. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  52455. var _this = this;
  52456. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  52457. var engine = scene.getEngine();
  52458. 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);
  52459. 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);
  52460. blurX.onActivateObservable.add(function () {
  52461. var dw = blurX.width / engine.getRenderingCanvas().width;
  52462. blurX.kernel = _this[blurWidthKey] * dw;
  52463. });
  52464. blurY.onActivateObservable.add(function () {
  52465. var dw = blurY.height / engine.getRenderingCanvas().height;
  52466. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  52467. });
  52468. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  52469. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  52470. this.blurHPostProcesses.push(blurX);
  52471. this.blurVPostProcesses.push(blurY);
  52472. };
  52473. // Create texture adder post-process
  52474. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  52475. var _this = this;
  52476. 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);
  52477. this.textureAdderPostProcess.onApply = function (effect) {
  52478. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  52479. effect.setTexture("lensSampler", _this.lensTexture);
  52480. effect.setFloat("exposure", _this.exposure);
  52481. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  52482. };
  52483. // Add to pipeline
  52484. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  52485. };
  52486. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  52487. var _this = this;
  52488. var geometryRenderer = scene.enableGeometryBufferRenderer();
  52489. geometryRenderer.enablePosition = true;
  52490. var geometry = geometryRenderer.getGBuffer();
  52491. // Base post-process
  52492. 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));
  52493. var depthValues = BABYLON.Vector2.Zero();
  52494. this.volumetricLightPostProcess.onApply = function (effect) {
  52495. if (_this.sourceLight && _this.sourceLight.getShadowGenerator()) {
  52496. var generator = _this.sourceLight.getShadowGenerator();
  52497. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  52498. effect.setTexture("positionSampler", geometry.textures[2]);
  52499. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  52500. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  52501. effect.setVector3("cameraPosition", scene.activeCamera.globalPosition);
  52502. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  52503. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  52504. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  52505. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  52506. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  52507. effect.setVector2("depthValues", depthValues);
  52508. }
  52509. };
  52510. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  52511. // Smooth
  52512. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  52513. // Merge
  52514. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  52515. this.volumetricLightMergePostProces.onApply = function (effect) {
  52516. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  52517. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  52518. };
  52519. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  52520. };
  52521. // Create luminance
  52522. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  52523. var _this = this;
  52524. // Create luminance
  52525. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  52526. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  52527. var offsets = [];
  52528. this.luminancePostProcess.onApply = function (effect) {
  52529. var sU = (1.0 / _this.luminancePostProcess.width);
  52530. var sV = (1.0 / _this.luminancePostProcess.height);
  52531. offsets[0] = -0.5 * sU;
  52532. offsets[1] = 0.5 * sV;
  52533. offsets[2] = 0.5 * sU;
  52534. offsets[3] = 0.5 * sV;
  52535. offsets[4] = -0.5 * sU;
  52536. offsets[5] = -0.5 * sV;
  52537. offsets[6] = 0.5 * sU;
  52538. offsets[7] = -0.5 * sV;
  52539. effect.setArray2("lumOffsets", offsets);
  52540. };
  52541. // Add to pipeline
  52542. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  52543. // Create down sample luminance
  52544. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  52545. var size = Math.pow(3, i);
  52546. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  52547. if (i === 0) {
  52548. defines += "#define FINAL_DOWN_SAMPLER";
  52549. }
  52550. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  52551. this.luminanceDownSamplePostProcesses.push(postProcess);
  52552. }
  52553. // Create callbacks and add effects
  52554. var lastLuminance = this.luminancePostProcess;
  52555. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  52556. var downSampleOffsets = new Array(18);
  52557. pp.onApply = function (effect) {
  52558. var id = 0;
  52559. for (var x = -1; x < 2; x++) {
  52560. for (var y = -1; y < 2; y++) {
  52561. downSampleOffsets[id] = x / lastLuminance.width;
  52562. downSampleOffsets[id + 1] = y / lastLuminance.height;
  52563. id += 2;
  52564. }
  52565. }
  52566. effect.setArray2("dsOffsets", downSampleOffsets);
  52567. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  52568. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  52569. lastLuminance = _this.luminancePostProcess;
  52570. }
  52571. else {
  52572. lastLuminance = pp;
  52573. }
  52574. };
  52575. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  52576. pp.onAfterRender = function (effect) {
  52577. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  52578. 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);
  52579. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  52580. };
  52581. }
  52582. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  52583. });
  52584. };
  52585. // Create HDR post-process
  52586. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  52587. var _this = this;
  52588. 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);
  52589. var outputLiminance = 1;
  52590. var time = 0;
  52591. var lastTime = 0;
  52592. this.hdrPostProcess.onApply = function (effect) {
  52593. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  52594. time += scene.getEngine().getDeltaTime();
  52595. if (outputLiminance < 0) {
  52596. outputLiminance = _this._hdrCurrentLuminance;
  52597. }
  52598. else {
  52599. var dt = (lastTime - time) / 1000.0;
  52600. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  52601. outputLiminance += _this.hdrDecreaseRate * dt;
  52602. }
  52603. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  52604. outputLiminance -= _this.hdrIncreaseRate * dt;
  52605. }
  52606. else {
  52607. outputLiminance = _this._hdrCurrentLuminance;
  52608. }
  52609. }
  52610. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  52611. effect.setFloat("averageLuminance", outputLiminance);
  52612. lastTime = time;
  52613. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  52614. };
  52615. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  52616. };
  52617. // Create lens flare post-process
  52618. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  52619. var _this = this;
  52620. 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);
  52621. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  52622. this._createBlurPostProcesses(scene, ratio / 4, 2);
  52623. 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);
  52624. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  52625. var resolution = new BABYLON.Vector2(0, 0);
  52626. // Lens flare
  52627. this.lensFlarePostProcess.onApply = function (effect) {
  52628. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  52629. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  52630. effect.setFloat("strength", _this.lensFlareStrength);
  52631. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  52632. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  52633. // Shift
  52634. resolution.x = _this.lensFlarePostProcess.width;
  52635. resolution.y = _this.lensFlarePostProcess.height;
  52636. effect.setVector2("resolution", resolution);
  52637. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  52638. };
  52639. // Compose
  52640. 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);
  52641. 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);
  52642. this.lensFlareComposePostProcess.onApply = function (effect) {
  52643. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  52644. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  52645. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  52646. // Lens start rotation matrix
  52647. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  52648. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  52649. 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));
  52650. camRot *= 4.0;
  52651. 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);
  52652. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  52653. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  52654. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  52655. };
  52656. };
  52657. // Create depth-of-field post-process
  52658. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  52659. var _this = this;
  52660. 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);
  52661. this.depthOfFieldPostProcess.onApply = function (effect) {
  52662. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  52663. effect.setTexture("depthSampler", _this._getDepthTexture());
  52664. effect.setFloat("distance", _this.depthOfFieldDistance);
  52665. };
  52666. // Add to pipeline
  52667. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  52668. };
  52669. // Create motion blur post-process
  52670. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  52671. var _this = this;
  52672. 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);
  52673. var motionScale = 0;
  52674. var prevViewProjection = BABYLON.Matrix.Identity();
  52675. var invViewProjection = BABYLON.Matrix.Identity();
  52676. var viewProjection = BABYLON.Matrix.Identity();
  52677. var screenSize = BABYLON.Vector2.Zero();
  52678. this.motionBlurPostProcess.onApply = function (effect) {
  52679. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  52680. viewProjection.invertToRef(invViewProjection);
  52681. effect.setMatrix("inverseViewProjection", invViewProjection);
  52682. effect.setMatrix("prevViewProjection", prevViewProjection);
  52683. prevViewProjection = viewProjection;
  52684. screenSize.x = _this.motionBlurPostProcess.width;
  52685. screenSize.y = _this.motionBlurPostProcess.height;
  52686. effect.setVector2("screenSize", screenSize);
  52687. motionScale = scene.getEngine().getFps() / 60.0;
  52688. effect.setFloat("motionScale", motionScale);
  52689. effect.setFloat("motionStrength", _this.motionStrength);
  52690. effect.setTexture("depthSampler", _this._getDepthTexture());
  52691. };
  52692. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  52693. };
  52694. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  52695. var geometry = this._scene.enableGeometryBufferRenderer();
  52696. if (geometry) {
  52697. return geometry.getGBuffer().textures[0];
  52698. }
  52699. return this._scene.enableDepthRenderer().getDepthMap();
  52700. };
  52701. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  52702. for (var i = 0; i < this._cameras.length; i++) {
  52703. var camera = this._cameras[i];
  52704. if (this.originalPostProcess) {
  52705. this.originalPostProcess.dispose(camera);
  52706. }
  52707. if (this.downSampleX4PostProcess) {
  52708. this.downSampleX4PostProcess.dispose(camera);
  52709. }
  52710. if (this.brightPassPostProcess) {
  52711. this.brightPassPostProcess.dispose(camera);
  52712. }
  52713. if (this.textureAdderPostProcess) {
  52714. this.textureAdderPostProcess.dispose(camera);
  52715. }
  52716. if (this.textureAdderFinalPostProcess) {
  52717. this.textureAdderFinalPostProcess.dispose(camera);
  52718. }
  52719. if (this.volumetricLightPostProcess) {
  52720. this.volumetricLightPostProcess.dispose(camera);
  52721. }
  52722. if (this.volumetricLightSmoothXPostProcess) {
  52723. this.volumetricLightSmoothXPostProcess.dispose(camera);
  52724. }
  52725. if (this.volumetricLightSmoothYPostProcess) {
  52726. this.volumetricLightSmoothYPostProcess.dispose(camera);
  52727. }
  52728. if (this.volumetricLightMergePostProces) {
  52729. this.volumetricLightMergePostProces.dispose(camera);
  52730. }
  52731. if (this.volumetricLightFinalPostProcess) {
  52732. this.volumetricLightFinalPostProcess.dispose(camera);
  52733. }
  52734. if (this.lensFlarePostProcess) {
  52735. this.lensFlarePostProcess.dispose(camera);
  52736. }
  52737. if (this.lensFlareComposePostProcess) {
  52738. this.lensFlareComposePostProcess.dispose(camera);
  52739. }
  52740. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  52741. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  52742. }
  52743. if (this.luminancePostProcess) {
  52744. this.luminancePostProcess.dispose(camera);
  52745. }
  52746. if (this.hdrPostProcess) {
  52747. this.hdrPostProcess.dispose(camera);
  52748. }
  52749. if (this.hdrFinalPostProcess) {
  52750. this.hdrFinalPostProcess.dispose(camera);
  52751. }
  52752. if (this.depthOfFieldPostProcess) {
  52753. this.depthOfFieldPostProcess.dispose(camera);
  52754. }
  52755. if (this.motionBlurPostProcess) {
  52756. this.motionBlurPostProcess.dispose(camera);
  52757. }
  52758. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  52759. this.blurHPostProcesses[j].dispose(camera);
  52760. }
  52761. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  52762. this.blurVPostProcesses[j].dispose(camera);
  52763. }
  52764. }
  52765. this.originalPostProcess = null;
  52766. this.downSampleX4PostProcess = null;
  52767. this.brightPassPostProcess = null;
  52768. this.textureAdderPostProcess = null;
  52769. this.textureAdderFinalPostProcess = null;
  52770. this.volumetricLightPostProcess = null;
  52771. this.volumetricLightSmoothXPostProcess = null;
  52772. this.volumetricLightSmoothYPostProcess = null;
  52773. this.volumetricLightMergePostProces = null;
  52774. this.volumetricLightFinalPostProcess = null;
  52775. this.lensFlarePostProcess = null;
  52776. this.lensFlareComposePostProcess = null;
  52777. this.luminancePostProcess = null;
  52778. this.hdrPostProcess = null;
  52779. this.hdrFinalPostProcess = null;
  52780. this.depthOfFieldPostProcess = null;
  52781. this.motionBlurPostProcess = null;
  52782. this.luminanceDownSamplePostProcesses = [];
  52783. this.blurHPostProcesses = [];
  52784. this.blurVPostProcesses = [];
  52785. };
  52786. // Dispose
  52787. StandardRenderingPipeline.prototype.dispose = function () {
  52788. this._disposePostProcesses();
  52789. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  52790. _super.prototype.dispose.call(this);
  52791. };
  52792. // Serialize rendering pipeline
  52793. StandardRenderingPipeline.prototype.serialize = function () {
  52794. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  52795. serializationObject.customType = "StandardRenderingPipeline";
  52796. return serializationObject;
  52797. };
  52798. /**
  52799. * Static members
  52800. */
  52801. // Parse serialized pipeline
  52802. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  52803. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  52804. };
  52805. return StandardRenderingPipeline;
  52806. }(BABYLON.PostProcessRenderPipeline));
  52807. // Luminance steps
  52808. StandardRenderingPipeline.LuminanceSteps = 6;
  52809. __decorate([
  52810. BABYLON.serialize()
  52811. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  52812. __decorate([
  52813. BABYLON.serialize()
  52814. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  52815. __decorate([
  52816. BABYLON.serialize()
  52817. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  52818. __decorate([
  52819. BABYLON.serialize()
  52820. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  52821. __decorate([
  52822. BABYLON.serializeAsTexture("lensTexture")
  52823. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  52824. __decorate([
  52825. BABYLON.serialize()
  52826. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  52827. __decorate([
  52828. BABYLON.serialize()
  52829. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  52830. __decorate([
  52831. BABYLON.serialize()
  52832. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  52833. __decorate([
  52834. BABYLON.serialize()
  52835. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  52836. __decorate([
  52837. BABYLON.serialize()
  52838. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  52839. __decorate([
  52840. BABYLON.serialize()
  52841. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  52842. __decorate([
  52843. BABYLON.serializeAsTexture("lensColorTexture")
  52844. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  52845. __decorate([
  52846. BABYLON.serialize()
  52847. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  52848. __decorate([
  52849. BABYLON.serialize()
  52850. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  52851. __decorate([
  52852. BABYLON.serialize()
  52853. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  52854. __decorate([
  52855. BABYLON.serialize()
  52856. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  52857. __decorate([
  52858. BABYLON.serializeAsTexture("lensStarTexture")
  52859. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  52860. __decorate([
  52861. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  52862. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  52863. __decorate([
  52864. BABYLON.serialize()
  52865. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  52866. __decorate([
  52867. BABYLON.serialize()
  52868. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  52869. __decorate([
  52870. BABYLON.serialize()
  52871. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  52872. __decorate([
  52873. BABYLON.serialize()
  52874. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  52875. __decorate([
  52876. BABYLON.serialize()
  52877. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  52878. __decorate([
  52879. BABYLON.serialize()
  52880. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  52881. __decorate([
  52882. BABYLON.serialize()
  52883. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  52884. __decorate([
  52885. BABYLON.serialize()
  52886. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  52887. __decorate([
  52888. BABYLON.serialize()
  52889. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  52890. __decorate([
  52891. BABYLON.serialize()
  52892. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  52893. __decorate([
  52894. BABYLON.serialize()
  52895. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  52896. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  52897. })(BABYLON || (BABYLON = {}));
  52898. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  52899. var BABYLON;
  52900. (function (BABYLON) {
  52901. var FxaaPostProcess = (function (_super) {
  52902. __extends(FxaaPostProcess, _super);
  52903. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  52904. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52905. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  52906. _this.onApplyObservable.add(function (effect) {
  52907. var texelSize = _this.texelSize;
  52908. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  52909. });
  52910. return _this;
  52911. }
  52912. return FxaaPostProcess;
  52913. }(BABYLON.PostProcess));
  52914. BABYLON.FxaaPostProcess = FxaaPostProcess;
  52915. })(BABYLON || (BABYLON = {}));
  52916. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  52917. var BABYLON;
  52918. (function (BABYLON) {
  52919. var DefaultRenderingPipeline = (function (_super) {
  52920. __extends(DefaultRenderingPipeline, _super);
  52921. /**
  52922. * @constructor
  52923. * @param {string} name - The rendering pipeline name
  52924. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  52925. * @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)
  52926. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  52927. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  52928. */
  52929. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  52930. if (automaticBuild === void 0) { automaticBuild = true; }
  52931. var _this = _super.call(this, scene.getEngine(), name) || this;
  52932. _this.PassPostProcessId = "PassPostProcessEffect";
  52933. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  52934. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  52935. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  52936. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  52937. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  52938. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  52939. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  52940. // IAnimatable
  52941. _this.animations = [];
  52942. // Values
  52943. _this._bloomEnabled = false;
  52944. _this._fxaaEnabled = false;
  52945. _this._imageProcessingEnabled = true;
  52946. _this._bloomScale = 0.6;
  52947. _this._buildAllowed = true;
  52948. /**
  52949. * Specifies the size of the bloom blur kernel, relative to the final output size
  52950. */
  52951. _this.bloomKernel = 64;
  52952. /**
  52953. * Specifies the weight of the bloom in the final rendering
  52954. */
  52955. _this._bloomWeight = 0.15;
  52956. _this._cameras = cameras || [];
  52957. _this._buildAllowed = automaticBuild;
  52958. // Initialize
  52959. _this._scene = scene;
  52960. var caps = _this._scene.getEngine().getCaps();
  52961. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  52962. // Misc
  52963. if (_this._hdr) {
  52964. if (caps.textureHalfFloatRender) {
  52965. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  52966. }
  52967. else if (caps.textureFloatRender) {
  52968. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  52969. }
  52970. }
  52971. else {
  52972. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  52973. }
  52974. // Attach
  52975. scene.postProcessRenderPipelineManager.addPipeline(_this);
  52976. _this._buildPipeline();
  52977. return _this;
  52978. }
  52979. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  52980. get: function () {
  52981. return this._bloomWeight;
  52982. },
  52983. set: function (value) {
  52984. if (this._bloomWeight === value) {
  52985. return;
  52986. }
  52987. this._bloomWeight = value;
  52988. if (this._hdr && this.copyBack) {
  52989. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  52990. }
  52991. },
  52992. enumerable: true,
  52993. configurable: true
  52994. });
  52995. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  52996. get: function () {
  52997. return this._bloomScale;
  52998. },
  52999. set: function (value) {
  53000. if (this._bloomScale === value) {
  53001. return;
  53002. }
  53003. this._bloomScale = value;
  53004. this._buildPipeline();
  53005. },
  53006. enumerable: true,
  53007. configurable: true
  53008. });
  53009. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  53010. get: function () {
  53011. return this._bloomEnabled;
  53012. },
  53013. set: function (enabled) {
  53014. if (this._bloomEnabled === enabled) {
  53015. return;
  53016. }
  53017. this._bloomEnabled = enabled;
  53018. this._buildPipeline();
  53019. },
  53020. enumerable: true,
  53021. configurable: true
  53022. });
  53023. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  53024. get: function () {
  53025. return this._fxaaEnabled;
  53026. },
  53027. set: function (enabled) {
  53028. if (this._fxaaEnabled === enabled) {
  53029. return;
  53030. }
  53031. this._fxaaEnabled = enabled;
  53032. this._buildPipeline();
  53033. },
  53034. enumerable: true,
  53035. configurable: true
  53036. });
  53037. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  53038. get: function () {
  53039. return this._imageProcessingEnabled;
  53040. },
  53041. set: function (enabled) {
  53042. if (this._imageProcessingEnabled === enabled) {
  53043. return;
  53044. }
  53045. this._imageProcessingEnabled = enabled;
  53046. this._buildPipeline();
  53047. },
  53048. enumerable: true,
  53049. configurable: true
  53050. });
  53051. /**
  53052. * Force the compilation of the entire pipeline.
  53053. */
  53054. DefaultRenderingPipeline.prototype.prepare = function () {
  53055. var previousState = this._buildAllowed;
  53056. this._buildAllowed = true;
  53057. this._buildPipeline();
  53058. this._buildAllowed = previousState;
  53059. };
  53060. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  53061. var _this = this;
  53062. if (!this._buildAllowed) {
  53063. return;
  53064. }
  53065. var engine = this._scene.getEngine();
  53066. this._disposePostProcesses();
  53067. this._reset();
  53068. if (this.bloomEnabled) {
  53069. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  53070. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  53071. if (!this._hdr) {
  53072. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  53073. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  53074. this.highlights.autoClear = false;
  53075. this.highlights.alwaysForcePOT = true;
  53076. }
  53077. 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);
  53078. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  53079. this.blurX.alwaysForcePOT = true;
  53080. this.blurX.autoClear = false;
  53081. this.blurX.onActivateObservable.add(function () {
  53082. var dw = _this.blurX.width / engine.getRenderingCanvas().width;
  53083. _this.blurX.kernel = _this.bloomKernel * dw;
  53084. });
  53085. 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);
  53086. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  53087. this.blurY.alwaysForcePOT = true;
  53088. this.blurY.autoClear = false;
  53089. this.blurY.onActivateObservable.add(function () {
  53090. var dh = _this.blurY.height / engine.getRenderingCanvas().height;
  53091. _this.blurY.kernel = _this.bloomKernel * dh;
  53092. });
  53093. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  53094. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  53095. this.copyBack.alwaysForcePOT = true;
  53096. if (this._hdr) {
  53097. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  53098. var w = this.bloomWeight;
  53099. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  53100. }
  53101. else {
  53102. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  53103. }
  53104. this.copyBack.autoClear = false;
  53105. }
  53106. if (this._imageProcessingEnabled) {
  53107. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  53108. if (this._hdr) {
  53109. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  53110. }
  53111. }
  53112. if (this.fxaaEnabled) {
  53113. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  53114. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  53115. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  53116. }
  53117. else {
  53118. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  53119. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  53120. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  53121. }
  53122. if (this.bloomEnabled) {
  53123. if (this._hdr) {
  53124. this.copyBack.shareOutputWith(this.blurX);
  53125. if (this.imageProcessing) {
  53126. this.imageProcessing.shareOutputWith(this.pass);
  53127. this.imageProcessing.autoClear = false;
  53128. }
  53129. else if (this.fxaa) {
  53130. this.fxaa.shareOutputWith(this.pass);
  53131. }
  53132. else {
  53133. this.finalMerge.shareOutputWith(this.pass);
  53134. }
  53135. }
  53136. else {
  53137. if (this.fxaa) {
  53138. this.fxaa.shareOutputWith(this.pass);
  53139. }
  53140. else {
  53141. this.finalMerge.shareOutputWith(this.pass);
  53142. }
  53143. }
  53144. }
  53145. if (this._cameras !== null) {
  53146. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  53147. }
  53148. };
  53149. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  53150. for (var i = 0; i < this._cameras.length; i++) {
  53151. var camera = this._cameras[i];
  53152. if (this.pass) {
  53153. this.pass.dispose(camera);
  53154. }
  53155. if (this.highlights) {
  53156. this.highlights.dispose(camera);
  53157. }
  53158. if (this.blurX) {
  53159. this.blurX.dispose(camera);
  53160. }
  53161. if (this.blurY) {
  53162. this.blurY.dispose(camera);
  53163. }
  53164. if (this.copyBack) {
  53165. this.copyBack.dispose(camera);
  53166. }
  53167. if (this.imageProcessing) {
  53168. this.imageProcessing.dispose(camera);
  53169. }
  53170. if (this.fxaa) {
  53171. this.fxaa.dispose(camera);
  53172. }
  53173. if (this.finalMerge) {
  53174. this.finalMerge.dispose(camera);
  53175. }
  53176. }
  53177. this.pass = null;
  53178. this.highlights = null;
  53179. this.blurX = null;
  53180. this.blurY = null;
  53181. this.copyBack = null;
  53182. this.imageProcessing = null;
  53183. this.fxaa = null;
  53184. this.finalMerge = null;
  53185. };
  53186. // Dispose
  53187. DefaultRenderingPipeline.prototype.dispose = function () {
  53188. this._disposePostProcesses();
  53189. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  53190. _super.prototype.dispose.call(this);
  53191. };
  53192. // Serialize rendering pipeline
  53193. DefaultRenderingPipeline.prototype.serialize = function () {
  53194. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  53195. serializationObject.customType = "DefaultRenderingPipeline";
  53196. return serializationObject;
  53197. };
  53198. // Parse serialized pipeline
  53199. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  53200. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  53201. };
  53202. return DefaultRenderingPipeline;
  53203. }(BABYLON.PostProcessRenderPipeline));
  53204. __decorate([
  53205. BABYLON.serialize()
  53206. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  53207. __decorate([
  53208. BABYLON.serialize()
  53209. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  53210. __decorate([
  53211. BABYLON.serialize()
  53212. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  53213. __decorate([
  53214. BABYLON.serialize()
  53215. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  53216. __decorate([
  53217. BABYLON.serialize()
  53218. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  53219. __decorate([
  53220. BABYLON.serialize()
  53221. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  53222. __decorate([
  53223. BABYLON.serialize()
  53224. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  53225. __decorate([
  53226. BABYLON.serialize()
  53227. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  53228. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  53229. })(BABYLON || (BABYLON = {}));
  53230. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  53231. var BABYLON;
  53232. (function (BABYLON) {
  53233. var GeometryBufferRenderer = (function () {
  53234. function GeometryBufferRenderer(scene, ratio) {
  53235. if (ratio === void 0) { ratio = 1; }
  53236. this._viewMatrix = BABYLON.Matrix.Zero();
  53237. this._projectionMatrix = BABYLON.Matrix.Zero();
  53238. this._transformMatrix = BABYLON.Matrix.Zero();
  53239. this._worldViewProjection = BABYLON.Matrix.Zero();
  53240. this._enablePosition = false;
  53241. this._scene = scene;
  53242. this._ratio = ratio;
  53243. // Render target
  53244. this._createRenderTargets();
  53245. }
  53246. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  53247. set: function (meshes) {
  53248. this._multiRenderTarget.renderList = meshes;
  53249. },
  53250. enumerable: true,
  53251. configurable: true
  53252. });
  53253. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  53254. get: function () {
  53255. return this._multiRenderTarget.isSupported;
  53256. },
  53257. enumerable: true,
  53258. configurable: true
  53259. });
  53260. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  53261. get: function () {
  53262. return this._enablePosition;
  53263. },
  53264. set: function (enable) {
  53265. this._enablePosition = enable;
  53266. this.dispose();
  53267. this._createRenderTargets();
  53268. },
  53269. enumerable: true,
  53270. configurable: true
  53271. });
  53272. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  53273. var material = subMesh.getMaterial();
  53274. if (material && material.disableDepthWrite) {
  53275. return false;
  53276. }
  53277. var defines = [];
  53278. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  53279. var mesh = subMesh.getMesh();
  53280. var scene = mesh.getScene();
  53281. // Alpha test
  53282. if (material && material.needAlphaTesting()) {
  53283. defines.push("#define ALPHATEST");
  53284. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53285. attribs.push(BABYLON.VertexBuffer.UVKind);
  53286. defines.push("#define UV1");
  53287. }
  53288. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53289. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53290. defines.push("#define UV2");
  53291. }
  53292. }
  53293. // Buffers
  53294. if (this._enablePosition) {
  53295. defines.push("#define POSITION");
  53296. }
  53297. // Bones
  53298. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53299. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53300. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53301. if (mesh.numBoneInfluencers > 4) {
  53302. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  53303. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  53304. }
  53305. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53306. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53307. }
  53308. else {
  53309. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53310. }
  53311. // Instances
  53312. if (useInstances) {
  53313. defines.push("#define INSTANCES");
  53314. attribs.push("world0");
  53315. attribs.push("world1");
  53316. attribs.push("world2");
  53317. attribs.push("world3");
  53318. }
  53319. // Get correct effect
  53320. var join = defines.join("\n");
  53321. if (this._cachedDefines !== join) {
  53322. this._cachedDefines = join;
  53323. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join);
  53324. }
  53325. return this._effect.isReady();
  53326. };
  53327. GeometryBufferRenderer.prototype.getGBuffer = function () {
  53328. return this._multiRenderTarget;
  53329. };
  53330. // Methods
  53331. GeometryBufferRenderer.prototype.dispose = function () {
  53332. this.getGBuffer().dispose();
  53333. };
  53334. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  53335. var _this = this;
  53336. var engine = this._scene.getEngine();
  53337. var count = this._enablePosition ? 3 : 2;
  53338. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  53339. if (!this.isSupported) {
  53340. return null;
  53341. }
  53342. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53343. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53344. this._multiRenderTarget.refreshRate = 1;
  53345. this._multiRenderTarget.renderParticles = false;
  53346. this._multiRenderTarget.renderList = null;
  53347. // set default depth value to 1.0 (far away)
  53348. this._multiRenderTarget.onClearObservable.add(function (engine) {
  53349. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  53350. });
  53351. // Custom render function
  53352. var renderSubMesh = function (subMesh) {
  53353. var mesh = subMesh.getRenderingMesh();
  53354. var scene = _this._scene;
  53355. var engine = scene.getEngine();
  53356. // Culling
  53357. engine.setState(subMesh.getMaterial().backFaceCulling);
  53358. // Managing instances
  53359. var batch = mesh._getInstancesRenderList(subMesh._id);
  53360. if (batch.mustReturn) {
  53361. return;
  53362. }
  53363. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  53364. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  53365. engine.enableEffect(_this._effect);
  53366. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  53367. var material = subMesh.getMaterial();
  53368. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  53369. _this._effect.setMatrix("view", scene.getViewMatrix());
  53370. // Alpha test
  53371. if (material && material.needAlphaTesting()) {
  53372. var alphaTexture = material.getAlphaTestTexture();
  53373. _this._effect.setTexture("diffuseSampler", alphaTexture);
  53374. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  53375. }
  53376. // Bones
  53377. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53378. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  53379. }
  53380. // Draw
  53381. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  53382. }
  53383. };
  53384. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  53385. var index;
  53386. for (index = 0; index < opaqueSubMeshes.length; index++) {
  53387. renderSubMesh(opaqueSubMeshes.data[index]);
  53388. }
  53389. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  53390. renderSubMesh(alphaTestSubMeshes.data[index]);
  53391. }
  53392. };
  53393. };
  53394. return GeometryBufferRenderer;
  53395. }());
  53396. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  53397. })(BABYLON || (BABYLON = {}));
  53398. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  53399. var BABYLON;
  53400. (function (BABYLON) {
  53401. var RefractionPostProcess = (function (_super) {
  53402. __extends(RefractionPostProcess, _super);
  53403. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  53404. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  53405. _this.color = color;
  53406. _this.depth = depth;
  53407. _this.colorLevel = colorLevel;
  53408. _this.onActivateObservable.add(function (cam) {
  53409. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  53410. });
  53411. _this.onApplyObservable.add(function (effect) {
  53412. effect.setColor3("baseColor", _this.color);
  53413. effect.setFloat("depth", _this.depth);
  53414. effect.setFloat("colorLevel", _this.colorLevel);
  53415. effect.setTexture("refractionSampler", _this._refRexture);
  53416. });
  53417. return _this;
  53418. }
  53419. // Methods
  53420. RefractionPostProcess.prototype.dispose = function (camera) {
  53421. if (this._refRexture) {
  53422. this._refRexture.dispose();
  53423. }
  53424. _super.prototype.dispose.call(this, camera);
  53425. };
  53426. return RefractionPostProcess;
  53427. }(BABYLON.PostProcess));
  53428. BABYLON.RefractionPostProcess = RefractionPostProcess;
  53429. })(BABYLON || (BABYLON = {}));
  53430. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  53431. var BABYLON;
  53432. (function (BABYLON) {
  53433. var BlackAndWhitePostProcess = (function (_super) {
  53434. __extends(BlackAndWhitePostProcess, _super);
  53435. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  53436. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  53437. _this.degree = 1;
  53438. _this.onApplyObservable.add(function (effect) {
  53439. effect.setFloat("degree", _this.degree);
  53440. });
  53441. return _this;
  53442. }
  53443. return BlackAndWhitePostProcess;
  53444. }(BABYLON.PostProcess));
  53445. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  53446. })(BABYLON || (BABYLON = {}));
  53447. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  53448. var BABYLON;
  53449. (function (BABYLON) {
  53450. var ConvolutionPostProcess = (function (_super) {
  53451. __extends(ConvolutionPostProcess, _super);
  53452. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  53453. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  53454. _this.kernel = kernel;
  53455. _this.onApply = function (effect) {
  53456. effect.setFloat2("screenSize", _this.width, _this.height);
  53457. effect.setArray("kernel", _this.kernel);
  53458. };
  53459. return _this;
  53460. }
  53461. return ConvolutionPostProcess;
  53462. }(BABYLON.PostProcess));
  53463. // Statics
  53464. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  53465. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  53466. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  53467. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  53468. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  53469. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  53470. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  53471. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  53472. })(BABYLON || (BABYLON = {}));
  53473. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  53474. var BABYLON;
  53475. (function (BABYLON) {
  53476. var FilterPostProcess = (function (_super) {
  53477. __extends(FilterPostProcess, _super);
  53478. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  53479. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  53480. _this.kernelMatrix = kernelMatrix;
  53481. _this.onApply = function (effect) {
  53482. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  53483. };
  53484. return _this;
  53485. }
  53486. return FilterPostProcess;
  53487. }(BABYLON.PostProcess));
  53488. BABYLON.FilterPostProcess = FilterPostProcess;
  53489. })(BABYLON || (BABYLON = {}));
  53490. //# sourceMappingURL=babylon.filterPostProcess.js.map
  53491. var BABYLON;
  53492. (function (BABYLON) {
  53493. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  53494. var VolumetricLightScatteringPostProcess = (function (_super) {
  53495. __extends(VolumetricLightScatteringPostProcess, _super);
  53496. /**
  53497. * @constructor
  53498. * @param {string} name - The post-process name
  53499. * @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)
  53500. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  53501. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  53502. * @param {number} samples - The post-process quality, default 100
  53503. * @param {number} samplingMode - The post-process filtering mode
  53504. * @param {BABYLON.Engine} engine - The babylon engine
  53505. * @param {boolean} reusable - If the post-process is reusable
  53506. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  53507. */
  53508. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  53509. if (samples === void 0) { samples = 100; }
  53510. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  53511. 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;
  53512. _this._screenCoordinates = BABYLON.Vector2.Zero();
  53513. /**
  53514. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  53515. * @type {Vector3}
  53516. */
  53517. _this.customMeshPosition = BABYLON.Vector3.Zero();
  53518. /**
  53519. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  53520. * @type {boolean}
  53521. */
  53522. _this.useCustomMeshPosition = false;
  53523. /**
  53524. * If the post-process should inverse the light scattering direction
  53525. * @type {boolean}
  53526. */
  53527. _this.invert = true;
  53528. /**
  53529. * Array containing the excluded meshes not rendered in the internal pass
  53530. */
  53531. _this.excludedMeshes = new Array();
  53532. /**
  53533. * Controls the overall intensity of the post-process
  53534. * @type {number}
  53535. */
  53536. _this.exposure = 0.3;
  53537. /**
  53538. * Dissipates each sample's contribution in range [0, 1]
  53539. * @type {number}
  53540. */
  53541. _this.decay = 0.96815;
  53542. /**
  53543. * Controls the overall intensity of each sample
  53544. * @type {number}
  53545. */
  53546. _this.weight = 0.58767;
  53547. /**
  53548. * Controls the density of each sample
  53549. * @type {number}
  53550. */
  53551. _this.density = 0.926;
  53552. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  53553. var engine = scene.getEngine();
  53554. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  53555. // Configure mesh
  53556. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  53557. // Configure
  53558. _this._createPass(scene, ratio.passRatio || ratio);
  53559. _this.onActivate = function (camera) {
  53560. if (!_this.isSupported) {
  53561. _this.dispose(camera);
  53562. }
  53563. _this.onActivate = null;
  53564. };
  53565. _this.onApplyObservable.add(function (effect) {
  53566. _this._updateMeshScreenCoordinates(scene);
  53567. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  53568. effect.setFloat("exposure", _this.exposure);
  53569. effect.setFloat("decay", _this.decay);
  53570. effect.setFloat("weight", _this.weight);
  53571. effect.setFloat("density", _this.density);
  53572. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  53573. });
  53574. return _this;
  53575. }
  53576. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  53577. get: function () {
  53578. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  53579. return false;
  53580. },
  53581. set: function (useDiffuseColor) {
  53582. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  53583. },
  53584. enumerable: true,
  53585. configurable: true
  53586. });
  53587. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  53588. return "VolumetricLightScatteringPostProcess";
  53589. };
  53590. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  53591. var mesh = subMesh.getMesh();
  53592. // Render this.mesh as default
  53593. if (mesh === this.mesh) {
  53594. return mesh.material.isReady(mesh);
  53595. }
  53596. var defines = [];
  53597. var attribs = [BABYLON.VertexBuffer.PositionKind];
  53598. var material = subMesh.getMaterial();
  53599. var needUV = false;
  53600. // Alpha test
  53601. if (material) {
  53602. if (material.needAlphaTesting()) {
  53603. defines.push("#define ALPHATEST");
  53604. }
  53605. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53606. attribs.push(BABYLON.VertexBuffer.UVKind);
  53607. defines.push("#define UV1");
  53608. }
  53609. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53610. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53611. defines.push("#define UV2");
  53612. }
  53613. }
  53614. // Bones
  53615. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53616. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53617. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53618. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53619. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53620. }
  53621. else {
  53622. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53623. }
  53624. // Instances
  53625. if (useInstances) {
  53626. defines.push("#define INSTANCES");
  53627. attribs.push("world0");
  53628. attribs.push("world1");
  53629. attribs.push("world2");
  53630. attribs.push("world3");
  53631. }
  53632. // Get correct effect
  53633. var join = defines.join("\n");
  53634. if (this._cachedDefines !== join) {
  53635. this._cachedDefines = join;
  53636. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  53637. }
  53638. return this._volumetricLightScatteringPass.isReady();
  53639. };
  53640. /**
  53641. * Sets the new light position for light scattering effect
  53642. * @param {BABYLON.Vector3} The new custom light position
  53643. */
  53644. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  53645. this.customMeshPosition = position;
  53646. };
  53647. /**
  53648. * Returns the light position for light scattering effect
  53649. * @return {BABYLON.Vector3} The custom light position
  53650. */
  53651. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  53652. return this.customMeshPosition;
  53653. };
  53654. /**
  53655. * Disposes the internal assets and detaches the post-process from the camera
  53656. */
  53657. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  53658. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  53659. if (rttIndex !== -1) {
  53660. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  53661. }
  53662. this._volumetricLightScatteringRTT.dispose();
  53663. _super.prototype.dispose.call(this, camera);
  53664. };
  53665. /**
  53666. * Returns the render target texture used by the post-process
  53667. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  53668. */
  53669. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  53670. return this._volumetricLightScatteringRTT;
  53671. };
  53672. // Private methods
  53673. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  53674. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  53675. return true;
  53676. }
  53677. return false;
  53678. };
  53679. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  53680. var _this = this;
  53681. var engine = scene.getEngine();
  53682. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  53683. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53684. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53685. this._volumetricLightScatteringRTT.renderList = null;
  53686. this._volumetricLightScatteringRTT.renderParticles = false;
  53687. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  53688. // Custom render function for submeshes
  53689. var renderSubMesh = function (subMesh) {
  53690. var mesh = subMesh.getRenderingMesh();
  53691. if (_this._meshExcluded(mesh)) {
  53692. return;
  53693. }
  53694. var scene = mesh.getScene();
  53695. var engine = scene.getEngine();
  53696. // Culling
  53697. engine.setState(subMesh.getMaterial().backFaceCulling);
  53698. // Managing instances
  53699. var batch = mesh._getInstancesRenderList(subMesh._id);
  53700. if (batch.mustReturn) {
  53701. return;
  53702. }
  53703. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  53704. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  53705. var effect = _this._volumetricLightScatteringPass;
  53706. if (mesh === _this.mesh) {
  53707. if (subMesh.effect) {
  53708. effect = subMesh.effect;
  53709. }
  53710. else {
  53711. effect = subMesh.getMaterial().getEffect();
  53712. }
  53713. }
  53714. engine.enableEffect(effect);
  53715. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  53716. if (mesh === _this.mesh) {
  53717. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  53718. }
  53719. else {
  53720. var material = subMesh.getMaterial();
  53721. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  53722. // Alpha test
  53723. if (material && material.needAlphaTesting()) {
  53724. var alphaTexture = material.getAlphaTestTexture();
  53725. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  53726. if (alphaTexture) {
  53727. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  53728. }
  53729. }
  53730. // Bones
  53731. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53732. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  53733. }
  53734. }
  53735. // Draw
  53736. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  53737. }
  53738. };
  53739. // Render target texture callbacks
  53740. var savedSceneClearColor;
  53741. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  53742. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  53743. savedSceneClearColor = scene.clearColor;
  53744. scene.clearColor = sceneClearColor;
  53745. });
  53746. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  53747. scene.clearColor = savedSceneClearColor;
  53748. });
  53749. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  53750. var engine = scene.getEngine();
  53751. var index;
  53752. for (index = 0; index < opaqueSubMeshes.length; index++) {
  53753. renderSubMesh(opaqueSubMeshes.data[index]);
  53754. }
  53755. engine.setAlphaTesting(true);
  53756. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  53757. renderSubMesh(alphaTestSubMeshes.data[index]);
  53758. }
  53759. engine.setAlphaTesting(false);
  53760. if (transparentSubMeshes.length) {
  53761. // Sort sub meshes
  53762. for (index = 0; index < transparentSubMeshes.length; index++) {
  53763. var submesh = transparentSubMeshes.data[index];
  53764. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  53765. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  53766. }
  53767. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  53768. sortedArray.sort(function (a, b) {
  53769. // Alpha index first
  53770. if (a._alphaIndex > b._alphaIndex) {
  53771. return 1;
  53772. }
  53773. if (a._alphaIndex < b._alphaIndex) {
  53774. return -1;
  53775. }
  53776. // Then distance to camera
  53777. if (a._distanceToCamera < b._distanceToCamera) {
  53778. return 1;
  53779. }
  53780. if (a._distanceToCamera > b._distanceToCamera) {
  53781. return -1;
  53782. }
  53783. return 0;
  53784. });
  53785. // Render sub meshes
  53786. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53787. for (index = 0; index < sortedArray.length; index++) {
  53788. renderSubMesh(sortedArray[index]);
  53789. }
  53790. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53791. }
  53792. };
  53793. };
  53794. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  53795. var transform = scene.getTransformMatrix();
  53796. var meshPosition;
  53797. if (this.useCustomMeshPosition) {
  53798. meshPosition = this.customMeshPosition;
  53799. }
  53800. else if (this.attachedNode) {
  53801. meshPosition = this.attachedNode.position;
  53802. }
  53803. else {
  53804. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  53805. }
  53806. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  53807. this._screenCoordinates.x = pos.x / this._viewPort.width;
  53808. this._screenCoordinates.y = pos.y / this._viewPort.height;
  53809. if (this.invert)
  53810. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  53811. };
  53812. // Static methods
  53813. /**
  53814. * Creates a default mesh for the Volumeric Light Scattering post-process
  53815. * @param {string} The mesh name
  53816. * @param {BABYLON.Scene} The scene where to create the mesh
  53817. * @return {BABYLON.Mesh} the default mesh
  53818. */
  53819. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  53820. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  53821. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  53822. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  53823. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  53824. mesh.material = material;
  53825. return mesh;
  53826. };
  53827. return VolumetricLightScatteringPostProcess;
  53828. }(BABYLON.PostProcess));
  53829. __decorate([
  53830. BABYLON.serializeAsVector3()
  53831. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  53832. __decorate([
  53833. BABYLON.serialize()
  53834. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  53835. __decorate([
  53836. BABYLON.serialize()
  53837. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  53838. __decorate([
  53839. BABYLON.serializeAsMeshReference()
  53840. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  53841. __decorate([
  53842. BABYLON.serialize()
  53843. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  53844. __decorate([
  53845. BABYLON.serialize()
  53846. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  53847. __decorate([
  53848. BABYLON.serialize()
  53849. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  53850. __decorate([
  53851. BABYLON.serialize()
  53852. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  53853. __decorate([
  53854. BABYLON.serialize()
  53855. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  53856. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  53857. })(BABYLON || (BABYLON = {}));
  53858. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  53859. //
  53860. // This post-process allows the modification of rendered colors by using
  53861. // a 'look-up table' (LUT). This effect is also called Color Grading.
  53862. //
  53863. // The object needs to be provided an url to a texture containing the color
  53864. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  53865. // Use an image editing software to tweak the LUT to match your needs.
  53866. //
  53867. // For an example of a color LUT, see here:
  53868. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  53869. // For explanations on color grading, see here:
  53870. // http://udn.epicgames.com/Three/ColorGrading.html
  53871. //
  53872. var BABYLON;
  53873. (function (BABYLON) {
  53874. var ColorCorrectionPostProcess = (function (_super) {
  53875. __extends(ColorCorrectionPostProcess, _super);
  53876. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  53877. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  53878. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  53879. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  53880. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53881. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53882. _this.onApply = function (effect) {
  53883. effect.setTexture("colorTable", _this._colorTableTexture);
  53884. };
  53885. return _this;
  53886. }
  53887. return ColorCorrectionPostProcess;
  53888. }(BABYLON.PostProcess));
  53889. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  53890. })(BABYLON || (BABYLON = {}));
  53891. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  53892. var BABYLON;
  53893. (function (BABYLON) {
  53894. var TonemappingOperator;
  53895. (function (TonemappingOperator) {
  53896. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  53897. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  53898. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  53899. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  53900. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  53901. ;
  53902. var TonemapPostProcess = (function (_super) {
  53903. __extends(TonemapPostProcess, _super);
  53904. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  53905. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  53906. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53907. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  53908. _this._operator = _operator;
  53909. _this.exposureAdjustment = exposureAdjustment;
  53910. var defines = "#define ";
  53911. if (_this._operator === TonemappingOperator.Hable)
  53912. defines += "HABLE_TONEMAPPING";
  53913. else if (_this._operator === TonemappingOperator.Reinhard)
  53914. defines += "REINHARD_TONEMAPPING";
  53915. else if (_this._operator === TonemappingOperator.HejiDawson)
  53916. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  53917. else if (_this._operator === TonemappingOperator.Photographic)
  53918. defines += "PHOTOGRAPHIC_TONEMAPPING";
  53919. //sadly a second call to create the effect.
  53920. _this.updateEffect(defines);
  53921. _this.onApply = function (effect) {
  53922. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  53923. };
  53924. return _this;
  53925. }
  53926. return TonemapPostProcess;
  53927. }(BABYLON.PostProcess));
  53928. BABYLON.TonemapPostProcess = TonemapPostProcess;
  53929. })(BABYLON || (BABYLON = {}));
  53930. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  53931. var BABYLON;
  53932. (function (BABYLON) {
  53933. var DisplayPassPostProcess = (function (_super) {
  53934. __extends(DisplayPassPostProcess, _super);
  53935. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  53936. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  53937. }
  53938. return DisplayPassPostProcess;
  53939. }(BABYLON.PostProcess));
  53940. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  53941. })(BABYLON || (BABYLON = {}));
  53942. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  53943. var BABYLON;
  53944. (function (BABYLON) {
  53945. var HighlightsPostProcess = (function (_super) {
  53946. __extends(HighlightsPostProcess, _super);
  53947. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  53948. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53949. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  53950. }
  53951. return HighlightsPostProcess;
  53952. }(BABYLON.PostProcess));
  53953. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  53954. })(BABYLON || (BABYLON = {}));
  53955. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  53956. var BABYLON;
  53957. (function (BABYLON) {
  53958. var ImageProcessingPostProcess = (function (_super) {
  53959. __extends(ImageProcessingPostProcess, _super);
  53960. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  53961. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53962. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  53963. _this._fromLinearSpace = true;
  53964. /**
  53965. * Defines cache preventing GC.
  53966. */
  53967. _this._defines = {
  53968. IMAGEPROCESSING: false,
  53969. VIGNETTE: false,
  53970. VIGNETTEBLENDMODEMULTIPLY: false,
  53971. VIGNETTEBLENDMODEOPAQUE: false,
  53972. TONEMAPPING: false,
  53973. CONTRAST: false,
  53974. COLORCURVES: false,
  53975. COLORGRADING: false,
  53976. FROMLINEARSPACE: false,
  53977. SAMPLER3DGREENDEPTH: false,
  53978. SAMPLER3DBGRMAP: false,
  53979. IMAGEPROCESSINGPOSTPROCESS: false,
  53980. EXPOSURE: false,
  53981. };
  53982. // Setup the default processing configuration to the scene.
  53983. _this._attachImageProcessingConfiguration(null, true);
  53984. _this.imageProcessingConfiguration.applyByPostProcess = true;
  53985. _this.onApply = function (effect) {
  53986. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  53987. };
  53988. return _this;
  53989. }
  53990. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  53991. /**
  53992. * Gets the image processing configuration used either in this material.
  53993. */
  53994. get: function () {
  53995. return this._imageProcessingConfiguration;
  53996. },
  53997. /**
  53998. * Sets the Default image processing configuration used either in the this material.
  53999. *
  54000. * If sets to null, the scene one is in use.
  54001. */
  54002. set: function (value) {
  54003. this._attachImageProcessingConfiguration(value);
  54004. },
  54005. enumerable: true,
  54006. configurable: true
  54007. });
  54008. /**
  54009. * Attaches a new image processing configuration to the PBR Material.
  54010. * @param configuration
  54011. */
  54012. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  54013. var _this = this;
  54014. if (doNotBuild === void 0) { doNotBuild = false; }
  54015. if (configuration === this._imageProcessingConfiguration) {
  54016. return;
  54017. }
  54018. // Detaches observer.
  54019. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  54020. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  54021. }
  54022. // Pick the scene configuration if needed.
  54023. if (!configuration) {
  54024. var camera = this.getCamera();
  54025. var scene = camera ? camera.getScene() : BABYLON.Engine.LastCreatedScene;
  54026. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  54027. }
  54028. else {
  54029. this._imageProcessingConfiguration = configuration;
  54030. }
  54031. // Attaches observer.
  54032. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  54033. _this._updateParameters();
  54034. });
  54035. // Ensure the effect will be rebuilt.
  54036. if (!doNotBuild) {
  54037. this._updateParameters();
  54038. }
  54039. };
  54040. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  54041. /**
  54042. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  54043. */
  54044. get: function () {
  54045. return this.imageProcessingConfiguration.colorCurves;
  54046. },
  54047. /**
  54048. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  54049. */
  54050. set: function (value) {
  54051. this.imageProcessingConfiguration.colorCurves = value;
  54052. },
  54053. enumerable: true,
  54054. configurable: true
  54055. });
  54056. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  54057. /**
  54058. * Gets wether the color curves effect is enabled.
  54059. */
  54060. get: function () {
  54061. return this.imageProcessingConfiguration.colorCurvesEnabled;
  54062. },
  54063. /**
  54064. * Sets wether the color curves effect is enabled.
  54065. */
  54066. set: function (value) {
  54067. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  54068. },
  54069. enumerable: true,
  54070. configurable: true
  54071. });
  54072. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  54073. /**
  54074. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  54075. */
  54076. get: function () {
  54077. return this.imageProcessingConfiguration.colorGradingTexture;
  54078. },
  54079. /**
  54080. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  54081. */
  54082. set: function (value) {
  54083. this.imageProcessingConfiguration.colorGradingTexture = value;
  54084. },
  54085. enumerable: true,
  54086. configurable: true
  54087. });
  54088. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  54089. /**
  54090. * Gets wether the color grading effect is enabled.
  54091. */
  54092. get: function () {
  54093. return this.imageProcessingConfiguration.colorGradingEnabled;
  54094. },
  54095. /**
  54096. * Gets wether the color grading effect is enabled.
  54097. */
  54098. set: function (value) {
  54099. this.imageProcessingConfiguration.colorGradingEnabled = value;
  54100. },
  54101. enumerable: true,
  54102. configurable: true
  54103. });
  54104. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  54105. /**
  54106. * Gets exposure used in the effect.
  54107. */
  54108. get: function () {
  54109. return this.imageProcessingConfiguration.exposure;
  54110. },
  54111. /**
  54112. * Sets exposure used in the effect.
  54113. */
  54114. set: function (value) {
  54115. this.imageProcessingConfiguration.exposure = value;
  54116. },
  54117. enumerable: true,
  54118. configurable: true
  54119. });
  54120. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  54121. /**
  54122. * Gets wether tonemapping is enabled or not.
  54123. */
  54124. get: function () {
  54125. return this._imageProcessingConfiguration.toneMappingEnabled;
  54126. },
  54127. /**
  54128. * Sets wether tonemapping is enabled or not
  54129. */
  54130. set: function (value) {
  54131. this._imageProcessingConfiguration.toneMappingEnabled = value;
  54132. },
  54133. enumerable: true,
  54134. configurable: true
  54135. });
  54136. ;
  54137. ;
  54138. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  54139. /**
  54140. * Gets contrast used in the effect.
  54141. */
  54142. get: function () {
  54143. return this.imageProcessingConfiguration.contrast;
  54144. },
  54145. /**
  54146. * Sets contrast used in the effect.
  54147. */
  54148. set: function (value) {
  54149. this.imageProcessingConfiguration.contrast = value;
  54150. },
  54151. enumerable: true,
  54152. configurable: true
  54153. });
  54154. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  54155. /**
  54156. * Gets Vignette stretch size.
  54157. */
  54158. get: function () {
  54159. return this.imageProcessingConfiguration.vignetteStretch;
  54160. },
  54161. /**
  54162. * Sets Vignette stretch size.
  54163. */
  54164. set: function (value) {
  54165. this.imageProcessingConfiguration.vignetteStretch = value;
  54166. },
  54167. enumerable: true,
  54168. configurable: true
  54169. });
  54170. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  54171. /**
  54172. * Gets Vignette centre X Offset.
  54173. */
  54174. get: function () {
  54175. return this.imageProcessingConfiguration.vignetteCentreX;
  54176. },
  54177. /**
  54178. * Sets Vignette centre X Offset.
  54179. */
  54180. set: function (value) {
  54181. this.imageProcessingConfiguration.vignetteCentreX = value;
  54182. },
  54183. enumerable: true,
  54184. configurable: true
  54185. });
  54186. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  54187. /**
  54188. * Gets Vignette centre Y Offset.
  54189. */
  54190. get: function () {
  54191. return this.imageProcessingConfiguration.vignetteCentreY;
  54192. },
  54193. /**
  54194. * Sets Vignette centre Y Offset.
  54195. */
  54196. set: function (value) {
  54197. this.imageProcessingConfiguration.vignetteCentreY = value;
  54198. },
  54199. enumerable: true,
  54200. configurable: true
  54201. });
  54202. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  54203. /**
  54204. * Gets Vignette weight or intensity of the vignette effect.
  54205. */
  54206. get: function () {
  54207. return this.imageProcessingConfiguration.vignetteWeight;
  54208. },
  54209. /**
  54210. * Sets Vignette weight or intensity of the vignette effect.
  54211. */
  54212. set: function (value) {
  54213. this.imageProcessingConfiguration.vignetteWeight = value;
  54214. },
  54215. enumerable: true,
  54216. configurable: true
  54217. });
  54218. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  54219. /**
  54220. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  54221. * if vignetteEnabled is set to true.
  54222. */
  54223. get: function () {
  54224. return this.imageProcessingConfiguration.vignetteColor;
  54225. },
  54226. /**
  54227. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  54228. * if vignetteEnabled is set to true.
  54229. */
  54230. set: function (value) {
  54231. this.imageProcessingConfiguration.vignetteColor = value;
  54232. },
  54233. enumerable: true,
  54234. configurable: true
  54235. });
  54236. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  54237. /**
  54238. * Gets Camera field of view used by the Vignette effect.
  54239. */
  54240. get: function () {
  54241. return this.imageProcessingConfiguration.vignetteCameraFov;
  54242. },
  54243. /**
  54244. * Sets Camera field of view used by the Vignette effect.
  54245. */
  54246. set: function (value) {
  54247. this.imageProcessingConfiguration.vignetteCameraFov = value;
  54248. },
  54249. enumerable: true,
  54250. configurable: true
  54251. });
  54252. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  54253. /**
  54254. * Gets the vignette blend mode allowing different kind of effect.
  54255. */
  54256. get: function () {
  54257. return this.imageProcessingConfiguration.vignetteBlendMode;
  54258. },
  54259. /**
  54260. * Sets the vignette blend mode allowing different kind of effect.
  54261. */
  54262. set: function (value) {
  54263. this.imageProcessingConfiguration.vignetteBlendMode = value;
  54264. },
  54265. enumerable: true,
  54266. configurable: true
  54267. });
  54268. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  54269. /**
  54270. * Gets wether the vignette effect is enabled.
  54271. */
  54272. get: function () {
  54273. return this.imageProcessingConfiguration.vignetteEnabled;
  54274. },
  54275. /**
  54276. * Sets wether the vignette effect is enabled.
  54277. */
  54278. set: function (value) {
  54279. this.imageProcessingConfiguration.vignetteEnabled = value;
  54280. },
  54281. enumerable: true,
  54282. configurable: true
  54283. });
  54284. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  54285. /**
  54286. * Gets wether the input of the processing is in Gamma or Linear Space.
  54287. */
  54288. get: function () {
  54289. return this._fromLinearSpace;
  54290. },
  54291. /**
  54292. * Sets wether the input of the processing is in Gamma or Linear Space.
  54293. */
  54294. set: function (value) {
  54295. if (this._fromLinearSpace === value) {
  54296. return;
  54297. }
  54298. this._fromLinearSpace = value;
  54299. this._updateParameters();
  54300. },
  54301. enumerable: true,
  54302. configurable: true
  54303. });
  54304. ImageProcessingPostProcess.prototype.getClassName = function () {
  54305. return "ImageProcessingPostProcess";
  54306. };
  54307. ImageProcessingPostProcess.prototype._updateParameters = function () {
  54308. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  54309. this.imageProcessingConfiguration.prepareDefines(this._defines);
  54310. var defines = "";
  54311. for (var define in this._defines) {
  54312. if (this._defines[define]) {
  54313. defines += "#define " + define + ";\r\n";
  54314. }
  54315. }
  54316. var samplers = ["textureSampler"];
  54317. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  54318. var uniforms = ["scale"];
  54319. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  54320. this.updateEffect(defines, uniforms, samplers);
  54321. };
  54322. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  54323. _super.prototype.dispose.call(this, camera);
  54324. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  54325. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  54326. }
  54327. this.imageProcessingConfiguration.applyByPostProcess = false;
  54328. };
  54329. return ImageProcessingPostProcess;
  54330. }(BABYLON.PostProcess));
  54331. __decorate([
  54332. BABYLON.serialize()
  54333. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  54334. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  54335. })(BABYLON || (BABYLON = {}));
  54336. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  54337. var BABYLON;
  54338. (function (BABYLON) {
  54339. var BlurPostProcess = (function (_super) {
  54340. __extends(BlurPostProcess, _super);
  54341. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  54342. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  54343. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54344. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  54345. _this.direction = direction;
  54346. _this._packedFloat = false;
  54347. _this.onApplyObservable.add(function (effect) {
  54348. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  54349. });
  54350. _this.kernel = kernel;
  54351. return _this;
  54352. }
  54353. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  54354. /**
  54355. * Gets the length in pixels of the blur sample region
  54356. */
  54357. get: function () {
  54358. return this._idealKernel;
  54359. },
  54360. /**
  54361. * Sets the length in pixels of the blur sample region
  54362. */
  54363. set: function (v) {
  54364. if (this._idealKernel === v) {
  54365. return;
  54366. }
  54367. v = Math.max(v, 1);
  54368. this._idealKernel = v;
  54369. this._kernel = this._nearestBestKernel(v);
  54370. this._updateParameters();
  54371. },
  54372. enumerable: true,
  54373. configurable: true
  54374. });
  54375. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  54376. /**
  54377. * Gets wether or not the blur is unpacking/repacking floats
  54378. */
  54379. get: function () {
  54380. return this._packedFloat;
  54381. },
  54382. /**
  54383. * Sets wether or not the blur needs to unpack/repack floats
  54384. */
  54385. set: function (v) {
  54386. if (this._packedFloat === v) {
  54387. return;
  54388. }
  54389. this._packedFloat = v;
  54390. this._updateParameters();
  54391. },
  54392. enumerable: true,
  54393. configurable: true
  54394. });
  54395. BlurPostProcess.prototype._updateParameters = function () {
  54396. // Generate sampling offsets and weights
  54397. var N = this._kernel;
  54398. var centerIndex = (N - 1) / 2;
  54399. // Generate Gaussian sampling weights over kernel
  54400. var offsets = [];
  54401. var weights = [];
  54402. var totalWeight = 0;
  54403. for (var i = 0; i < N; i++) {
  54404. var u = i / (N - 1);
  54405. var w = this._gaussianWeight(u * 2.0 - 1);
  54406. offsets[i] = (i - centerIndex);
  54407. weights[i] = w;
  54408. totalWeight += w;
  54409. }
  54410. // Normalize weights
  54411. for (var i = 0; i < weights.length; i++) {
  54412. weights[i] /= totalWeight;
  54413. }
  54414. // Optimize: combine samples to take advantage of hardware linear sampling
  54415. // Walk from left to center, combining pairs (symmetrically)
  54416. var linearSamplingWeights = [];
  54417. var linearSamplingOffsets = [];
  54418. var linearSamplingMap = [];
  54419. for (var i = 0; i <= centerIndex; i += 2) {
  54420. var j = Math.min(i + 1, Math.floor(centerIndex));
  54421. var singleCenterSample = i === j;
  54422. if (singleCenterSample) {
  54423. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  54424. }
  54425. else {
  54426. var sharedCell = j === centerIndex;
  54427. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  54428. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  54429. if (offsetLinear === 0) {
  54430. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  54431. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  54432. }
  54433. else {
  54434. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  54435. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  54436. }
  54437. }
  54438. }
  54439. for (var i = 0; i < linearSamplingMap.length; i++) {
  54440. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  54441. linearSamplingWeights[i] = linearSamplingMap[i].w;
  54442. }
  54443. // Replace with optimized
  54444. offsets = linearSamplingOffsets;
  54445. weights = linearSamplingWeights;
  54446. // Generate shaders
  54447. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  54448. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  54449. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  54450. var defines = "";
  54451. for (var i = 0; i < varyingCount; i++) {
  54452. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  54453. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  54454. }
  54455. var depCount = 0;
  54456. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  54457. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  54458. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  54459. depCount++;
  54460. }
  54461. if (this.packedFloat) {
  54462. defines += "#define PACKEDFLOAT 1";
  54463. }
  54464. this.updateEffect(defines, null, null, {
  54465. varyingCount: varyingCount,
  54466. depCount: depCount
  54467. });
  54468. };
  54469. /**
  54470. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  54471. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  54472. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  54473. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  54474. * The gaps between physical kernels are compensated for in the weighting of the samples
  54475. * @param idealKernel Ideal blur kernel.
  54476. * @return Nearest best kernel.
  54477. */
  54478. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  54479. var v = Math.round(idealKernel);
  54480. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  54481. var k = _a[_i];
  54482. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  54483. return Math.max(k, 3);
  54484. }
  54485. }
  54486. return Math.max(v, 3);
  54487. };
  54488. /**
  54489. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  54490. * @param x The point on the Gaussian distribution to sample.
  54491. * @return the value of the Gaussian function at x.
  54492. */
  54493. BlurPostProcess.prototype._gaussianWeight = function (x) {
  54494. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  54495. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  54496. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  54497. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  54498. // truncated at around 1.3% of peak strength.
  54499. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  54500. var sigma = (1 / 3);
  54501. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  54502. var exponent = -((x * x) / (2.0 * sigma * sigma));
  54503. var weight = (1.0 / denominator) * Math.exp(exponent);
  54504. return weight;
  54505. };
  54506. /**
  54507. * Generates a string that can be used as a floating point number in GLSL.
  54508. * @param x Value to print.
  54509. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  54510. * @return GLSL float string.
  54511. */
  54512. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  54513. if (decimalFigures === void 0) { decimalFigures = 8; }
  54514. return x.toFixed(decimalFigures).replace(/0+$/, '');
  54515. };
  54516. return BlurPostProcess;
  54517. }(BABYLON.PostProcess));
  54518. BABYLON.BlurPostProcess = BlurPostProcess;
  54519. })(BABYLON || (BABYLON = {}));
  54520. //# sourceMappingURL=babylon.blurPostProcess.js.map
  54521. /// <reference path="..\babylon.node.ts" />
  54522. var BABYLON;
  54523. (function (BABYLON) {
  54524. var Bone = (function (_super) {
  54525. __extends(Bone, _super);
  54526. function Bone(name, skeleton, parentBone, matrix, restPose) {
  54527. if (parentBone === void 0) { parentBone = null; }
  54528. var _this = _super.call(this, name, skeleton.getScene()) || this;
  54529. _this.name = name;
  54530. _this.children = new Array();
  54531. _this.animations = new Array();
  54532. _this._worldTransform = new BABYLON.Matrix();
  54533. _this._absoluteTransform = new BABYLON.Matrix();
  54534. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  54535. _this._scaleMatrix = BABYLON.Matrix.Identity();
  54536. _this._scaleVector = BABYLON.Vector3.One();
  54537. _this._negateScaleChildren = BABYLON.Vector3.One();
  54538. _this._scalingDeterminant = 1;
  54539. _this._skeleton = skeleton;
  54540. _this._localMatrix = matrix ? matrix : BABYLON.Matrix.Identity();
  54541. _this._baseMatrix = _this._localMatrix.clone();
  54542. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  54543. skeleton.bones.push(_this);
  54544. _this.setParent(parentBone, false);
  54545. _this._updateDifferenceMatrix();
  54546. return _this;
  54547. }
  54548. Object.defineProperty(Bone.prototype, "_matrix", {
  54549. get: function () {
  54550. return this._localMatrix;
  54551. },
  54552. set: function (val) {
  54553. if (this._localMatrix) {
  54554. this._localMatrix.copyFrom(val);
  54555. }
  54556. else {
  54557. this._localMatrix = val;
  54558. }
  54559. },
  54560. enumerable: true,
  54561. configurable: true
  54562. });
  54563. // Members
  54564. Bone.prototype.getSkeleton = function () {
  54565. return this._skeleton;
  54566. };
  54567. Bone.prototype.getParent = function () {
  54568. return this._parent;
  54569. };
  54570. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  54571. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  54572. if (this._parent === parent) {
  54573. return;
  54574. }
  54575. if (this._parent) {
  54576. var index = this._parent.children.indexOf(this);
  54577. if (index !== -1) {
  54578. this._parent.children.splice(index);
  54579. }
  54580. }
  54581. this._parent = parent;
  54582. if (this._parent) {
  54583. this._parent.children.push(this);
  54584. }
  54585. if (updateDifferenceMatrix) {
  54586. this._updateDifferenceMatrix();
  54587. }
  54588. };
  54589. Bone.prototype.getLocalMatrix = function () {
  54590. return this._localMatrix;
  54591. };
  54592. Bone.prototype.getBaseMatrix = function () {
  54593. return this._baseMatrix;
  54594. };
  54595. Bone.prototype.getRestPose = function () {
  54596. return this._restPose;
  54597. };
  54598. Bone.prototype.returnToRest = function () {
  54599. this.updateMatrix(this._restPose.clone());
  54600. };
  54601. Bone.prototype.getWorldMatrix = function () {
  54602. return this._worldTransform;
  54603. };
  54604. Bone.prototype.getInvertedAbsoluteTransform = function () {
  54605. return this._invertedAbsoluteTransform;
  54606. };
  54607. Bone.prototype.getAbsoluteTransform = function () {
  54608. return this._absoluteTransform;
  54609. };
  54610. Object.defineProperty(Bone.prototype, "position", {
  54611. // Properties (matches AbstractMesh properties)
  54612. get: function () {
  54613. return this.getPosition();
  54614. },
  54615. set: function (newPosition) {
  54616. this.setPosition(newPosition);
  54617. },
  54618. enumerable: true,
  54619. configurable: true
  54620. });
  54621. Object.defineProperty(Bone.prototype, "rotation", {
  54622. get: function () {
  54623. return this.getRotation();
  54624. },
  54625. set: function (newRotation) {
  54626. this.setRotation(newRotation);
  54627. },
  54628. enumerable: true,
  54629. configurable: true
  54630. });
  54631. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  54632. get: function () {
  54633. return this.getRotationQuaternion();
  54634. },
  54635. set: function (newRotation) {
  54636. this.setRotationQuaternion(newRotation);
  54637. },
  54638. enumerable: true,
  54639. configurable: true
  54640. });
  54641. Object.defineProperty(Bone.prototype, "scaling", {
  54642. get: function () {
  54643. return this.getScale();
  54644. },
  54645. set: function (newScaling) {
  54646. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  54647. },
  54648. enumerable: true,
  54649. configurable: true
  54650. });
  54651. // Methods
  54652. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  54653. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  54654. this._baseMatrix = matrix.clone();
  54655. this._localMatrix = matrix.clone();
  54656. this._skeleton._markAsDirty();
  54657. if (updateDifferenceMatrix) {
  54658. this._updateDifferenceMatrix();
  54659. }
  54660. };
  54661. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  54662. if (!rootMatrix) {
  54663. rootMatrix = this._baseMatrix;
  54664. }
  54665. if (this._parent) {
  54666. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  54667. }
  54668. else {
  54669. this._absoluteTransform.copyFrom(rootMatrix);
  54670. }
  54671. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  54672. for (var index = 0; index < this.children.length; index++) {
  54673. this.children[index]._updateDifferenceMatrix();
  54674. }
  54675. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  54676. };
  54677. Bone.prototype.markAsDirty = function () {
  54678. this._currentRenderId++;
  54679. this._skeleton._markAsDirty();
  54680. };
  54681. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  54682. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  54683. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  54684. // all animation may be coming from a library skeleton, so may need to create animation
  54685. if (this.animations.length === 0) {
  54686. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  54687. this.animations[0].setKeys([]);
  54688. }
  54689. // get animation info / verify there is such a range from the source bone
  54690. var sourceRange = source.animations[0].getRange(rangeName);
  54691. if (!sourceRange) {
  54692. return false;
  54693. }
  54694. var from = sourceRange.from;
  54695. var to = sourceRange.to;
  54696. var sourceKeys = source.animations[0].getKeys();
  54697. // rescaling prep
  54698. var sourceBoneLength = source.length;
  54699. var sourceParent = source.getParent();
  54700. var parent = this.getParent();
  54701. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  54702. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  54703. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  54704. var destKeys = this.animations[0].getKeys();
  54705. // loop vars declaration
  54706. var orig;
  54707. var origTranslation;
  54708. var mat;
  54709. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  54710. orig = sourceKeys[key];
  54711. if (orig.frame >= from && orig.frame <= to) {
  54712. if (rescaleAsRequired) {
  54713. mat = orig.value.clone();
  54714. // scale based on parent ratio, when bone has parent
  54715. if (parentScalingReqd) {
  54716. origTranslation = mat.getTranslation();
  54717. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  54718. // scale based on skeleton dimension ratio when root bone, and value is passed
  54719. }
  54720. else if (dimensionsScalingReqd) {
  54721. origTranslation = mat.getTranslation();
  54722. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  54723. // use original when root bone, and no data for skelDimensionsRatio
  54724. }
  54725. else {
  54726. mat = orig.value;
  54727. }
  54728. }
  54729. else {
  54730. mat = orig.value;
  54731. }
  54732. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  54733. }
  54734. }
  54735. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  54736. return true;
  54737. };
  54738. /**
  54739. * Translate the bone in local or world space.
  54740. * @param vec The amount to translate the bone.
  54741. * @param space The space that the translation is in.
  54742. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  54743. */
  54744. Bone.prototype.translate = function (vec, space, mesh) {
  54745. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  54746. var lm = this.getLocalMatrix();
  54747. if (space == BABYLON.Space.LOCAL) {
  54748. lm.m[12] += vec.x;
  54749. lm.m[13] += vec.y;
  54750. lm.m[14] += vec.z;
  54751. }
  54752. else {
  54753. var wm;
  54754. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  54755. if (mesh) {
  54756. wm = mesh.getWorldMatrix();
  54757. }
  54758. this._skeleton.computeAbsoluteTransforms();
  54759. var tmat = Bone._tmpMats[0];
  54760. var tvec = Bone._tmpVecs[0];
  54761. if (mesh) {
  54762. tmat.copyFrom(this._parent.getAbsoluteTransform());
  54763. tmat.multiplyToRef(wm, tmat);
  54764. }
  54765. else {
  54766. tmat.copyFrom(this._parent.getAbsoluteTransform());
  54767. }
  54768. tmat.m[12] = 0;
  54769. tmat.m[13] = 0;
  54770. tmat.m[14] = 0;
  54771. tmat.invert();
  54772. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  54773. lm.m[12] += tvec.x;
  54774. lm.m[13] += tvec.y;
  54775. lm.m[14] += tvec.z;
  54776. }
  54777. this.markAsDirty();
  54778. };
  54779. /**
  54780. * Set the postion of the bone in local or world space.
  54781. * @param position The position to set the bone.
  54782. * @param space The space that the position is in.
  54783. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  54784. */
  54785. Bone.prototype.setPosition = function (position, space, mesh) {
  54786. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  54787. var lm = this.getLocalMatrix();
  54788. if (space == BABYLON.Space.LOCAL) {
  54789. lm.m[12] = position.x;
  54790. lm.m[13] = position.y;
  54791. lm.m[14] = position.z;
  54792. }
  54793. else {
  54794. var wm;
  54795. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  54796. if (mesh) {
  54797. wm = mesh.getWorldMatrix();
  54798. }
  54799. this._skeleton.computeAbsoluteTransforms();
  54800. var tmat = Bone._tmpMats[0];
  54801. var vec = Bone._tmpVecs[0];
  54802. if (mesh) {
  54803. tmat.copyFrom(this._parent.getAbsoluteTransform());
  54804. tmat.multiplyToRef(wm, tmat);
  54805. }
  54806. else {
  54807. tmat.copyFrom(this._parent.getAbsoluteTransform());
  54808. }
  54809. tmat.invert();
  54810. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  54811. lm.m[12] = vec.x;
  54812. lm.m[13] = vec.y;
  54813. lm.m[14] = vec.z;
  54814. }
  54815. this.markAsDirty();
  54816. };
  54817. /**
  54818. * Set the absolute postion of the bone (world space).
  54819. * @param position The position to set the bone.
  54820. * @param mesh The mesh that this bone is attached to.
  54821. */
  54822. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  54823. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  54824. };
  54825. /**
  54826. * Set the scale of the bone on the x, y and z axes.
  54827. * @param x The scale of the bone on the x axis.
  54828. * @param x The scale of the bone on the y axis.
  54829. * @param z The scale of the bone on the z axis.
  54830. * @param scaleChildren Set this to true if children of the bone should be scaled.
  54831. */
  54832. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  54833. if (scaleChildren === void 0) { scaleChildren = false; }
  54834. if (this.animations[0] && !this.animations[0].isStopped()) {
  54835. if (!scaleChildren) {
  54836. this._negateScaleChildren.x = 1 / x;
  54837. this._negateScaleChildren.y = 1 / y;
  54838. this._negateScaleChildren.z = 1 / z;
  54839. }
  54840. this._syncScaleVector();
  54841. }
  54842. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  54843. };
  54844. /**
  54845. * Scale the bone on the x, y and z axes.
  54846. * @param x The amount to scale the bone on the x axis.
  54847. * @param x The amount to scale the bone on the y axis.
  54848. * @param z The amount to scale the bone on the z axis.
  54849. * @param scaleChildren Set this to true if children of the bone should be scaled.
  54850. */
  54851. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  54852. if (scaleChildren === void 0) { scaleChildren = false; }
  54853. var locMat = this.getLocalMatrix();
  54854. var origLocMat = Bone._tmpMats[0];
  54855. origLocMat.copyFrom(locMat);
  54856. var origLocMatInv = Bone._tmpMats[1];
  54857. origLocMatInv.copyFrom(origLocMat);
  54858. origLocMatInv.invert();
  54859. var scaleMat = Bone._tmpMats[2];
  54860. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  54861. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  54862. this._scaleVector.x *= x;
  54863. this._scaleVector.y *= y;
  54864. this._scaleVector.z *= z;
  54865. locMat.multiplyToRef(origLocMatInv, locMat);
  54866. locMat.multiplyToRef(scaleMat, locMat);
  54867. locMat.multiplyToRef(origLocMat, locMat);
  54868. var parent = this.getParent();
  54869. if (parent) {
  54870. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  54871. }
  54872. else {
  54873. this.getAbsoluteTransform().copyFrom(locMat);
  54874. }
  54875. var len = this.children.length;
  54876. scaleMat.invert();
  54877. for (var i = 0; i < len; i++) {
  54878. var child = this.children[i];
  54879. var cm = child.getLocalMatrix();
  54880. cm.multiplyToRef(scaleMat, cm);
  54881. var lm = child.getLocalMatrix();
  54882. lm.m[12] *= x;
  54883. lm.m[13] *= y;
  54884. lm.m[14] *= z;
  54885. }
  54886. this.computeAbsoluteTransforms();
  54887. if (scaleChildren) {
  54888. for (var i = 0; i < len; i++) {
  54889. this.children[i].scale(x, y, z, scaleChildren);
  54890. }
  54891. }
  54892. this.markAsDirty();
  54893. };
  54894. /**
  54895. * Set the yaw, pitch, and roll of the bone in local or world space.
  54896. * @param yaw The rotation of the bone on the y axis.
  54897. * @param pitch The rotation of the bone on the x axis.
  54898. * @param roll The rotation of the bone on the z axis.
  54899. * @param space The space that the axes of rotation are in.
  54900. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  54901. */
  54902. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  54903. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  54904. var rotMat = Bone._tmpMats[0];
  54905. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  54906. var rotMatInv = Bone._tmpMats[1];
  54907. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  54908. rotMatInv.multiplyToRef(rotMat, rotMat);
  54909. this._rotateWithMatrix(rotMat, space, mesh);
  54910. };
  54911. /**
  54912. * Rotate the bone on an axis in local or world space.
  54913. * @param axis The axis to rotate the bone on.
  54914. * @param amount The amount to rotate the bone.
  54915. * @param space The space that the axis is in.
  54916. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  54917. */
  54918. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  54919. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  54920. var rmat = Bone._tmpMats[0];
  54921. rmat.m[12] = 0;
  54922. rmat.m[13] = 0;
  54923. rmat.m[14] = 0;
  54924. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  54925. this._rotateWithMatrix(rmat, space, mesh);
  54926. };
  54927. /**
  54928. * Set the rotation of the bone to a particular axis angle in local or world space.
  54929. * @param axis The axis to rotate the bone on.
  54930. * @param angle The angle that the bone should be rotated to.
  54931. * @param space The space that the axis is in.
  54932. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  54933. */
  54934. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  54935. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  54936. var rotMat = Bone._tmpMats[0];
  54937. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  54938. var rotMatInv = Bone._tmpMats[1];
  54939. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  54940. rotMatInv.multiplyToRef(rotMat, rotMat);
  54941. this._rotateWithMatrix(rotMat, space, mesh);
  54942. };
  54943. /**
  54944. * Set the euler rotation of the bone in local of world space.
  54945. * @param rotation The euler rotation that the bone should be set to.
  54946. * @param space The space that the rotation is in.
  54947. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  54948. */
  54949. Bone.prototype.setRotation = function (rotation, space, mesh) {
  54950. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  54951. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  54952. };
  54953. /**
  54954. * Set the quaternion rotation of the bone in local of world space.
  54955. * @param quat The quaternion rotation that the bone should be set to.
  54956. * @param space The space that the rotation is in.
  54957. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  54958. */
  54959. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  54960. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  54961. var rotMatInv = Bone._tmpMats[0];
  54962. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  54963. var rotMat = Bone._tmpMats[1];
  54964. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  54965. rotMatInv.multiplyToRef(rotMat, rotMat);
  54966. this._rotateWithMatrix(rotMat, space, mesh);
  54967. };
  54968. /**
  54969. * Set the rotation matrix of the bone in local of world space.
  54970. * @param rotMat The rotation matrix that the bone should be set to.
  54971. * @param space The space that the rotation is in.
  54972. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  54973. */
  54974. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  54975. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  54976. var rotMatInv = Bone._tmpMats[0];
  54977. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  54978. var rotMat2 = Bone._tmpMats[1];
  54979. rotMat2.copyFrom(rotMat);
  54980. rotMatInv.multiplyToRef(rotMat, rotMat2);
  54981. this._rotateWithMatrix(rotMat2, space, mesh);
  54982. };
  54983. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  54984. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  54985. var lmat = this.getLocalMatrix();
  54986. var lx = lmat.m[12];
  54987. var ly = lmat.m[13];
  54988. var lz = lmat.m[14];
  54989. var parent = this.getParent();
  54990. var parentScale = Bone._tmpMats[3];
  54991. var parentScaleInv = Bone._tmpMats[4];
  54992. if (parent) {
  54993. if (space == BABYLON.Space.WORLD) {
  54994. if (mesh) {
  54995. parentScale.copyFrom(mesh.getWorldMatrix());
  54996. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  54997. }
  54998. else {
  54999. parentScale.copyFrom(parent.getAbsoluteTransform());
  55000. }
  55001. }
  55002. else {
  55003. parentScale = parent._scaleMatrix;
  55004. }
  55005. parentScaleInv.copyFrom(parentScale);
  55006. parentScaleInv.invert();
  55007. lmat.multiplyToRef(parentScale, lmat);
  55008. lmat.multiplyToRef(rmat, lmat);
  55009. lmat.multiplyToRef(parentScaleInv, lmat);
  55010. }
  55011. else {
  55012. if (space == BABYLON.Space.WORLD && mesh) {
  55013. parentScale.copyFrom(mesh.getWorldMatrix());
  55014. parentScaleInv.copyFrom(parentScale);
  55015. parentScaleInv.invert();
  55016. lmat.multiplyToRef(parentScale, lmat);
  55017. lmat.multiplyToRef(rmat, lmat);
  55018. lmat.multiplyToRef(parentScaleInv, lmat);
  55019. }
  55020. else {
  55021. lmat.multiplyToRef(rmat, lmat);
  55022. }
  55023. }
  55024. lmat.m[12] = lx;
  55025. lmat.m[13] = ly;
  55026. lmat.m[14] = lz;
  55027. this.computeAbsoluteTransforms();
  55028. this.markAsDirty();
  55029. };
  55030. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  55031. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55032. if (space == BABYLON.Space.WORLD) {
  55033. var scaleMatrix = Bone._tmpMats[2];
  55034. scaleMatrix.copyFrom(this._scaleMatrix);
  55035. rotMatInv.copyFrom(this.getAbsoluteTransform());
  55036. if (mesh) {
  55037. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  55038. var meshScale = Bone._tmpMats[3];
  55039. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  55040. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  55041. }
  55042. rotMatInv.invert();
  55043. scaleMatrix.m[0] *= this._scalingDeterminant;
  55044. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  55045. }
  55046. else {
  55047. rotMatInv.copyFrom(this.getLocalMatrix());
  55048. rotMatInv.invert();
  55049. var scaleMatrix = Bone._tmpMats[2];
  55050. scaleMatrix.copyFrom(this._scaleMatrix);
  55051. if (this._parent) {
  55052. var pscaleMatrix = Bone._tmpMats[3];
  55053. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  55054. pscaleMatrix.invert();
  55055. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  55056. }
  55057. else {
  55058. scaleMatrix.m[0] *= this._scalingDeterminant;
  55059. }
  55060. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  55061. }
  55062. };
  55063. /**
  55064. * Get the scale of the bone
  55065. * @returns the scale of the bone
  55066. */
  55067. Bone.prototype.getScale = function () {
  55068. return this._scaleVector.clone();
  55069. };
  55070. /**
  55071. * Copy the scale of the bone to a vector3.
  55072. * @param result The vector3 to copy the scale to
  55073. */
  55074. Bone.prototype.getScaleToRef = function (result) {
  55075. result.copyFrom(this._scaleVector);
  55076. };
  55077. /**
  55078. * Get the position of the bone in local or world space.
  55079. * @param space The space that the returned position is in.
  55080. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55081. * @returns The position of the bone
  55082. */
  55083. Bone.prototype.getPosition = function (space, mesh) {
  55084. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55085. var pos = BABYLON.Vector3.Zero();
  55086. this.getPositionToRef(space, mesh, pos);
  55087. return pos;
  55088. };
  55089. /**
  55090. * Copy the position of the bone to a vector3 in local or world space.
  55091. * @param space The space that the returned position is in.
  55092. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55093. * @param result The vector3 to copy the position to.
  55094. */
  55095. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  55096. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55097. if (space == BABYLON.Space.LOCAL) {
  55098. var lm = this.getLocalMatrix();
  55099. result.x = lm.m[12];
  55100. result.y = lm.m[13];
  55101. result.z = lm.m[14];
  55102. }
  55103. else {
  55104. var wm;
  55105. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  55106. if (mesh) {
  55107. wm = mesh.getWorldMatrix();
  55108. }
  55109. this._skeleton.computeAbsoluteTransforms();
  55110. var tmat = Bone._tmpMats[0];
  55111. if (mesh) {
  55112. tmat.copyFrom(this.getAbsoluteTransform());
  55113. tmat.multiplyToRef(wm, tmat);
  55114. }
  55115. else {
  55116. tmat = this.getAbsoluteTransform();
  55117. }
  55118. result.x = tmat.m[12];
  55119. result.y = tmat.m[13];
  55120. result.z = tmat.m[14];
  55121. }
  55122. };
  55123. /**
  55124. * Get the absolute position of the bone (world space).
  55125. * @param mesh The mesh that this bone is attached to.
  55126. * @returns The absolute position of the bone
  55127. */
  55128. Bone.prototype.getAbsolutePosition = function (mesh) {
  55129. var pos = BABYLON.Vector3.Zero();
  55130. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  55131. return pos;
  55132. };
  55133. /**
  55134. * Copy the absolute position of the bone (world space) to the result param.
  55135. * @param mesh The mesh that this bone is attached to.
  55136. * @param result The vector3 to copy the absolute position to.
  55137. */
  55138. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  55139. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  55140. };
  55141. /**
  55142. * Compute the absolute transforms of this bone and its children.
  55143. */
  55144. Bone.prototype.computeAbsoluteTransforms = function () {
  55145. if (this._parent) {
  55146. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  55147. }
  55148. else {
  55149. this._absoluteTransform.copyFrom(this._localMatrix);
  55150. var poseMatrix = this._skeleton.getPoseMatrix();
  55151. if (poseMatrix) {
  55152. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  55153. }
  55154. }
  55155. var children = this.children;
  55156. var len = children.length;
  55157. for (var i = 0; i < len; i++) {
  55158. children[i].computeAbsoluteTransforms();
  55159. }
  55160. };
  55161. Bone.prototype._syncScaleVector = function () {
  55162. var lm = this.getLocalMatrix();
  55163. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  55164. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  55165. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  55166. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  55167. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  55168. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  55169. this._scaleVector.x = xs * Math.sqrt(xsq);
  55170. this._scaleVector.y = ys * Math.sqrt(ysq);
  55171. this._scaleVector.z = zs * Math.sqrt(zsq);
  55172. if (this._parent) {
  55173. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  55174. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  55175. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  55176. }
  55177. 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);
  55178. };
  55179. /**
  55180. * Get the world direction from an axis that is in the local space of the bone.
  55181. * @param localAxis The local direction that is used to compute the world direction.
  55182. * @param mesh The mesh that this bone is attached to.
  55183. * @returns The world direction
  55184. */
  55185. Bone.prototype.getDirection = function (localAxis, mesh) {
  55186. var result = BABYLON.Vector3.Zero();
  55187. this.getDirectionToRef(localAxis, mesh, result);
  55188. return result;
  55189. };
  55190. /**
  55191. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  55192. * @param localAxis The local direction that is used to compute the world direction.
  55193. * @param mesh The mesh that this bone is attached to.
  55194. * @param result The vector3 that the world direction will be copied to.
  55195. */
  55196. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  55197. var wm;
  55198. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  55199. if (mesh) {
  55200. wm = mesh.getWorldMatrix();
  55201. }
  55202. this._skeleton.computeAbsoluteTransforms();
  55203. var mat = Bone._tmpMats[0];
  55204. mat.copyFrom(this.getAbsoluteTransform());
  55205. if (mesh) {
  55206. mat.multiplyToRef(wm, mat);
  55207. }
  55208. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  55209. result.normalize();
  55210. };
  55211. /**
  55212. * Get the euler rotation of the bone in local or world space.
  55213. * @param space The space that the rotation should be in.
  55214. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55215. * @returns The euler rotation
  55216. */
  55217. Bone.prototype.getRotation = function (space, mesh) {
  55218. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55219. var result = BABYLON.Vector3.Zero();
  55220. this.getRotationToRef(space, mesh, result);
  55221. return result;
  55222. };
  55223. /**
  55224. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  55225. * @param space The space that the rotation should be in.
  55226. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55227. * @param result The vector3 that the rotation should be copied to.
  55228. */
  55229. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  55230. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55231. var quat = Bone._tmpQuat;
  55232. this.getRotationQuaternionToRef(space, mesh, quat);
  55233. quat.toEulerAnglesToRef(result);
  55234. };
  55235. /**
  55236. * Get the quaternion rotation of the bone in either local or world space.
  55237. * @param space The space that the rotation should be in.
  55238. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55239. * @returns The quaternion rotation
  55240. */
  55241. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  55242. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55243. var result = BABYLON.Quaternion.Identity();
  55244. this.getRotationQuaternionToRef(space, mesh, result);
  55245. return result;
  55246. };
  55247. /**
  55248. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  55249. * @param space The space that the rotation should be in.
  55250. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55251. * @param result The quaternion that the rotation should be copied to.
  55252. */
  55253. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  55254. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55255. if (space == BABYLON.Space.LOCAL) {
  55256. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  55257. }
  55258. else {
  55259. var mat = Bone._tmpMats[0];
  55260. var amat = this.getAbsoluteTransform();
  55261. if (mesh) {
  55262. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  55263. }
  55264. else {
  55265. mat.copyFrom(amat);
  55266. }
  55267. mat.m[0] *= this._scalingDeterminant;
  55268. mat.m[1] *= this._scalingDeterminant;
  55269. mat.m[2] *= this._scalingDeterminant;
  55270. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  55271. }
  55272. };
  55273. /**
  55274. * Get the rotation matrix of the bone in local or world space.
  55275. * @param space The space that the rotation should be in.
  55276. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55277. * @returns The rotation matrix
  55278. */
  55279. Bone.prototype.getRotationMatrix = function (space, mesh) {
  55280. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55281. var result = BABYLON.Matrix.Identity();
  55282. this.getRotationMatrixToRef(space, mesh, result);
  55283. return result;
  55284. };
  55285. /**
  55286. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  55287. * @param space The space that the rotation should be in.
  55288. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55289. * @param result The quaternion that the rotation should be copied to.
  55290. */
  55291. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  55292. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55293. if (space == BABYLON.Space.LOCAL) {
  55294. this.getLocalMatrix().getRotationMatrixToRef(result);
  55295. }
  55296. else {
  55297. var mat = Bone._tmpMats[0];
  55298. var amat = this.getAbsoluteTransform();
  55299. if (mesh) {
  55300. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  55301. }
  55302. else {
  55303. mat.copyFrom(amat);
  55304. }
  55305. mat.m[0] *= this._scalingDeterminant;
  55306. mat.m[1] *= this._scalingDeterminant;
  55307. mat.m[2] *= this._scalingDeterminant;
  55308. mat.getRotationMatrixToRef(result);
  55309. }
  55310. };
  55311. /**
  55312. * Get the world position of a point that is in the local space of the bone.
  55313. * @param position The local position
  55314. * @param mesh The mesh that this bone is attached to.
  55315. * @returns The world position
  55316. */
  55317. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  55318. var result = BABYLON.Vector3.Zero();
  55319. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  55320. return result;
  55321. };
  55322. /**
  55323. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  55324. * @param position The local position
  55325. * @param mesh The mesh that this bone is attached to.
  55326. * @param result The vector3 that the world position should be copied to.
  55327. */
  55328. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  55329. var wm;
  55330. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  55331. if (mesh) {
  55332. wm = mesh.getWorldMatrix();
  55333. }
  55334. this._skeleton.computeAbsoluteTransforms();
  55335. var tmat = Bone._tmpMats[0];
  55336. if (mesh) {
  55337. tmat.copyFrom(this.getAbsoluteTransform());
  55338. tmat.multiplyToRef(wm, tmat);
  55339. }
  55340. else {
  55341. tmat = this.getAbsoluteTransform();
  55342. }
  55343. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  55344. };
  55345. /**
  55346. * Get the local position of a point that is in world space.
  55347. * @param position The world position
  55348. * @param mesh The mesh that this bone is attached to.
  55349. * @returns The local position
  55350. */
  55351. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  55352. var result = BABYLON.Vector3.Zero();
  55353. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  55354. return result;
  55355. };
  55356. /**
  55357. * Get the local position of a point that is in world space and copy it to the result param.
  55358. * @param position The world position
  55359. * @param mesh The mesh that this bone is attached to.
  55360. * @param result The vector3 that the local position should be copied to.
  55361. */
  55362. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  55363. var wm;
  55364. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  55365. if (mesh) {
  55366. wm = mesh.getWorldMatrix();
  55367. }
  55368. this._skeleton.computeAbsoluteTransforms();
  55369. var tmat = Bone._tmpMats[0];
  55370. tmat.copyFrom(this.getAbsoluteTransform());
  55371. if (mesh) {
  55372. tmat.multiplyToRef(wm, tmat);
  55373. }
  55374. tmat.invert();
  55375. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  55376. };
  55377. return Bone;
  55378. }(BABYLON.Node));
  55379. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  55380. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  55381. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  55382. BABYLON.Bone = Bone;
  55383. })(BABYLON || (BABYLON = {}));
  55384. //# sourceMappingURL=babylon.bone.js.map
  55385. var BABYLON;
  55386. (function (BABYLON) {
  55387. var BoneIKController = (function () {
  55388. function BoneIKController(mesh, bone, options) {
  55389. this.targetPosition = BABYLON.Vector3.Zero();
  55390. this.poleTargetPosition = BABYLON.Vector3.Zero();
  55391. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  55392. this.poleAngle = 0;
  55393. this.slerpAmount = 1;
  55394. this._bone1Quat = BABYLON.Quaternion.Identity();
  55395. this._bone1Mat = BABYLON.Matrix.Identity();
  55396. this._bone2Ang = Math.PI;
  55397. this._maxAngle = Math.PI;
  55398. this._rightHandedSystem = false;
  55399. this._bendAxis = BABYLON.Vector3.Right();
  55400. this._slerping = false;
  55401. this._adjustRoll = 0;
  55402. this._bone2 = bone;
  55403. this._bone1 = bone.getParent();
  55404. this.mesh = mesh;
  55405. var bonePos = bone.getPosition();
  55406. if (bone.getAbsoluteTransform().determinant() > 0) {
  55407. this._rightHandedSystem = true;
  55408. this._bendAxis.x = 0;
  55409. this._bendAxis.y = 0;
  55410. this._bendAxis.z = -1;
  55411. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  55412. this._adjustRoll = Math.PI * .5;
  55413. this._bendAxis.z = 1;
  55414. }
  55415. }
  55416. if (this._bone1.length) {
  55417. var boneScale1 = this._bone1.getScale();
  55418. var boneScale2 = this._bone2.getScale();
  55419. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  55420. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  55421. }
  55422. else if (this._bone1.children[0]) {
  55423. mesh.computeWorldMatrix(true);
  55424. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  55425. var pos2 = this._bone2.getAbsolutePosition(mesh);
  55426. var pos3 = this._bone1.getAbsolutePosition(mesh);
  55427. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  55428. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  55429. }
  55430. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  55431. this.maxAngle = Math.PI;
  55432. if (options) {
  55433. if (options.targetMesh) {
  55434. this.targetMesh = options.targetMesh;
  55435. this.targetMesh.computeWorldMatrix(true);
  55436. }
  55437. if (options.poleTargetMesh) {
  55438. this.poleTargetMesh = options.poleTargetMesh;
  55439. this.poleTargetMesh.computeWorldMatrix(true);
  55440. }
  55441. else if (options.poleTargetBone) {
  55442. this.poleTargetBone = options.poleTargetBone;
  55443. }
  55444. else if (this._bone1.getParent()) {
  55445. this.poleTargetBone = this._bone1.getParent();
  55446. }
  55447. if (options.poleTargetLocalOffset) {
  55448. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  55449. }
  55450. if (options.poleAngle) {
  55451. this.poleAngle = options.poleAngle;
  55452. }
  55453. if (options.bendAxis) {
  55454. this._bendAxis.copyFrom(options.bendAxis);
  55455. }
  55456. if (options.maxAngle) {
  55457. this.maxAngle = options.maxAngle;
  55458. }
  55459. if (options.slerpAmount) {
  55460. this.slerpAmount = options.slerpAmount;
  55461. }
  55462. }
  55463. }
  55464. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  55465. get: function () {
  55466. return this._maxAngle;
  55467. },
  55468. set: function (value) {
  55469. this._setMaxAngle(value);
  55470. },
  55471. enumerable: true,
  55472. configurable: true
  55473. });
  55474. BoneIKController.prototype._setMaxAngle = function (ang) {
  55475. if (ang < 0) {
  55476. ang = 0;
  55477. }
  55478. if (ang > Math.PI || ang == undefined) {
  55479. ang = Math.PI;
  55480. }
  55481. this._maxAngle = ang;
  55482. var a = this._bone1Length;
  55483. var b = this._bone2Length;
  55484. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  55485. };
  55486. BoneIKController.prototype.update = function () {
  55487. var bone1 = this._bone1;
  55488. var target = this.targetPosition;
  55489. var poleTarget = this.poleTargetPosition;
  55490. var mat1 = BoneIKController._tmpMats[0];
  55491. var mat2 = BoneIKController._tmpMats[1];
  55492. if (this.targetMesh) {
  55493. target.copyFrom(this.targetMesh.getAbsolutePosition());
  55494. }
  55495. if (this.poleTargetBone) {
  55496. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  55497. }
  55498. else if (this.poleTargetMesh) {
  55499. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  55500. }
  55501. var bonePos = BoneIKController._tmpVecs[0];
  55502. var zaxis = BoneIKController._tmpVecs[1];
  55503. var xaxis = BoneIKController._tmpVecs[2];
  55504. var yaxis = BoneIKController._tmpVecs[3];
  55505. var upAxis = BoneIKController._tmpVecs[4];
  55506. var _tmpQuat = BoneIKController._tmpQuat;
  55507. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  55508. poleTarget.subtractToRef(bonePos, upAxis);
  55509. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  55510. upAxis.y = 1;
  55511. }
  55512. else {
  55513. upAxis.normalize();
  55514. }
  55515. target.subtractToRef(bonePos, yaxis);
  55516. yaxis.normalize();
  55517. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  55518. zaxis.normalize();
  55519. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  55520. xaxis.normalize();
  55521. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  55522. var a = this._bone1Length;
  55523. var b = this._bone2Length;
  55524. var c = BABYLON.Vector3.Distance(bonePos, target);
  55525. if (this._maxReach > 0) {
  55526. c = Math.min(this._maxReach, c);
  55527. }
  55528. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  55529. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  55530. if (acosa > 1) {
  55531. acosa = 1;
  55532. }
  55533. if (acosb > 1) {
  55534. acosb = 1;
  55535. }
  55536. if (acosa < -1) {
  55537. acosa = -1;
  55538. }
  55539. if (acosb < -1) {
  55540. acosb = -1;
  55541. }
  55542. var angA = Math.acos(acosa);
  55543. var angB = Math.acos(acosb);
  55544. var angC = -angA - angB;
  55545. if (this._rightHandedSystem) {
  55546. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  55547. mat2.multiplyToRef(mat1, mat1);
  55548. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  55549. mat2.multiplyToRef(mat1, mat1);
  55550. }
  55551. else {
  55552. var _tmpVec = BoneIKController._tmpVecs[5];
  55553. _tmpVec.copyFrom(this._bendAxis);
  55554. _tmpVec.x *= -1;
  55555. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  55556. mat2.multiplyToRef(mat1, mat1);
  55557. }
  55558. if (this.poleAngle) {
  55559. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  55560. mat1.multiplyToRef(mat2, mat1);
  55561. }
  55562. if (this.slerpAmount < 1) {
  55563. if (!this._slerping) {
  55564. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  55565. }
  55566. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  55567. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  55568. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  55569. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  55570. this._slerping = true;
  55571. }
  55572. else {
  55573. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  55574. this._bone1Mat.copyFrom(mat1);
  55575. this._slerping = false;
  55576. }
  55577. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  55578. this._bone2Ang = angC;
  55579. };
  55580. return BoneIKController;
  55581. }());
  55582. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  55583. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  55584. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  55585. BABYLON.BoneIKController = BoneIKController;
  55586. })(BABYLON || (BABYLON = {}));
  55587. //# sourceMappingURL=babylon.boneIKController.js.map
  55588. var BABYLON;
  55589. (function (BABYLON) {
  55590. var BoneLookController = (function () {
  55591. /**
  55592. * Create a BoneLookController
  55593. * @param mesh the mesh that the bone belongs to
  55594. * @param bone the bone that will be looking to the target
  55595. * @param target the target Vector3 to look at
  55596. * @param settings optional settings:
  55597. * - maxYaw: the maximum angle the bone will yaw to
  55598. * - minYaw: the minimum angle the bone will yaw to
  55599. * - maxPitch: the maximum angle the bone will pitch to
  55600. * - minPitch: the minimum angle the bone will yaw to
  55601. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  55602. * - upAxis: the up axis of the coordinate system
  55603. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  55604. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  55605. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  55606. * - adjustYaw: used to make an adjustment to the yaw of the bone
  55607. * - adjustPitch: used to make an adjustment to the pitch of the bone
  55608. * - adjustRoll: used to make an adjustment to the roll of the bone
  55609. **/
  55610. function BoneLookController(mesh, bone, target, options) {
  55611. /**
  55612. * The up axis of the coordinate system that is used when the bone is rotated.
  55613. */
  55614. this.upAxis = BABYLON.Vector3.Up();
  55615. /**
  55616. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  55617. */
  55618. this.upAxisSpace = BABYLON.Space.LOCAL;
  55619. /**
  55620. * Used to make an adjustment to the yaw of the bone.
  55621. */
  55622. this.adjustYaw = 0;
  55623. /**
  55624. * Used to make an adjustment to the pitch of the bone.
  55625. */
  55626. this.adjustPitch = 0;
  55627. /**
  55628. * Used to make an adjustment to the roll of the bone.
  55629. */
  55630. this.adjustRoll = 0;
  55631. /**
  55632. * 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).
  55633. */
  55634. this.slerpAmount = 1;
  55635. this._boneQuat = BABYLON.Quaternion.Identity();
  55636. this._slerping = false;
  55637. this._firstFrameSkipped = false;
  55638. this._fowardAxis = BABYLON.Vector3.Forward();
  55639. this.mesh = mesh;
  55640. this.bone = bone;
  55641. this.target = target;
  55642. if (options) {
  55643. if (options.adjustYaw) {
  55644. this.adjustYaw = options.adjustYaw;
  55645. }
  55646. if (options.adjustPitch) {
  55647. this.adjustPitch = options.adjustPitch;
  55648. }
  55649. if (options.adjustRoll) {
  55650. this.adjustRoll = options.adjustRoll;
  55651. }
  55652. if (options.maxYaw != null) {
  55653. this.maxYaw = options.maxYaw;
  55654. }
  55655. else {
  55656. this.maxYaw = Math.PI;
  55657. }
  55658. if (options.minYaw != null) {
  55659. this.minYaw = options.minYaw;
  55660. }
  55661. else {
  55662. this.minYaw = -Math.PI;
  55663. }
  55664. if (options.maxPitch != null) {
  55665. this.maxPitch = options.maxPitch;
  55666. }
  55667. else {
  55668. this.maxPitch = Math.PI;
  55669. }
  55670. if (options.minPitch != null) {
  55671. this.minPitch = options.minPitch;
  55672. }
  55673. else {
  55674. this.minPitch = -Math.PI;
  55675. }
  55676. if (options.slerpAmount != null) {
  55677. this.slerpAmount = options.slerpAmount;
  55678. }
  55679. if (options.upAxis != null) {
  55680. this.upAxis = options.upAxis;
  55681. }
  55682. if (options.upAxisSpace != null) {
  55683. this.upAxisSpace = options.upAxisSpace;
  55684. }
  55685. if (options.yawAxis != null || options.pitchAxis != null) {
  55686. var newYawAxis = BABYLON.Axis.Y;
  55687. var newPitchAxis = BABYLON.Axis.X;
  55688. if (options.yawAxis != null) {
  55689. newYawAxis = options.yawAxis.clone();
  55690. newYawAxis.normalize();
  55691. }
  55692. if (options.pitchAxis != null) {
  55693. newPitchAxis = options.pitchAxis.clone();
  55694. newPitchAxis.normalize();
  55695. }
  55696. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  55697. this._transformYawPitch = BABYLON.Matrix.Identity();
  55698. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  55699. this._transformYawPitchInv = this._transformYawPitch.clone();
  55700. this._transformYawPitch.invert();
  55701. }
  55702. }
  55703. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  55704. this.upAxisSpace = BABYLON.Space.LOCAL;
  55705. }
  55706. }
  55707. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  55708. /**
  55709. * Get/set the minimum yaw angle that the bone can look to.
  55710. */
  55711. get: function () {
  55712. return this._minYaw;
  55713. },
  55714. set: function (value) {
  55715. this._minYaw = value;
  55716. this._minYawSin = Math.sin(value);
  55717. this._minYawCos = Math.cos(value);
  55718. if (this._maxYaw != null) {
  55719. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  55720. this._yawRange = this._maxYaw - this._minYaw;
  55721. }
  55722. },
  55723. enumerable: true,
  55724. configurable: true
  55725. });
  55726. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  55727. /**
  55728. * Get/set the maximum yaw angle that the bone can look to.
  55729. */
  55730. get: function () {
  55731. return this._maxYaw;
  55732. },
  55733. set: function (value) {
  55734. this._maxYaw = value;
  55735. this._maxYawSin = Math.sin(value);
  55736. this._maxYawCos = Math.cos(value);
  55737. if (this._minYaw != null) {
  55738. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  55739. this._yawRange = this._maxYaw - this._minYaw;
  55740. }
  55741. },
  55742. enumerable: true,
  55743. configurable: true
  55744. });
  55745. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  55746. /**
  55747. * Get/set the minimum pitch angle that the bone can look to.
  55748. */
  55749. get: function () {
  55750. return this._minPitch;
  55751. },
  55752. set: function (value) {
  55753. this._minPitch = value;
  55754. this._minPitchTan = Math.tan(value);
  55755. },
  55756. enumerable: true,
  55757. configurable: true
  55758. });
  55759. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  55760. /**
  55761. * Get/set the maximum pitch angle that the bone can look to.
  55762. */
  55763. get: function () {
  55764. return this._maxPitch;
  55765. },
  55766. set: function (value) {
  55767. this._maxPitch = value;
  55768. this._maxPitchTan = Math.tan(value);
  55769. },
  55770. enumerable: true,
  55771. configurable: true
  55772. });
  55773. /**
  55774. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  55775. */
  55776. BoneLookController.prototype.update = function () {
  55777. //skip the first frame when slerping so that the mesh rotation is correct
  55778. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  55779. this._firstFrameSkipped = true;
  55780. return;
  55781. }
  55782. var bone = this.bone;
  55783. var bonePos = BoneLookController._tmpVecs[0];
  55784. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  55785. var target = this.target;
  55786. var _tmpMat1 = BoneLookController._tmpMats[0];
  55787. var _tmpMat2 = BoneLookController._tmpMats[1];
  55788. var mesh = this.mesh;
  55789. var parentBone = bone.getParent();
  55790. var upAxis = BoneLookController._tmpVecs[1];
  55791. upAxis.copyFrom(this.upAxis);
  55792. if (this.upAxisSpace == BABYLON.Space.BONE) {
  55793. if (this._transformYawPitch) {
  55794. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  55795. }
  55796. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  55797. }
  55798. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  55799. mesh.getDirectionToRef(upAxis, upAxis);
  55800. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  55801. upAxis.normalize();
  55802. }
  55803. }
  55804. var checkYaw = false;
  55805. var checkPitch = false;
  55806. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  55807. checkYaw = true;
  55808. }
  55809. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  55810. checkPitch = true;
  55811. }
  55812. if (checkYaw || checkPitch) {
  55813. var spaceMat = BoneLookController._tmpMats[2];
  55814. var spaceMatInv = BoneLookController._tmpMats[3];
  55815. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1) {
  55816. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  55817. }
  55818. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  55819. spaceMat.copyFrom(mesh.getWorldMatrix());
  55820. }
  55821. else {
  55822. var forwardAxis = BoneLookController._tmpVecs[2];
  55823. forwardAxis.copyFrom(this._fowardAxis);
  55824. if (this._transformYawPitch) {
  55825. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  55826. }
  55827. if (parentBone) {
  55828. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  55829. }
  55830. else {
  55831. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  55832. }
  55833. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  55834. rightAxis.normalize();
  55835. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  55836. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  55837. }
  55838. spaceMat.invertToRef(spaceMatInv);
  55839. var xzlen;
  55840. if (checkPitch) {
  55841. var localTarget = BoneLookController._tmpVecs[3];
  55842. target.subtractToRef(bonePos, localTarget);
  55843. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  55844. var xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  55845. var pitch = Math.atan2(localTarget.y, xzlen);
  55846. var newPitch = pitch;
  55847. if (pitch > this._maxPitch) {
  55848. localTarget.y = this._maxPitchTan * xzlen;
  55849. newPitch = this._maxPitch;
  55850. }
  55851. else if (pitch < this._minPitch) {
  55852. localTarget.y = this._minPitchTan * xzlen;
  55853. newPitch = this._minPitch;
  55854. }
  55855. if (pitch != newPitch) {
  55856. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  55857. localTarget.addInPlace(bonePos);
  55858. target = localTarget;
  55859. }
  55860. }
  55861. if (checkYaw) {
  55862. var localTarget = BoneLookController._tmpVecs[4];
  55863. target.subtractToRef(bonePos, localTarget);
  55864. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  55865. var yaw = Math.atan2(localTarget.x, localTarget.z);
  55866. var newYaw = yaw;
  55867. if (yaw > this._maxYaw || yaw < this._minYaw) {
  55868. if (xzlen == null) {
  55869. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  55870. }
  55871. if (this._yawRange > Math.PI) {
  55872. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  55873. localTarget.z = this._maxYawCos * xzlen;
  55874. localTarget.x = this._maxYawSin * xzlen;
  55875. newYaw = this._maxYaw;
  55876. }
  55877. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  55878. localTarget.z = this._minYawCos * xzlen;
  55879. localTarget.x = this._minYawSin * xzlen;
  55880. newYaw = this._minYaw;
  55881. }
  55882. }
  55883. else {
  55884. if (yaw > this._maxYaw) {
  55885. localTarget.z = this._maxYawCos * xzlen;
  55886. localTarget.x = this._maxYawSin * xzlen;
  55887. newYaw = this._maxYaw;
  55888. }
  55889. else if (yaw < this._minYaw) {
  55890. localTarget.z = this._minYawCos * xzlen;
  55891. localTarget.x = this._minYawSin * xzlen;
  55892. newYaw = this._minYaw;
  55893. }
  55894. }
  55895. }
  55896. if (this._slerping && this._yawRange > Math.PI) {
  55897. //are we going to be crossing into the min/max region?
  55898. var boneFwd = BoneLookController._tmpVecs[8];
  55899. boneFwd.copyFrom(BABYLON.Axis.Z);
  55900. if (this._transformYawPitch) {
  55901. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  55902. }
  55903. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  55904. this._boneQuat.toRotationMatrix(boneRotMat);
  55905. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  55906. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  55907. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  55908. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  55909. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  55910. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  55911. if (angBtwTar > angBtwMidYaw) {
  55912. if (xzlen == null) {
  55913. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  55914. }
  55915. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  55916. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  55917. if (angBtwMin < angBtwMax) {
  55918. newYaw = boneYaw + Math.PI * .75;
  55919. localTarget.z = Math.cos(newYaw) * xzlen;
  55920. localTarget.x = Math.sin(newYaw) * xzlen;
  55921. }
  55922. else {
  55923. newYaw = boneYaw - Math.PI * .75;
  55924. localTarget.z = Math.cos(newYaw) * xzlen;
  55925. localTarget.x = Math.sin(newYaw) * xzlen;
  55926. }
  55927. }
  55928. }
  55929. if (yaw != newYaw) {
  55930. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  55931. localTarget.addInPlace(bonePos);
  55932. target = localTarget;
  55933. }
  55934. }
  55935. }
  55936. var zaxis = BoneLookController._tmpVecs[5];
  55937. var xaxis = BoneLookController._tmpVecs[6];
  55938. var yaxis = BoneLookController._tmpVecs[7];
  55939. var _tmpQuat = BoneLookController._tmpQuat;
  55940. target.subtractToRef(bonePos, zaxis);
  55941. zaxis.normalize();
  55942. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  55943. xaxis.normalize();
  55944. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  55945. yaxis.normalize();
  55946. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  55947. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  55948. return;
  55949. }
  55950. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  55951. return;
  55952. }
  55953. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  55954. return;
  55955. }
  55956. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  55957. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  55958. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  55959. }
  55960. if (this.slerpAmount < 1) {
  55961. if (!this._slerping) {
  55962. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  55963. }
  55964. if (this._transformYawPitch) {
  55965. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  55966. }
  55967. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  55968. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  55969. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  55970. this._slerping = true;
  55971. }
  55972. else {
  55973. if (this._transformYawPitch) {
  55974. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  55975. }
  55976. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  55977. this._slerping = false;
  55978. }
  55979. };
  55980. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  55981. var angDiff = ang2 - ang1;
  55982. angDiff %= Math.PI * 2;
  55983. if (angDiff > Math.PI) {
  55984. angDiff -= Math.PI * 2;
  55985. }
  55986. else if (angDiff < -Math.PI) {
  55987. angDiff += Math.PI * 2;
  55988. }
  55989. return angDiff;
  55990. };
  55991. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  55992. ang1 %= (2 * Math.PI);
  55993. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  55994. ang2 %= (2 * Math.PI);
  55995. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  55996. var ab = 0;
  55997. if (ang1 < ang2) {
  55998. ab = ang2 - ang1;
  55999. }
  56000. else {
  56001. ab = ang1 - ang2;
  56002. }
  56003. if (ab > Math.PI) {
  56004. ab = Math.PI * 2 - ab;
  56005. }
  56006. return ab;
  56007. };
  56008. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  56009. ang %= (2 * Math.PI);
  56010. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  56011. ang1 %= (2 * Math.PI);
  56012. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  56013. ang2 %= (2 * Math.PI);
  56014. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  56015. if (ang1 < ang2) {
  56016. if (ang > ang1 && ang < ang2) {
  56017. return true;
  56018. }
  56019. }
  56020. else {
  56021. if (ang > ang2 && ang < ang1) {
  56022. return true;
  56023. }
  56024. }
  56025. return false;
  56026. };
  56027. return BoneLookController;
  56028. }());
  56029. 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()];
  56030. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  56031. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  56032. BABYLON.BoneLookController = BoneLookController;
  56033. })(BABYLON || (BABYLON = {}));
  56034. //# sourceMappingURL=babylon.boneLookController.js.map
  56035. var BABYLON;
  56036. (function (BABYLON) {
  56037. var Skeleton = (function () {
  56038. function Skeleton(name, id, scene) {
  56039. this.name = name;
  56040. this.id = id;
  56041. this.bones = new Array();
  56042. this.needInitialSkinMatrix = false;
  56043. this._isDirty = true;
  56044. this._meshesWithPoseMatrix = new Array();
  56045. this._identity = BABYLON.Matrix.Identity();
  56046. this._ranges = {};
  56047. this._lastAbsoluteTransformsUpdateId = -1;
  56048. // Events
  56049. /**
  56050. * An event triggered before computing the skeleton's matrices
  56051. * @type {BABYLON.Observable}
  56052. */
  56053. this.onBeforeComputeObservable = new BABYLON.Observable();
  56054. this.bones = [];
  56055. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56056. scene.skeletons.push(this);
  56057. //make sure it will recalculate the matrix next time prepare is called.
  56058. this._isDirty = true;
  56059. }
  56060. // Members
  56061. Skeleton.prototype.getTransformMatrices = function (mesh) {
  56062. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  56063. return mesh._bonesTransformMatrices;
  56064. }
  56065. if (!this._transformMatrices) {
  56066. this.prepare();
  56067. }
  56068. return this._transformMatrices;
  56069. };
  56070. Skeleton.prototype.getScene = function () {
  56071. return this._scene;
  56072. };
  56073. // Methods
  56074. /**
  56075. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  56076. */
  56077. Skeleton.prototype.toString = function (fullDetails) {
  56078. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  56079. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  56080. if (fullDetails) {
  56081. ret += ", Ranges: {";
  56082. var first = true;
  56083. for (var name_1 in this._ranges) {
  56084. if (first) {
  56085. ret += ", ";
  56086. first = false;
  56087. }
  56088. ret += name_1;
  56089. }
  56090. ret += "}";
  56091. }
  56092. return ret;
  56093. };
  56094. /**
  56095. * Get bone's index searching by name
  56096. * @param {string} name is bone's name to search for
  56097. * @return {number} Indice of the bone. Returns -1 if not found
  56098. */
  56099. Skeleton.prototype.getBoneIndexByName = function (name) {
  56100. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  56101. if (this.bones[boneIndex].name === name) {
  56102. return boneIndex;
  56103. }
  56104. }
  56105. return -1;
  56106. };
  56107. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  56108. // check name not already in use
  56109. if (!this._ranges[name]) {
  56110. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  56111. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  56112. if (this.bones[i].animations[0]) {
  56113. this.bones[i].animations[0].createRange(name, from, to);
  56114. }
  56115. }
  56116. }
  56117. };
  56118. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  56119. if (deleteFrames === void 0) { deleteFrames = true; }
  56120. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  56121. if (this.bones[i].animations[0]) {
  56122. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  56123. }
  56124. }
  56125. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  56126. };
  56127. Skeleton.prototype.getAnimationRange = function (name) {
  56128. return this._ranges[name];
  56129. };
  56130. /**
  56131. * Returns as an Array, all AnimationRanges defined on this skeleton
  56132. */
  56133. Skeleton.prototype.getAnimationRanges = function () {
  56134. var animationRanges = [];
  56135. var name;
  56136. var i = 0;
  56137. for (name in this._ranges) {
  56138. animationRanges[i] = this._ranges[name];
  56139. i++;
  56140. }
  56141. return animationRanges;
  56142. };
  56143. /**
  56144. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  56145. */
  56146. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  56147. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  56148. if (this._ranges[name] || !source.getAnimationRange(name)) {
  56149. return false;
  56150. }
  56151. var ret = true;
  56152. var frameOffset = this._getHighestAnimationFrame() + 1;
  56153. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  56154. var boneDict = {};
  56155. var sourceBones = source.bones;
  56156. var nBones;
  56157. var i;
  56158. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  56159. boneDict[sourceBones[i].name] = sourceBones[i];
  56160. }
  56161. if (this.bones.length !== sourceBones.length) {
  56162. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  56163. ret = false;
  56164. }
  56165. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  56166. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  56167. var boneName = this.bones[i].name;
  56168. var sourceBone = boneDict[boneName];
  56169. if (sourceBone) {
  56170. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  56171. }
  56172. else {
  56173. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  56174. ret = false;
  56175. }
  56176. }
  56177. // do not call createAnimationRange(), since it also is done to bones, which was already done
  56178. var range = source.getAnimationRange(name);
  56179. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  56180. return ret;
  56181. };
  56182. Skeleton.prototype.returnToRest = function () {
  56183. for (var index = 0; index < this.bones.length; index++) {
  56184. this.bones[index].returnToRest();
  56185. }
  56186. };
  56187. Skeleton.prototype._getHighestAnimationFrame = function () {
  56188. var ret = 0;
  56189. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  56190. if (this.bones[i].animations[0]) {
  56191. var highest = this.bones[i].animations[0].getHighestFrame();
  56192. if (ret < highest) {
  56193. ret = highest;
  56194. }
  56195. }
  56196. }
  56197. return ret;
  56198. };
  56199. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  56200. var range = this.getAnimationRange(name);
  56201. if (!range) {
  56202. return null;
  56203. }
  56204. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  56205. };
  56206. Skeleton.prototype._markAsDirty = function () {
  56207. this._isDirty = true;
  56208. };
  56209. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  56210. this._meshesWithPoseMatrix.push(mesh);
  56211. };
  56212. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  56213. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  56214. if (index > -1) {
  56215. this._meshesWithPoseMatrix.splice(index, 1);
  56216. }
  56217. };
  56218. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  56219. this.onBeforeComputeObservable.notifyObservers(this);
  56220. for (var index = 0; index < this.bones.length; index++) {
  56221. var bone = this.bones[index];
  56222. var parentBone = bone.getParent();
  56223. if (parentBone) {
  56224. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  56225. }
  56226. else {
  56227. if (initialSkinMatrix) {
  56228. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  56229. }
  56230. else {
  56231. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  56232. }
  56233. }
  56234. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  56235. }
  56236. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  56237. };
  56238. Skeleton.prototype.prepare = function () {
  56239. if (!this._isDirty) {
  56240. return;
  56241. }
  56242. if (this.needInitialSkinMatrix) {
  56243. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  56244. var mesh = this._meshesWithPoseMatrix[index];
  56245. var poseMatrix = mesh.getPoseMatrix();
  56246. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  56247. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  56248. }
  56249. if (this._synchronizedWithMesh !== mesh) {
  56250. this._synchronizedWithMesh = mesh;
  56251. // Prepare bones
  56252. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  56253. var bone = this.bones[boneIndex];
  56254. if (!bone.getParent()) {
  56255. var matrix = bone.getBaseMatrix();
  56256. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  56257. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  56258. }
  56259. }
  56260. }
  56261. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  56262. }
  56263. }
  56264. else {
  56265. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  56266. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  56267. }
  56268. this._computeTransformMatrices(this._transformMatrices, null);
  56269. }
  56270. this._isDirty = false;
  56271. this._scene._activeBones.addCount(this.bones.length, false);
  56272. };
  56273. Skeleton.prototype.getAnimatables = function () {
  56274. if (!this._animatables || this._animatables.length !== this.bones.length) {
  56275. this._animatables = [];
  56276. for (var index = 0; index < this.bones.length; index++) {
  56277. this._animatables.push(this.bones[index]);
  56278. }
  56279. }
  56280. return this._animatables;
  56281. };
  56282. Skeleton.prototype.clone = function (name, id) {
  56283. var result = new Skeleton(name, id || name, this._scene);
  56284. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  56285. for (var index = 0; index < this.bones.length; index++) {
  56286. var source = this.bones[index];
  56287. var parentBone = null;
  56288. if (source.getParent()) {
  56289. var parentIndex = this.bones.indexOf(source.getParent());
  56290. parentBone = result.bones[parentIndex];
  56291. }
  56292. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  56293. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  56294. }
  56295. if (this._ranges) {
  56296. result._ranges = {};
  56297. for (var rangeName in this._ranges) {
  56298. result._ranges[rangeName] = this._ranges[rangeName].clone();
  56299. }
  56300. }
  56301. this._isDirty = true;
  56302. return result;
  56303. };
  56304. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  56305. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  56306. this.bones.forEach(function (bone) {
  56307. bone.animations.forEach(function (animation) {
  56308. animation.enableBlending = true;
  56309. animation.blendingSpeed = blendingSpeed;
  56310. });
  56311. });
  56312. };
  56313. Skeleton.prototype.dispose = function () {
  56314. this._meshesWithPoseMatrix = [];
  56315. // Animations
  56316. this.getScene().stopAnimation(this);
  56317. // Remove from scene
  56318. this.getScene().removeSkeleton(this);
  56319. };
  56320. Skeleton.prototype.serialize = function () {
  56321. var serializationObject = {};
  56322. serializationObject.name = this.name;
  56323. serializationObject.id = this.id;
  56324. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  56325. serializationObject.bones = [];
  56326. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  56327. for (var index = 0; index < this.bones.length; index++) {
  56328. var bone = this.bones[index];
  56329. var serializedBone = {
  56330. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  56331. name: bone.name,
  56332. matrix: bone.getBaseMatrix().toArray(),
  56333. rest: bone.getRestPose().toArray()
  56334. };
  56335. serializationObject.bones.push(serializedBone);
  56336. if (bone.length) {
  56337. serializedBone.length = bone.length;
  56338. }
  56339. if (bone.animations && bone.animations.length > 0) {
  56340. serializedBone.animation = bone.animations[0].serialize();
  56341. }
  56342. serializationObject.ranges = [];
  56343. for (var name in this._ranges) {
  56344. var range = {};
  56345. range.name = name;
  56346. range.from = this._ranges[name].from;
  56347. range.to = this._ranges[name].to;
  56348. serializationObject.ranges.push(range);
  56349. }
  56350. }
  56351. return serializationObject;
  56352. };
  56353. Skeleton.Parse = function (parsedSkeleton, scene) {
  56354. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  56355. if (parsedSkeleton.dimensionsAtRest) {
  56356. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  56357. }
  56358. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  56359. var index;
  56360. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  56361. var parsedBone = parsedSkeleton.bones[index];
  56362. var parentBone = null;
  56363. if (parsedBone.parentBoneIndex > -1) {
  56364. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  56365. }
  56366. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  56367. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  56368. if (parsedBone.length) {
  56369. bone.length = parsedBone.length;
  56370. }
  56371. if (parsedBone.animation) {
  56372. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  56373. }
  56374. }
  56375. // placed after bones, so createAnimationRange can cascade down
  56376. if (parsedSkeleton.ranges) {
  56377. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  56378. var data = parsedSkeleton.ranges[index];
  56379. skeleton.createAnimationRange(data.name, data.from, data.to);
  56380. }
  56381. }
  56382. return skeleton;
  56383. };
  56384. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  56385. if (forceUpdate === void 0) { forceUpdate = false; }
  56386. var renderId = this._scene.getRenderId();
  56387. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  56388. this.bones[0].computeAbsoluteTransforms();
  56389. this._lastAbsoluteTransformsUpdateId = renderId;
  56390. }
  56391. };
  56392. Skeleton.prototype.getPoseMatrix = function () {
  56393. var poseMatrix;
  56394. if (this._meshesWithPoseMatrix.length > 0) {
  56395. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  56396. }
  56397. return poseMatrix;
  56398. };
  56399. return Skeleton;
  56400. }());
  56401. BABYLON.Skeleton = Skeleton;
  56402. })(BABYLON || (BABYLON = {}));
  56403. //# sourceMappingURL=babylon.skeleton.js.map
  56404. var BABYLON;
  56405. (function (BABYLON) {
  56406. var SphericalPolynomial = (function () {
  56407. function SphericalPolynomial() {
  56408. this.x = BABYLON.Vector3.Zero();
  56409. this.y = BABYLON.Vector3.Zero();
  56410. this.z = BABYLON.Vector3.Zero();
  56411. this.xx = BABYLON.Vector3.Zero();
  56412. this.yy = BABYLON.Vector3.Zero();
  56413. this.zz = BABYLON.Vector3.Zero();
  56414. this.xy = BABYLON.Vector3.Zero();
  56415. this.yz = BABYLON.Vector3.Zero();
  56416. this.zx = BABYLON.Vector3.Zero();
  56417. }
  56418. SphericalPolynomial.prototype.addAmbient = function (color) {
  56419. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  56420. this.xx = this.xx.add(colorVector);
  56421. this.yy = this.yy.add(colorVector);
  56422. this.zz = this.zz.add(colorVector);
  56423. };
  56424. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  56425. var result = new SphericalPolynomial();
  56426. result.x = harmonics.L11.scale(1.02333);
  56427. result.y = harmonics.L1_1.scale(1.02333);
  56428. result.z = harmonics.L10.scale(1.02333);
  56429. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  56430. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  56431. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  56432. result.yz = harmonics.L2_1.scale(0.858086);
  56433. result.zx = harmonics.L21.scale(0.858086);
  56434. result.xy = harmonics.L2_2.scale(0.858086);
  56435. result.scale(1.0 / Math.PI);
  56436. return result;
  56437. };
  56438. SphericalPolynomial.prototype.scale = function (scale) {
  56439. this.x = this.x.scale(scale);
  56440. this.y = this.y.scale(scale);
  56441. this.z = this.z.scale(scale);
  56442. this.xx = this.xx.scale(scale);
  56443. this.yy = this.yy.scale(scale);
  56444. this.zz = this.zz.scale(scale);
  56445. this.yz = this.yz.scale(scale);
  56446. this.zx = this.zx.scale(scale);
  56447. this.xy = this.xy.scale(scale);
  56448. };
  56449. return SphericalPolynomial;
  56450. }());
  56451. BABYLON.SphericalPolynomial = SphericalPolynomial;
  56452. var SphericalHarmonics = (function () {
  56453. function SphericalHarmonics() {
  56454. this.L00 = BABYLON.Vector3.Zero();
  56455. this.L1_1 = BABYLON.Vector3.Zero();
  56456. this.L10 = BABYLON.Vector3.Zero();
  56457. this.L11 = BABYLON.Vector3.Zero();
  56458. this.L2_2 = BABYLON.Vector3.Zero();
  56459. this.L2_1 = BABYLON.Vector3.Zero();
  56460. this.L20 = BABYLON.Vector3.Zero();
  56461. this.L21 = BABYLON.Vector3.Zero();
  56462. this.L22 = BABYLON.Vector3.Zero();
  56463. }
  56464. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  56465. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  56466. var c = colorVector.scale(deltaSolidAngle);
  56467. this.L00 = this.L00.add(c.scale(0.282095));
  56468. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  56469. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  56470. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  56471. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  56472. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  56473. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  56474. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  56475. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  56476. };
  56477. SphericalHarmonics.prototype.scale = function (scale) {
  56478. this.L00 = this.L00.scale(scale);
  56479. this.L1_1 = this.L1_1.scale(scale);
  56480. this.L10 = this.L10.scale(scale);
  56481. this.L11 = this.L11.scale(scale);
  56482. this.L2_2 = this.L2_2.scale(scale);
  56483. this.L2_1 = this.L2_1.scale(scale);
  56484. this.L20 = this.L20.scale(scale);
  56485. this.L21 = this.L21.scale(scale);
  56486. this.L22 = this.L22.scale(scale);
  56487. };
  56488. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  56489. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  56490. //
  56491. // E_lm = A_l * L_lm
  56492. //
  56493. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  56494. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  56495. // the scaling factors are given in equation 9.
  56496. // Constant (Band 0)
  56497. this.L00 = this.L00.scale(3.141593);
  56498. // Linear (Band 1)
  56499. this.L1_1 = this.L1_1.scale(2.094395);
  56500. this.L10 = this.L10.scale(2.094395);
  56501. this.L11 = this.L11.scale(2.094395);
  56502. // Quadratic (Band 2)
  56503. this.L2_2 = this.L2_2.scale(0.785398);
  56504. this.L2_1 = this.L2_1.scale(0.785398);
  56505. this.L20 = this.L20.scale(0.785398);
  56506. this.L21 = this.L21.scale(0.785398);
  56507. this.L22 = this.L22.scale(0.785398);
  56508. };
  56509. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  56510. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  56511. // L = (1/pi) * E * rho
  56512. //
  56513. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  56514. this.scale(1.0 / Math.PI);
  56515. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  56516. // (The pixel shader must apply albedo after texture fetches, etc).
  56517. };
  56518. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  56519. var result = new SphericalHarmonics();
  56520. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  56521. result.L1_1 = polynomial.y.scale(0.977204);
  56522. result.L10 = polynomial.z.scale(0.977204);
  56523. result.L11 = polynomial.x.scale(0.977204);
  56524. result.L2_2 = polynomial.xy.scale(1.16538);
  56525. result.L2_1 = polynomial.yz.scale(1.16538);
  56526. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  56527. result.L21 = polynomial.zx.scale(1.16538);
  56528. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  56529. result.scale(Math.PI);
  56530. return result;
  56531. };
  56532. return SphericalHarmonics;
  56533. }());
  56534. BABYLON.SphericalHarmonics = SphericalHarmonics;
  56535. })(BABYLON || (BABYLON = {}));
  56536. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  56537. var BABYLON;
  56538. (function (BABYLON) {
  56539. var Internals;
  56540. (function (Internals) {
  56541. var FileFaceOrientation = (function () {
  56542. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  56543. this.name = name;
  56544. this.worldAxisForNormal = worldAxisForNormal;
  56545. this.worldAxisForFileX = worldAxisForFileX;
  56546. this.worldAxisForFileY = worldAxisForFileY;
  56547. }
  56548. return FileFaceOrientation;
  56549. }());
  56550. ;
  56551. /**
  56552. * Helper class dealing with the extraction of spherical polynomial dataArray
  56553. * from a cube map.
  56554. */
  56555. var CubeMapToSphericalPolynomialTools = (function () {
  56556. function CubeMapToSphericalPolynomialTools() {
  56557. }
  56558. /**
  56559. * Converts a texture to the according Spherical Polynomial data.
  56560. * This extracts the first 3 orders only as they are the only one used in the lighting.
  56561. *
  56562. * @param texture The texture to extract the information from.
  56563. * @return The Spherical Polynomial data.
  56564. */
  56565. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  56566. if (!texture.isCube) {
  56567. // Only supports cube Textures currently.
  56568. return null;
  56569. }
  56570. var size = texture.getSize().width;
  56571. var right = texture.readPixels(0);
  56572. var left = texture.readPixels(1);
  56573. var up;
  56574. var down;
  56575. if (texture.isRenderTarget) {
  56576. up = texture.readPixels(3);
  56577. down = texture.readPixels(2);
  56578. }
  56579. else {
  56580. up = texture.readPixels(2);
  56581. down = texture.readPixels(3);
  56582. }
  56583. var front = texture.readPixels(4);
  56584. var back = texture.readPixels(5);
  56585. var gammaSpace = texture.gammaSpace;
  56586. // Always read as RGBA.
  56587. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  56588. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  56589. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  56590. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  56591. }
  56592. var cubeInfo = {
  56593. size: size,
  56594. right: right,
  56595. left: left,
  56596. up: up,
  56597. down: down,
  56598. front: front,
  56599. back: back,
  56600. format: format,
  56601. type: type,
  56602. gammaSpace: gammaSpace,
  56603. };
  56604. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  56605. };
  56606. /**
  56607. * Converts a cubemap to the according Spherical Polynomial data.
  56608. * This extracts the first 3 orders only as they are the only one used in the lighting.
  56609. *
  56610. * @param cubeInfo The Cube map to extract the information from.
  56611. * @return The Spherical Polynomial data.
  56612. */
  56613. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  56614. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  56615. var totalSolidAngle = 0.0;
  56616. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  56617. var du = 2.0 / cubeInfo.size;
  56618. var dv = du;
  56619. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  56620. var minUV = du * 0.5 - 1.0;
  56621. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  56622. var fileFace = this.FileFaces[faceIndex];
  56623. var dataArray = cubeInfo[fileFace.name];
  56624. var v = minUV;
  56625. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  56626. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  56627. // Because SP is still linear, so summation is fine in that basis.
  56628. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  56629. for (var y = 0; y < cubeInfo.size; y++) {
  56630. var u = minUV;
  56631. for (var x = 0; x < cubeInfo.size; x++) {
  56632. // World direction (not normalised)
  56633. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  56634. worldDirection.normalize();
  56635. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  56636. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  56637. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  56638. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  56639. // Handle Integer types.
  56640. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  56641. r /= 255;
  56642. g /= 255;
  56643. b /= 255;
  56644. }
  56645. // Handle Gamma space textures.
  56646. if (cubeInfo.gammaSpace) {
  56647. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  56648. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  56649. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  56650. }
  56651. var color = new BABYLON.Color3(r, g, b);
  56652. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  56653. totalSolidAngle += deltaSolidAngle;
  56654. u += du;
  56655. }
  56656. v += dv;
  56657. }
  56658. }
  56659. // Solid angle for entire sphere is 4*pi
  56660. var sphereSolidAngle = 4.0 * Math.PI;
  56661. // Adjust the solid angle to allow for how many faces we processed.
  56662. var facesProcessed = 6.0;
  56663. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  56664. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  56665. // This is needed because the numerical integration over the cube uses a
  56666. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  56667. // and also to compensate for accumulative error due to float precision in the summation.
  56668. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  56669. sphericalHarmonics.scale(correctionFactor);
  56670. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  56671. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  56672. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  56673. };
  56674. return CubeMapToSphericalPolynomialTools;
  56675. }());
  56676. CubeMapToSphericalPolynomialTools.FileFaces = [
  56677. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  56678. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  56679. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  56680. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  56681. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  56682. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  56683. ];
  56684. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  56685. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56686. })(BABYLON || (BABYLON = {}));
  56687. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  56688. var BABYLON;
  56689. (function (BABYLON) {
  56690. var Internals;
  56691. (function (Internals) {
  56692. /**
  56693. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  56694. */
  56695. var PanoramaToCubeMapTools = (function () {
  56696. function PanoramaToCubeMapTools() {
  56697. }
  56698. /**
  56699. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  56700. *
  56701. * @param float32Array The source data.
  56702. * @param inputWidth The width of the input panorama.
  56703. * @param inputhHeight The height of the input panorama.
  56704. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  56705. * @return The cubemap data
  56706. */
  56707. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  56708. if (!float32Array) {
  56709. throw "ConvertPanoramaToCubemap: input cannot be null";
  56710. }
  56711. if (float32Array.length != inputWidth * inputHeight * 3) {
  56712. throw "ConvertPanoramaToCubemap: input size is wrong";
  56713. }
  56714. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  56715. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  56716. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  56717. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  56718. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  56719. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  56720. return {
  56721. front: textureFront,
  56722. back: textureBack,
  56723. left: textureLeft,
  56724. right: textureRight,
  56725. up: textureUp,
  56726. down: textureDown,
  56727. size: size,
  56728. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  56729. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  56730. gammaSpace: false,
  56731. };
  56732. };
  56733. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  56734. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  56735. var textureArray = new Float32Array(buffer);
  56736. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  56737. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  56738. var dy = 1 / texSize;
  56739. var fy = 0;
  56740. for (var y = 0; y < texSize; y++) {
  56741. var xv1 = faceData[0];
  56742. var xv2 = faceData[2];
  56743. for (var x = 0; x < texSize; x++) {
  56744. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  56745. v.normalize();
  56746. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  56747. // 3 channels per pixels
  56748. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  56749. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  56750. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  56751. xv1 = xv1.add(rotDX1);
  56752. xv2 = xv2.add(rotDX2);
  56753. }
  56754. fy += dy;
  56755. }
  56756. return textureArray;
  56757. };
  56758. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  56759. var theta = Math.atan2(vDir.z, vDir.x);
  56760. var phi = Math.acos(vDir.y);
  56761. while (theta < -Math.PI)
  56762. theta += 2 * Math.PI;
  56763. while (theta > Math.PI)
  56764. theta -= 2 * Math.PI;
  56765. var dx = theta / Math.PI;
  56766. var dy = phi / Math.PI;
  56767. // recenter.
  56768. dx = dx * 0.5 + 0.5;
  56769. var px = Math.round(dx * inputWidth);
  56770. if (px < 0)
  56771. px = 0;
  56772. else if (px >= inputWidth)
  56773. px = inputWidth - 1;
  56774. var py = Math.round(dy * inputHeight);
  56775. if (py < 0)
  56776. py = 0;
  56777. else if (py >= inputHeight)
  56778. py = inputHeight - 1;
  56779. var inputY = (inputHeight - py - 1);
  56780. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  56781. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  56782. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  56783. return {
  56784. r: r,
  56785. g: g,
  56786. b: b
  56787. };
  56788. };
  56789. return PanoramaToCubeMapTools;
  56790. }());
  56791. PanoramaToCubeMapTools.FACE_FRONT = [
  56792. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  56793. new BABYLON.Vector3(1.0, -1.0, -1.0),
  56794. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  56795. new BABYLON.Vector3(1.0, 1.0, -1.0)
  56796. ];
  56797. PanoramaToCubeMapTools.FACE_BACK = [
  56798. new BABYLON.Vector3(1.0, -1.0, 1.0),
  56799. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  56800. new BABYLON.Vector3(1.0, 1.0, 1.0),
  56801. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  56802. ];
  56803. PanoramaToCubeMapTools.FACE_RIGHT = [
  56804. new BABYLON.Vector3(1.0, -1.0, -1.0),
  56805. new BABYLON.Vector3(1.0, -1.0, 1.0),
  56806. new BABYLON.Vector3(1.0, 1.0, -1.0),
  56807. new BABYLON.Vector3(1.0, 1.0, 1.0)
  56808. ];
  56809. PanoramaToCubeMapTools.FACE_LEFT = [
  56810. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  56811. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  56812. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  56813. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  56814. ];
  56815. PanoramaToCubeMapTools.FACE_DOWN = [
  56816. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  56817. new BABYLON.Vector3(1.0, 1.0, -1.0),
  56818. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  56819. new BABYLON.Vector3(1.0, 1.0, 1.0)
  56820. ];
  56821. PanoramaToCubeMapTools.FACE_UP = [
  56822. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  56823. new BABYLON.Vector3(1.0, -1.0, 1.0),
  56824. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  56825. new BABYLON.Vector3(1.0, -1.0, -1.0)
  56826. ];
  56827. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  56828. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56829. })(BABYLON || (BABYLON = {}));
  56830. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  56831. var BABYLON;
  56832. (function (BABYLON) {
  56833. var Internals;
  56834. (function (Internals) {
  56835. ;
  56836. /**
  56837. * This groups tools to convert HDR texture to native colors array.
  56838. */
  56839. var HDRTools = (function () {
  56840. function HDRTools() {
  56841. }
  56842. HDRTools.Ldexp = function (mantissa, exponent) {
  56843. if (exponent > 1023) {
  56844. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  56845. }
  56846. if (exponent < -1074) {
  56847. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  56848. }
  56849. return mantissa * Math.pow(2, exponent);
  56850. };
  56851. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  56852. if (exponent > 0) {
  56853. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  56854. float32array[index + 0] = red * exponent;
  56855. float32array[index + 1] = green * exponent;
  56856. float32array[index + 2] = blue * exponent;
  56857. }
  56858. else {
  56859. float32array[index + 0] = 0;
  56860. float32array[index + 1] = 0;
  56861. float32array[index + 2] = 0;
  56862. }
  56863. };
  56864. HDRTools.readStringLine = function (uint8array, startIndex) {
  56865. var line = "";
  56866. var character = "";
  56867. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  56868. character = String.fromCharCode(uint8array[i]);
  56869. if (character == "\n") {
  56870. break;
  56871. }
  56872. line += character;
  56873. }
  56874. return line;
  56875. };
  56876. /**
  56877. * Reads header information from an RGBE texture stored in a native array.
  56878. * More information on this format are available here:
  56879. * https://en.wikipedia.org/wiki/RGBE_image_format
  56880. *
  56881. * @param uint8array The binary file stored in native array.
  56882. * @return The header information.
  56883. */
  56884. HDRTools.RGBE_ReadHeader = function (uint8array) {
  56885. var height = 0;
  56886. var width = 0;
  56887. var line = this.readStringLine(uint8array, 0);
  56888. if (line[0] != '#' || line[1] != '?') {
  56889. throw "Bad HDR Format.";
  56890. }
  56891. var endOfHeader = false;
  56892. var findFormat = false;
  56893. var lineIndex = 0;
  56894. do {
  56895. lineIndex += (line.length + 1);
  56896. line = this.readStringLine(uint8array, lineIndex);
  56897. if (line == "FORMAT=32-bit_rle_rgbe") {
  56898. findFormat = true;
  56899. }
  56900. else if (line.length == 0) {
  56901. endOfHeader = true;
  56902. }
  56903. } while (!endOfHeader);
  56904. if (!findFormat) {
  56905. throw "HDR Bad header format, unsupported FORMAT";
  56906. }
  56907. lineIndex += (line.length + 1);
  56908. line = this.readStringLine(uint8array, lineIndex);
  56909. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  56910. var match = sizeRegexp.exec(line);
  56911. // TODO. Support +Y and -X if needed.
  56912. if (match.length < 3) {
  56913. throw "HDR Bad header format, no size";
  56914. }
  56915. width = parseInt(match[2]);
  56916. height = parseInt(match[1]);
  56917. if (width < 8 || width > 0x7fff) {
  56918. throw "HDR Bad header format, unsupported size";
  56919. }
  56920. lineIndex += (line.length + 1);
  56921. return {
  56922. height: height,
  56923. width: width,
  56924. dataPosition: lineIndex
  56925. };
  56926. };
  56927. /**
  56928. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  56929. * This RGBE texture needs to store the information as a panorama.
  56930. *
  56931. * More information on this format are available here:
  56932. * https://en.wikipedia.org/wiki/RGBE_image_format
  56933. *
  56934. * @param buffer The binary file stored in an array buffer.
  56935. * @param size The expected size of the extracted cubemap.
  56936. * @return The Cube Map information.
  56937. */
  56938. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  56939. var uint8array = new Uint8Array(buffer);
  56940. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  56941. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  56942. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  56943. return cubeMapData;
  56944. };
  56945. /**
  56946. * Returns the pixels data extracted from an RGBE texture.
  56947. * This pixels will be stored left to right up to down in the R G B order in one array.
  56948. *
  56949. * More information on this format are available here:
  56950. * https://en.wikipedia.org/wiki/RGBE_image_format
  56951. *
  56952. * @param uint8array The binary file stored in an array buffer.
  56953. * @param hdrInfo The header information of the file.
  56954. * @return The pixels data in RGB right to left up to down order.
  56955. */
  56956. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  56957. // Keep for multi format supports.
  56958. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  56959. };
  56960. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  56961. var num_scanlines = hdrInfo.height;
  56962. var scanline_width = hdrInfo.width;
  56963. var a, b, c, d, count;
  56964. var dataIndex = hdrInfo.dataPosition;
  56965. var index = 0, endIndex = 0, i = 0;
  56966. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  56967. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  56968. // 3 channels of 4 bytes per pixel in float.
  56969. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  56970. var resultArray = new Float32Array(resultBuffer);
  56971. // read in each successive scanline
  56972. while (num_scanlines > 0) {
  56973. a = uint8array[dataIndex++];
  56974. b = uint8array[dataIndex++];
  56975. c = uint8array[dataIndex++];
  56976. d = uint8array[dataIndex++];
  56977. if (a != 2 || b != 2 || (c & 0x80)) {
  56978. // this file is not run length encoded
  56979. throw "HDR Bad header format, not RLE";
  56980. }
  56981. if (((c << 8) | d) != scanline_width) {
  56982. throw "HDR Bad header format, wrong scan line width";
  56983. }
  56984. index = 0;
  56985. // read each of the four channels for the scanline into the buffer
  56986. for (i = 0; i < 4; i++) {
  56987. endIndex = (i + 1) * scanline_width;
  56988. while (index < endIndex) {
  56989. a = uint8array[dataIndex++];
  56990. b = uint8array[dataIndex++];
  56991. if (a > 128) {
  56992. // a run of the same value
  56993. count = a - 128;
  56994. if ((count == 0) || (count > endIndex - index)) {
  56995. throw "HDR Bad Format, bad scanline data (run)";
  56996. }
  56997. while (count-- > 0) {
  56998. scanLineArray[index++] = b;
  56999. }
  57000. }
  57001. else {
  57002. // a non-run
  57003. count = a;
  57004. if ((count == 0) || (count > endIndex - index)) {
  57005. throw "HDR Bad Format, bad scanline data (non-run)";
  57006. }
  57007. scanLineArray[index++] = b;
  57008. if (--count > 0) {
  57009. for (var j = 0; j < count; j++) {
  57010. scanLineArray[index++] = uint8array[dataIndex++];
  57011. }
  57012. }
  57013. }
  57014. }
  57015. }
  57016. // now convert data from buffer into floats
  57017. for (i = 0; i < scanline_width; i++) {
  57018. a = scanLineArray[i];
  57019. b = scanLineArray[i + scanline_width];
  57020. c = scanLineArray[i + 2 * scanline_width];
  57021. d = scanLineArray[i + 3 * scanline_width];
  57022. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  57023. }
  57024. num_scanlines--;
  57025. }
  57026. return resultArray;
  57027. };
  57028. return HDRTools;
  57029. }());
  57030. Internals.HDRTools = HDRTools;
  57031. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  57032. })(BABYLON || (BABYLON = {}));
  57033. //# sourceMappingURL=babylon.hdr.js.map
  57034. var BABYLON;
  57035. (function (BABYLON) {
  57036. /**
  57037. * This represents a texture coming from an HDR input.
  57038. *
  57039. * The only supported format is currently panorama picture stored in RGBE format.
  57040. * Example of such files can be found on HDRLib: http://hdrlib.com/
  57041. */
  57042. var HDRCubeTexture = (function (_super) {
  57043. __extends(HDRCubeTexture, _super);
  57044. /**
  57045. * Instantiates an HDRTexture from the following parameters.
  57046. *
  57047. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  57048. * @param scene The scene the texture will be used in
  57049. * @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.
  57050. * @param noMipmap Forces to not generate the mipmap if true
  57051. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  57052. * @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)
  57053. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  57054. */
  57055. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  57056. if (noMipmap === void 0) { noMipmap = false; }
  57057. if (generateHarmonics === void 0) { generateHarmonics = true; }
  57058. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  57059. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  57060. if (onLoad === void 0) { onLoad = null; }
  57061. if (onError === void 0) { onError = null; }
  57062. var _this = _super.call(this, scene) || this;
  57063. _this._useInGammaSpace = false;
  57064. _this._generateHarmonics = true;
  57065. _this._isBABYLONPreprocessed = false;
  57066. _this._onLoad = null;
  57067. _this._onError = null;
  57068. /**
  57069. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  57070. */
  57071. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  57072. /**
  57073. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  57074. * This is usefull at run time to apply the good shader.
  57075. */
  57076. _this.isPMREM = false;
  57077. _this._isBlocking = true;
  57078. if (!url) {
  57079. return _this;
  57080. }
  57081. _this.name = url;
  57082. _this.url = url;
  57083. _this.hasAlpha = false;
  57084. _this.isCube = true;
  57085. _this._textureMatrix = BABYLON.Matrix.Identity();
  57086. _this._onLoad = onLoad;
  57087. _this._onError = onError;
  57088. _this.gammaSpace = false;
  57089. if (size) {
  57090. _this._isBABYLONPreprocessed = false;
  57091. _this._noMipmap = noMipmap;
  57092. _this._size = size;
  57093. _this._useInGammaSpace = useInGammaSpace;
  57094. _this._usePMREMGenerator = usePMREMGenerator &&
  57095. scene.getEngine().getCaps().textureLOD &&
  57096. _this.getScene().getEngine().getCaps().textureFloat &&
  57097. !_this._useInGammaSpace;
  57098. }
  57099. else {
  57100. _this._isBABYLONPreprocessed = true;
  57101. _this._noMipmap = false;
  57102. _this._useInGammaSpace = false;
  57103. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  57104. _this.getScene().getEngine().getCaps().textureFloat &&
  57105. !_this._useInGammaSpace;
  57106. }
  57107. _this.isPMREM = _this._usePMREMGenerator;
  57108. _this._texture = _this._getFromCache(url, _this._noMipmap);
  57109. if (!_this._texture) {
  57110. if (!scene.useDelayedTextureLoading) {
  57111. _this.loadTexture();
  57112. }
  57113. else {
  57114. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  57115. }
  57116. }
  57117. return _this;
  57118. }
  57119. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  57120. /**
  57121. * Gets wether or not the texture is blocking during loading.
  57122. */
  57123. get: function () {
  57124. return this._isBlocking;
  57125. },
  57126. /**
  57127. * Sets wether or not the texture is blocking during loading.
  57128. */
  57129. set: function (value) {
  57130. this._isBlocking = value;
  57131. },
  57132. enumerable: true,
  57133. configurable: true
  57134. });
  57135. /**
  57136. * Occurs when the file is a preprocessed .babylon.hdr file.
  57137. */
  57138. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  57139. var _this = this;
  57140. var mipLevels = 0;
  57141. var floatArrayView = null;
  57142. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  57143. var mips = [];
  57144. var startIndex = 30;
  57145. for (var level = 0; level < mipLevels; level++) {
  57146. mips.push([]);
  57147. // Fill each pixel of the mip level.
  57148. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  57149. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  57150. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  57151. mips[level].push(faceData);
  57152. startIndex += faceSize;
  57153. }
  57154. }
  57155. return mips;
  57156. } : null;
  57157. var callback = function (buffer) {
  57158. // Create Native Array Views
  57159. var intArrayView = new Int32Array(buffer);
  57160. floatArrayView = new Float32Array(buffer);
  57161. // Fill header.
  57162. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  57163. _this._size = intArrayView[1]; // CubeMap max mip face size.
  57164. // Update Texture Information.
  57165. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  57166. // Fill polynomial information.
  57167. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  57168. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  57169. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  57170. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  57171. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  57172. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  57173. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  57174. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  57175. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  57176. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  57177. _this.sphericalPolynomial = sphericalPolynomial;
  57178. // Fill pixel data.
  57179. mipLevels = intArrayView[29]; // Number of mip levels.
  57180. var startIndex = 30;
  57181. var data = [];
  57182. var faceSize = Math.pow(_this._size, 2) * 3;
  57183. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  57184. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  57185. startIndex += faceSize;
  57186. }
  57187. var results = [];
  57188. var byteArray = null;
  57189. // Push each faces.
  57190. for (var k = 0; k < 6; k++) {
  57191. var dataFace = null;
  57192. // To be deprecated.
  57193. if (version === 1) {
  57194. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  57195. dataFace = data[j];
  57196. }
  57197. // If special cases.
  57198. if (!mipmapGenerator) {
  57199. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  57200. // 3 channels of 1 bytes per pixel in bytes.
  57201. var byteBuffer = new ArrayBuffer(faceSize);
  57202. byteArray = new Uint8Array(byteBuffer);
  57203. }
  57204. for (var i = 0; i < _this._size * _this._size; i++) {
  57205. // Put in gamma space if requested.
  57206. if (_this._useInGammaSpace) {
  57207. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  57208. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  57209. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  57210. }
  57211. // Convert to int texture for fallback.
  57212. if (byteArray) {
  57213. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  57214. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  57215. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  57216. // May use luminance instead if the result is not accurate.
  57217. var max = Math.max(Math.max(r, g), b);
  57218. if (max > 255) {
  57219. var scale = 255 / max;
  57220. r *= scale;
  57221. g *= scale;
  57222. b *= scale;
  57223. }
  57224. byteArray[(i * 3) + 0] = r;
  57225. byteArray[(i * 3) + 1] = g;
  57226. byteArray[(i * 3) + 2] = b;
  57227. }
  57228. }
  57229. }
  57230. // Fill the array accordingly.
  57231. if (byteArray) {
  57232. results.push(byteArray);
  57233. }
  57234. else {
  57235. results.push(dataFace);
  57236. }
  57237. }
  57238. return results;
  57239. };
  57240. 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);
  57241. };
  57242. /**
  57243. * Occurs when the file is raw .hdr file.
  57244. */
  57245. HDRCubeTexture.prototype.loadHDRTexture = function () {
  57246. var _this = this;
  57247. var callback = function (buffer) {
  57248. // Extract the raw linear data.
  57249. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  57250. // Generate harmonics if needed.
  57251. if (_this._generateHarmonics) {
  57252. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  57253. _this.sphericalPolynomial = sphericalPolynomial;
  57254. }
  57255. var results = [];
  57256. var byteArray = null;
  57257. // Push each faces.
  57258. for (var j = 0; j < 6; j++) {
  57259. // Create uintarray fallback.
  57260. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  57261. // 3 channels of 1 bytes per pixel in bytes.
  57262. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  57263. byteArray = new Uint8Array(byteBuffer);
  57264. }
  57265. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  57266. // If special cases.
  57267. if (_this._useInGammaSpace || byteArray) {
  57268. for (var i = 0; i < _this._size * _this._size; i++) {
  57269. // Put in gamma space if requested.
  57270. if (_this._useInGammaSpace) {
  57271. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  57272. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  57273. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  57274. }
  57275. // Convert to int texture for fallback.
  57276. if (byteArray) {
  57277. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  57278. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  57279. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  57280. // May use luminance instead if the result is not accurate.
  57281. var max = Math.max(Math.max(r, g), b);
  57282. if (max > 255) {
  57283. var scale = 255 / max;
  57284. r *= scale;
  57285. g *= scale;
  57286. b *= scale;
  57287. }
  57288. byteArray[(i * 3) + 0] = r;
  57289. byteArray[(i * 3) + 1] = g;
  57290. byteArray[(i * 3) + 2] = b;
  57291. }
  57292. }
  57293. }
  57294. if (byteArray) {
  57295. results.push(byteArray);
  57296. }
  57297. else {
  57298. results.push(dataFace);
  57299. }
  57300. }
  57301. return results;
  57302. };
  57303. var mipmapGenerator = null;
  57304. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  57305. // if (!this._noMipmap &&
  57306. // this._usePMREMGenerator) {
  57307. // mipmapGenerator = (data: ArrayBufferView[]) => {
  57308. // // Custom setup of the generator matching with the PBR shader values.
  57309. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  57310. // this._size,
  57311. // this._size,
  57312. // 0,
  57313. // 3,
  57314. // this.getScene().getEngine().getCaps().textureFloat,
  57315. // 2048,
  57316. // 0.25,
  57317. // false,
  57318. // true);
  57319. // return generator.filterCubeMap();
  57320. // };
  57321. // }
  57322. 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);
  57323. };
  57324. /**
  57325. * Starts the loading process of the texture.
  57326. */
  57327. HDRCubeTexture.prototype.loadTexture = function () {
  57328. if (this._isBABYLONPreprocessed) {
  57329. this.loadBabylonTexture();
  57330. }
  57331. else {
  57332. this.loadHDRTexture();
  57333. }
  57334. };
  57335. HDRCubeTexture.prototype.clone = function () {
  57336. var size = this._isBABYLONPreprocessed ? null : this._size;
  57337. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  57338. // Base texture
  57339. newTexture.level = this.level;
  57340. newTexture.wrapU = this.wrapU;
  57341. newTexture.wrapV = this.wrapV;
  57342. newTexture.coordinatesIndex = this.coordinatesIndex;
  57343. newTexture.coordinatesMode = this.coordinatesMode;
  57344. return newTexture;
  57345. };
  57346. // Methods
  57347. HDRCubeTexture.prototype.delayLoad = function () {
  57348. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  57349. return;
  57350. }
  57351. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  57352. this._texture = this._getFromCache(this.url, this._noMipmap);
  57353. if (!this._texture) {
  57354. this.loadTexture();
  57355. }
  57356. };
  57357. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  57358. return this._textureMatrix;
  57359. };
  57360. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  57361. this._textureMatrix = value;
  57362. };
  57363. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  57364. var texture = null;
  57365. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  57366. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  57367. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  57368. texture.name = parsedTexture.name;
  57369. texture.hasAlpha = parsedTexture.hasAlpha;
  57370. texture.level = parsedTexture.level;
  57371. texture.coordinatesMode = parsedTexture.coordinatesMode;
  57372. texture.isBlocking = parsedTexture.isBlocking;
  57373. }
  57374. return texture;
  57375. };
  57376. HDRCubeTexture.prototype.serialize = function () {
  57377. if (!this.name) {
  57378. return null;
  57379. }
  57380. var serializationObject = {};
  57381. serializationObject.name = this.name;
  57382. serializationObject.hasAlpha = this.hasAlpha;
  57383. serializationObject.isCube = true;
  57384. serializationObject.level = this.level;
  57385. serializationObject.size = this._size;
  57386. serializationObject.coordinatesMode = this.coordinatesMode;
  57387. serializationObject.useInGammaSpace = this._useInGammaSpace;
  57388. serializationObject.generateHarmonics = this._generateHarmonics;
  57389. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  57390. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  57391. serializationObject.customType = "BABYLON.HDRCubeTexture";
  57392. serializationObject.noMipmap = this._noMipmap;
  57393. serializationObject.isBlocking = this._isBlocking;
  57394. return serializationObject;
  57395. };
  57396. /**
  57397. * Saves as a file the data contained in the texture in a binary format.
  57398. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  57399. * as the spherical used in the lighting.
  57400. * @param url The HDR file url.
  57401. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  57402. * @param onError Method called if any error happens during download.
  57403. * @return The packed binary data.
  57404. */
  57405. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  57406. if (onError === void 0) { onError = null; }
  57407. var callback = function (buffer) {
  57408. var data = new Blob([buffer], { type: 'application/octet-stream' });
  57409. // Returns a URL you can use as a href.
  57410. var objUrl = window.URL.createObjectURL(data);
  57411. // Simulates a link to it and click to dowload.
  57412. var a = document.createElement("a");
  57413. document.body.appendChild(a);
  57414. a.style.display = "none";
  57415. a.href = objUrl;
  57416. a.download = "envmap.babylon.hdr";
  57417. a.click();
  57418. };
  57419. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  57420. };
  57421. /**
  57422. * Serializes the data contained in the texture in a binary format.
  57423. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  57424. * as the spherical used in the lighting.
  57425. * @param url The HDR file url.
  57426. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  57427. * @param onError Method called if any error happens during download.
  57428. * @return The packed binary data.
  57429. */
  57430. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  57431. if (onError === void 0) { onError = null; }
  57432. // Needs the url tho create the texture.
  57433. if (!url) {
  57434. return null;
  57435. }
  57436. // Check Power of two size.
  57437. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  57438. return null;
  57439. }
  57440. // Coming Back in 3.1.
  57441. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  57442. return null;
  57443. };
  57444. return HDRCubeTexture;
  57445. }(BABYLON.BaseTexture));
  57446. HDRCubeTexture._facesMapping = [
  57447. "right",
  57448. "left",
  57449. "up",
  57450. "down",
  57451. "front",
  57452. "back"
  57453. ];
  57454. BABYLON.HDRCubeTexture = HDRCubeTexture;
  57455. })(BABYLON || (BABYLON = {}));
  57456. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  57457. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  57458. // Huge respect for a such great lib.
  57459. // Earcut license:
  57460. // Copyright (c) 2016, Mapbox
  57461. //
  57462. // Permission to use, copy, modify, and/or distribute this software for any purpose
  57463. // with or without fee is hereby granted, provided that the above copyright notice
  57464. // and this permission notice appear in all copies.
  57465. //
  57466. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  57467. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  57468. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  57469. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  57470. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  57471. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  57472. // THIS SOFTWARE.
  57473. var Earcut;
  57474. (function (Earcut) {
  57475. /**
  57476. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  57477. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  57478. * @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).
  57479. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  57480. */
  57481. function earcut(data, holeIndices, dim) {
  57482. dim = dim || 2;
  57483. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  57484. if (!outerNode)
  57485. return triangles;
  57486. var minX, minY, maxX, maxY, x, y, size;
  57487. if (hasHoles)
  57488. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  57489. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  57490. if (data.length > 80 * dim) {
  57491. minX = maxX = data[0];
  57492. minY = maxY = data[1];
  57493. for (var i = dim; i < outerLen; i += dim) {
  57494. x = data[i];
  57495. y = data[i + 1];
  57496. if (x < minX)
  57497. minX = x;
  57498. if (y < minY)
  57499. minY = y;
  57500. if (x > maxX)
  57501. maxX = x;
  57502. if (y > maxY)
  57503. maxY = y;
  57504. }
  57505. // minX, minY and size are later used to transform coords into integers for z-order calculation
  57506. size = Math.max(maxX - minX, maxY - minY);
  57507. }
  57508. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  57509. return triangles;
  57510. }
  57511. Earcut.earcut = earcut;
  57512. // create a circular doubly linked list from polygon points in the specified winding order
  57513. function linkedList(data, start, end, dim, clockwise) {
  57514. var i, last;
  57515. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  57516. for (i = start; i < end; i += dim)
  57517. last = insertNode(i, data[i], data[i + 1], last);
  57518. }
  57519. else {
  57520. for (i = end - dim; i >= start; i -= dim)
  57521. last = insertNode(i, data[i], data[i + 1], last);
  57522. }
  57523. if (last && equals(last, last.next)) {
  57524. removeNode(last);
  57525. last = last.next;
  57526. }
  57527. return last;
  57528. }
  57529. // eliminate colinear or duplicate points
  57530. function filterPoints(start, end) {
  57531. if (!start)
  57532. return start;
  57533. if (!end)
  57534. end = start;
  57535. var p = start, again;
  57536. do {
  57537. again = false;
  57538. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  57539. removeNode(p);
  57540. p = end = p.prev;
  57541. if (p === p.next)
  57542. return null;
  57543. again = true;
  57544. }
  57545. else {
  57546. p = p.next;
  57547. }
  57548. } while (again || p !== end);
  57549. return end;
  57550. }
  57551. // main ear slicing loop which triangulates a polygon (given as a linked list)
  57552. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  57553. if (!ear)
  57554. return;
  57555. // interlink polygon nodes in z-order
  57556. if (!pass && size)
  57557. indexCurve(ear, minX, minY, size);
  57558. var stop = ear, prev, next;
  57559. // iterate through ears, slicing them one by one
  57560. while (ear.prev !== ear.next) {
  57561. prev = ear.prev;
  57562. next = ear.next;
  57563. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  57564. // cut off the triangle
  57565. triangles.push(prev.i / dim);
  57566. triangles.push(ear.i / dim);
  57567. triangles.push(next.i / dim);
  57568. removeNode(ear);
  57569. // skipping the next vertice leads to less sliver triangles
  57570. ear = next.next;
  57571. stop = next.next;
  57572. continue;
  57573. }
  57574. ear = next;
  57575. // if we looped through the whole remaining polygon and can't find any more ears
  57576. if (ear === stop) {
  57577. // try filtering points and slicing again
  57578. if (!pass) {
  57579. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  57580. // if this didn't work, try curing all small self-intersections locally
  57581. }
  57582. else if (pass === 1) {
  57583. ear = cureLocalIntersections(ear, triangles, dim);
  57584. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  57585. // as a last resort, try splitting the remaining polygon into two
  57586. }
  57587. else if (pass === 2) {
  57588. splitEarcut(ear, triangles, dim, minX, minY, size);
  57589. }
  57590. break;
  57591. }
  57592. }
  57593. }
  57594. // check whether a polygon node forms a valid ear with adjacent nodes
  57595. function isEar(ear) {
  57596. var a = ear.prev, b = ear, c = ear.next;
  57597. if (area(a, b, c) >= 0)
  57598. return false; // reflex, can't be an ear
  57599. // now make sure we don't have other points inside the potential ear
  57600. var p = ear.next.next;
  57601. while (p !== ear.prev) {
  57602. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  57603. area(p.prev, p, p.next) >= 0)
  57604. return false;
  57605. p = p.next;
  57606. }
  57607. return true;
  57608. }
  57609. function isEarHashed(ear, minX, minY, size) {
  57610. var a = ear.prev, b = ear, c = ear.next;
  57611. if (area(a, b, c) >= 0)
  57612. return false; // reflex, can't be an ear
  57613. // triangle bbox; min & max are calculated like this for speed
  57614. 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);
  57615. // z-order range for the current triangle bbox;
  57616. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  57617. // first look for points inside the triangle in increasing z-order
  57618. var p = ear.nextZ;
  57619. while (p && p.z <= maxZ) {
  57620. if (p !== ear.prev &&
  57621. p !== ear.next &&
  57622. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  57623. area(p.prev, p, p.next) >= 0)
  57624. return false;
  57625. p = p.nextZ;
  57626. }
  57627. // then look for points in decreasing z-order
  57628. p = ear.prevZ;
  57629. while (p && p.z >= minZ) {
  57630. if (p !== ear.prev &&
  57631. p !== ear.next &&
  57632. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  57633. area(p.prev, p, p.next) >= 0)
  57634. return false;
  57635. p = p.prevZ;
  57636. }
  57637. return true;
  57638. }
  57639. // go through all polygon nodes and cure small local self-intersections
  57640. function cureLocalIntersections(start, triangles, dim) {
  57641. var p = start;
  57642. do {
  57643. var a = p.prev, b = p.next.next;
  57644. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  57645. triangles.push(a.i / dim);
  57646. triangles.push(p.i / dim);
  57647. triangles.push(b.i / dim);
  57648. // remove two nodes involved
  57649. removeNode(p);
  57650. removeNode(p.next);
  57651. p = start = b;
  57652. }
  57653. p = p.next;
  57654. } while (p !== start);
  57655. return p;
  57656. }
  57657. // try splitting polygon into two and triangulate them independently
  57658. function splitEarcut(start, triangles, dim, minX, minY, size) {
  57659. // look for a valid diagonal that divides the polygon into two
  57660. var a = start;
  57661. do {
  57662. var b = a.next.next;
  57663. while (b !== a.prev) {
  57664. if (a.i !== b.i && isValidDiagonal(a, b)) {
  57665. // split the polygon in two by the diagonal
  57666. var c = splitPolygon(a, b);
  57667. // filter colinear points around the cuts
  57668. a = filterPoints(a, a.next);
  57669. c = filterPoints(c, c.next);
  57670. // run earcut on each half
  57671. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  57672. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  57673. return;
  57674. }
  57675. b = b.next;
  57676. }
  57677. a = a.next;
  57678. } while (a !== start);
  57679. }
  57680. // link every hole into the outer loop, producing a single-ring polygon without holes
  57681. function eliminateHoles(data, holeIndices, outerNode, dim) {
  57682. var queue = [], i, len, start, end, list;
  57683. for (i = 0, len = holeIndices.length; i < len; i++) {
  57684. start = holeIndices[i] * dim;
  57685. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  57686. list = linkedList(data, start, end, dim, false);
  57687. if (list === list.next)
  57688. list.steiner = true;
  57689. queue.push(getLeftmost(list));
  57690. }
  57691. queue.sort(compareX);
  57692. // process holes from left to right
  57693. for (i = 0; i < queue.length; i++) {
  57694. eliminateHole(queue[i], outerNode);
  57695. outerNode = filterPoints(outerNode, outerNode.next);
  57696. }
  57697. return outerNode;
  57698. }
  57699. function compareX(a, b) {
  57700. return a.x - b.x;
  57701. }
  57702. // find a bridge between vertices that connects hole with an outer ring and and link it
  57703. function eliminateHole(hole, outerNode) {
  57704. outerNode = findHoleBridge(hole, outerNode);
  57705. if (outerNode) {
  57706. var b = splitPolygon(outerNode, hole);
  57707. filterPoints(b, b.next);
  57708. }
  57709. }
  57710. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  57711. function findHoleBridge(hole, outerNode) {
  57712. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  57713. // find a segment intersected by a ray from the hole's leftmost point to the left;
  57714. // segment's endpoint with lesser x will be potential connection point
  57715. do {
  57716. if (hy <= p.y && hy >= p.next.y) {
  57717. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  57718. if (x <= hx && x > qx) {
  57719. qx = x;
  57720. if (x === hx) {
  57721. if (hy === p.y)
  57722. return p;
  57723. if (hy === p.next.y)
  57724. return p.next;
  57725. }
  57726. m = p.x < p.next.x ? p : p.next;
  57727. }
  57728. }
  57729. p = p.next;
  57730. } while (p !== outerNode);
  57731. if (!m)
  57732. return null;
  57733. if (hx === qx)
  57734. return m.prev; // hole touches outer segment; pick lower endpoint
  57735. // look for points inside the triangle of hole point, segment intersection and endpoint;
  57736. // if there are no points found, we have a valid connection;
  57737. // otherwise choose the point of the minimum angle with the ray as connection point
  57738. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  57739. p = m.next;
  57740. while (p !== stop) {
  57741. if (hx >= p.x &&
  57742. p.x >= mx &&
  57743. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  57744. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  57745. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  57746. m = p;
  57747. tanMin = tan;
  57748. }
  57749. }
  57750. p = p.next;
  57751. }
  57752. return m;
  57753. }
  57754. // interlink polygon nodes in z-order
  57755. function indexCurve(start, minX, minY, size) {
  57756. var p = start;
  57757. do {
  57758. if (p.z === null)
  57759. p.z = zOrder(p.x, p.y, minX, minY, size);
  57760. p.prevZ = p.prev;
  57761. p.nextZ = p.next;
  57762. p = p.next;
  57763. } while (p !== start);
  57764. p.prevZ.nextZ = null;
  57765. p.prevZ = null;
  57766. sortLinked(p);
  57767. }
  57768. // Simon Tatham's linked list merge sort algorithm
  57769. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  57770. function sortLinked(list) {
  57771. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  57772. do {
  57773. p = list;
  57774. list = null;
  57775. tail = null;
  57776. numMerges = 0;
  57777. while (p) {
  57778. numMerges++;
  57779. q = p;
  57780. pSize = 0;
  57781. for (i = 0; i < inSize; i++) {
  57782. pSize++;
  57783. q = q.nextZ;
  57784. if (!q)
  57785. break;
  57786. }
  57787. qSize = inSize;
  57788. while (pSize > 0 || (qSize > 0 && q)) {
  57789. if (pSize === 0) {
  57790. e = q;
  57791. q = q.nextZ;
  57792. qSize--;
  57793. }
  57794. else if (qSize === 0 || !q) {
  57795. e = p;
  57796. p = p.nextZ;
  57797. pSize--;
  57798. }
  57799. else if (p.z <= q.z) {
  57800. e = p;
  57801. p = p.nextZ;
  57802. pSize--;
  57803. }
  57804. else {
  57805. e = q;
  57806. q = q.nextZ;
  57807. qSize--;
  57808. }
  57809. if (tail)
  57810. tail.nextZ = e;
  57811. else
  57812. list = e;
  57813. e.prevZ = tail;
  57814. tail = e;
  57815. }
  57816. p = q;
  57817. }
  57818. tail.nextZ = null;
  57819. inSize *= 2;
  57820. } while (numMerges > 1);
  57821. return list;
  57822. }
  57823. // z-order of a point given coords and size of the data bounding box
  57824. function zOrder(x, y, minX, minY, size) {
  57825. // coords are transformed into non-negative 15-bit integer range
  57826. x = 32767 * (x - minX) / size;
  57827. y = 32767 * (y - minY) / size;
  57828. x = (x | (x << 8)) & 0x00FF00FF;
  57829. x = (x | (x << 4)) & 0x0F0F0F0F;
  57830. x = (x | (x << 2)) & 0x33333333;
  57831. x = (x | (x << 1)) & 0x55555555;
  57832. y = (y | (y << 8)) & 0x00FF00FF;
  57833. y = (y | (y << 4)) & 0x0F0F0F0F;
  57834. y = (y | (y << 2)) & 0x33333333;
  57835. y = (y | (y << 1)) & 0x55555555;
  57836. return x | (y << 1);
  57837. }
  57838. // find the leftmost node of a polygon ring
  57839. function getLeftmost(start) {
  57840. var p = start, leftmost = start;
  57841. do {
  57842. if (p.x < leftmost.x)
  57843. leftmost = p;
  57844. p = p.next;
  57845. } while (p !== start);
  57846. return leftmost;
  57847. }
  57848. // check if a point lies within a convex triangle
  57849. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  57850. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  57851. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  57852. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  57853. }
  57854. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  57855. function isValidDiagonal(a, b) {
  57856. return a.next.i !== b.i &&
  57857. a.prev.i !== b.i &&
  57858. !intersectsPolygon(a, b) &&
  57859. locallyInside(a, b) &&
  57860. locallyInside(b, a) &&
  57861. middleInside(a, b);
  57862. }
  57863. // signed area of a triangle
  57864. function area(p, q, r) {
  57865. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  57866. }
  57867. // check if two points are equal
  57868. function equals(p1, p2) {
  57869. return p1.x === p2.x && p1.y === p2.y;
  57870. }
  57871. // check if two segments intersect
  57872. function intersects(p1, q1, p2, q2) {
  57873. if ((equals(p1, q1) && equals(p2, q2)) ||
  57874. (equals(p1, q2) && equals(p2, q1)))
  57875. return true;
  57876. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  57877. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  57878. }
  57879. // check if a polygon diagonal intersects any polygon segments
  57880. function intersectsPolygon(a, b) {
  57881. var p = a;
  57882. do {
  57883. if (p.i !== a.i &&
  57884. p.next.i !== a.i &&
  57885. p.i !== b.i &&
  57886. p.next.i !== b.i &&
  57887. intersects(p, p.next, a, b))
  57888. return true;
  57889. p = p.next;
  57890. } while (p !== a);
  57891. return false;
  57892. }
  57893. // check if a polygon diagonal is locally inside the polygon
  57894. function locallyInside(a, b) {
  57895. return area(a.prev, a, a.next) < 0
  57896. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  57897. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  57898. }
  57899. // check if the middle point of a polygon diagonal is inside the polygon
  57900. function middleInside(a, b) {
  57901. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  57902. do {
  57903. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  57904. inside = !inside;
  57905. p = p.next;
  57906. } while (p !== a);
  57907. return inside;
  57908. }
  57909. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  57910. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  57911. function splitPolygon(a, b) {
  57912. 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;
  57913. a.next = b;
  57914. b.prev = a;
  57915. a2.next = an;
  57916. an.prev = a2;
  57917. b2.next = a2;
  57918. a2.prev = b2;
  57919. bp.next = b2;
  57920. b2.prev = bp;
  57921. return b2;
  57922. }
  57923. // create a node and optionally link it with previous one (in a circular doubly linked list)
  57924. function insertNode(i, x, y, last) {
  57925. var p = new Node(i, x, y);
  57926. if (!last) {
  57927. p.prev = p;
  57928. p.next = p;
  57929. }
  57930. else {
  57931. p.next = last.next;
  57932. p.prev = last;
  57933. last.next.prev = p;
  57934. last.next = p;
  57935. }
  57936. return p;
  57937. }
  57938. function removeNode(p) {
  57939. p.next.prev = p.prev;
  57940. p.prev.next = p.next;
  57941. if (p.prevZ)
  57942. p.prevZ.nextZ = p.nextZ;
  57943. if (p.nextZ)
  57944. p.nextZ.prevZ = p.prevZ;
  57945. }
  57946. function Node(i, x, y) {
  57947. // vertice index in coordinates array
  57948. this.i = i;
  57949. // vertex coordinates
  57950. this.x = x;
  57951. this.y = y;
  57952. // previous and next vertice nodes in a polygon ring
  57953. this.prev = null;
  57954. this.next = null;
  57955. // z-order curve value
  57956. this.z = null;
  57957. // previous and next nodes in z-order
  57958. this.prevZ = null;
  57959. this.nextZ = null;
  57960. // indicates whether this is a steiner point
  57961. this.steiner = false;
  57962. }
  57963. /**
  57964. * return a percentage difference between the polygon area and its triangulation area;
  57965. * used to verify correctness of triangulation
  57966. */
  57967. function deviation(data, holeIndices, dim, triangles) {
  57968. var hasHoles = holeIndices && holeIndices.length;
  57969. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  57970. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  57971. if (hasHoles) {
  57972. for (var i = 0, len = holeIndices.length; i < len; i++) {
  57973. var start = holeIndices[i] * dim;
  57974. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  57975. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  57976. }
  57977. }
  57978. var trianglesArea = 0;
  57979. for (i = 0; i < triangles.length; i += 3) {
  57980. var a = triangles[i] * dim;
  57981. var b = triangles[i + 1] * dim;
  57982. var c = triangles[i + 2] * dim;
  57983. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  57984. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  57985. }
  57986. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  57987. }
  57988. Earcut.deviation = deviation;
  57989. ;
  57990. function signedArea(data, start, end, dim) {
  57991. var sum = 0;
  57992. for (var i = start, j = end - dim; i < end; i += dim) {
  57993. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  57994. j = i;
  57995. }
  57996. return sum;
  57997. }
  57998. /**
  57999. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  58000. */
  58001. function flatten(data) {
  58002. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  58003. for (var i = 0; i < data.length; i++) {
  58004. for (var j = 0; j < data[i].length; j++) {
  58005. for (var d = 0; d < dim; d++)
  58006. result.vertices.push(data[i][j][d]);
  58007. }
  58008. if (i > 0) {
  58009. holeIndex += data[i - 1].length;
  58010. result.holes.push(holeIndex);
  58011. }
  58012. }
  58013. return result;
  58014. }
  58015. Earcut.flatten = flatten;
  58016. ;
  58017. })(Earcut || (Earcut = {}));
  58018. //# sourceMappingURL=babylon.earcut.js.map
  58019. /// <reference path="..\Math\babylon.math.ts" />
  58020. var BABYLON;
  58021. (function (BABYLON) {
  58022. var IndexedVector2 = (function (_super) {
  58023. __extends(IndexedVector2, _super);
  58024. function IndexedVector2(original, index) {
  58025. var _this = _super.call(this, original.x, original.y) || this;
  58026. _this.index = index;
  58027. return _this;
  58028. }
  58029. return IndexedVector2;
  58030. }(BABYLON.Vector2));
  58031. var PolygonPoints = (function () {
  58032. function PolygonPoints() {
  58033. this.elements = new Array();
  58034. }
  58035. PolygonPoints.prototype.add = function (originalPoints) {
  58036. var _this = this;
  58037. var result = new Array();
  58038. originalPoints.forEach(function (point) {
  58039. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  58040. var newPoint = new IndexedVector2(point, _this.elements.length);
  58041. result.push(newPoint);
  58042. _this.elements.push(newPoint);
  58043. }
  58044. });
  58045. return result;
  58046. };
  58047. PolygonPoints.prototype.computeBounds = function () {
  58048. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  58049. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  58050. this.elements.forEach(function (point) {
  58051. // x
  58052. if (point.x < lmin.x) {
  58053. lmin.x = point.x;
  58054. }
  58055. else if (point.x > lmax.x) {
  58056. lmax.x = point.x;
  58057. }
  58058. // y
  58059. if (point.y < lmin.y) {
  58060. lmin.y = point.y;
  58061. }
  58062. else if (point.y > lmax.y) {
  58063. lmax.y = point.y;
  58064. }
  58065. });
  58066. return {
  58067. min: lmin,
  58068. max: lmax,
  58069. width: lmax.x - lmin.x,
  58070. height: lmax.y - lmin.y
  58071. };
  58072. };
  58073. return PolygonPoints;
  58074. }());
  58075. var Polygon = (function () {
  58076. function Polygon() {
  58077. }
  58078. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  58079. return [
  58080. new BABYLON.Vector2(xmin, ymin),
  58081. new BABYLON.Vector2(xmax, ymin),
  58082. new BABYLON.Vector2(xmax, ymax),
  58083. new BABYLON.Vector2(xmin, ymax)
  58084. ];
  58085. };
  58086. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  58087. if (cx === void 0) { cx = 0; }
  58088. if (cy === void 0) { cy = 0; }
  58089. if (numberOfSides === void 0) { numberOfSides = 32; }
  58090. var result = new Array();
  58091. var angle = 0;
  58092. var increment = (Math.PI * 2) / numberOfSides;
  58093. for (var i = 0; i < numberOfSides; i++) {
  58094. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  58095. angle -= increment;
  58096. }
  58097. return result;
  58098. };
  58099. Polygon.Parse = function (input) {
  58100. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  58101. var i, result = [];
  58102. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  58103. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  58104. }
  58105. return result;
  58106. };
  58107. Polygon.StartingAt = function (x, y) {
  58108. return BABYLON.Path2.StartingAt(x, y);
  58109. };
  58110. return Polygon;
  58111. }());
  58112. BABYLON.Polygon = Polygon;
  58113. var PolygonMeshBuilder = (function () {
  58114. function PolygonMeshBuilder(name, contours, scene) {
  58115. this._points = new PolygonPoints();
  58116. this._outlinepoints = new PolygonPoints();
  58117. this._holes = [];
  58118. this._epoints = new Array();
  58119. this._eholes = new Array();
  58120. this._name = name;
  58121. this._scene = scene;
  58122. var points;
  58123. if (contours instanceof BABYLON.Path2) {
  58124. points = contours.getPoints();
  58125. }
  58126. else {
  58127. points = contours;
  58128. }
  58129. this._addToepoint(points);
  58130. this._points.add(points);
  58131. this._outlinepoints.add(points);
  58132. }
  58133. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  58134. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  58135. var p = points_1[_i];
  58136. this._epoints.push(p.x, p.y);
  58137. }
  58138. };
  58139. PolygonMeshBuilder.prototype.addHole = function (hole) {
  58140. this._points.add(hole);
  58141. var holepoints = new PolygonPoints();
  58142. holepoints.add(hole);
  58143. this._holes.push(holepoints);
  58144. this._eholes.push(this._epoints.length / 2);
  58145. this._addToepoint(hole);
  58146. return this;
  58147. };
  58148. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  58149. var _this = this;
  58150. if (updatable === void 0) { updatable = false; }
  58151. var result = new BABYLON.Mesh(this._name, this._scene);
  58152. var normals = [];
  58153. var positions = [];
  58154. var uvs = [];
  58155. var bounds = this._points.computeBounds();
  58156. this._points.elements.forEach(function (p) {
  58157. normals.push(0, 1.0, 0);
  58158. positions.push(p.x, 0, p.y);
  58159. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  58160. });
  58161. var indices = [];
  58162. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  58163. for (var i = 0; i < res.length; i++) {
  58164. indices.push(res[i]);
  58165. }
  58166. if (depth > 0) {
  58167. var positionscount = (positions.length / 3); //get the current pointcount
  58168. this._points.elements.forEach(function (p) {
  58169. normals.push(0, -1.0, 0);
  58170. positions.push(p.x, -depth, p.y);
  58171. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  58172. });
  58173. var totalCount = indices.length;
  58174. for (var i = 0; i < totalCount; i += 3) {
  58175. var i0 = indices[i + 0];
  58176. var i1 = indices[i + 1];
  58177. var i2 = indices[i + 2];
  58178. indices.push(i2 + positionscount);
  58179. indices.push(i1 + positionscount);
  58180. indices.push(i0 + positionscount);
  58181. }
  58182. //Add the sides
  58183. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  58184. this._holes.forEach(function (hole) {
  58185. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  58186. });
  58187. }
  58188. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  58189. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  58190. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  58191. result.setIndices(indices);
  58192. return result;
  58193. };
  58194. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  58195. var StartIndex = positions.length / 3;
  58196. var ulength = 0;
  58197. for (var i = 0; i < points.elements.length; i++) {
  58198. var p = points.elements[i];
  58199. var p1;
  58200. if ((i + 1) > points.elements.length - 1) {
  58201. p1 = points.elements[0];
  58202. }
  58203. else {
  58204. p1 = points.elements[i + 1];
  58205. }
  58206. positions.push(p.x, 0, p.y);
  58207. positions.push(p.x, -depth, p.y);
  58208. positions.push(p1.x, 0, p1.y);
  58209. positions.push(p1.x, -depth, p1.y);
  58210. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  58211. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  58212. var v3 = v2.subtract(v1);
  58213. var v4 = new BABYLON.Vector3(0, 1, 0);
  58214. var vn = BABYLON.Vector3.Cross(v3, v4);
  58215. vn = vn.normalize();
  58216. uvs.push(ulength / bounds.width, 0);
  58217. uvs.push(ulength / bounds.width, 1);
  58218. ulength += v3.length();
  58219. uvs.push((ulength / bounds.width), 0);
  58220. uvs.push((ulength / bounds.width), 1);
  58221. if (!flip) {
  58222. normals.push(-vn.x, -vn.y, -vn.z);
  58223. normals.push(-vn.x, -vn.y, -vn.z);
  58224. normals.push(-vn.x, -vn.y, -vn.z);
  58225. normals.push(-vn.x, -vn.y, -vn.z);
  58226. indices.push(StartIndex);
  58227. indices.push(StartIndex + 1);
  58228. indices.push(StartIndex + 2);
  58229. indices.push(StartIndex + 1);
  58230. indices.push(StartIndex + 3);
  58231. indices.push(StartIndex + 2);
  58232. }
  58233. else {
  58234. normals.push(vn.x, vn.y, vn.z);
  58235. normals.push(vn.x, vn.y, vn.z);
  58236. normals.push(vn.x, vn.y, vn.z);
  58237. normals.push(vn.x, vn.y, vn.z);
  58238. indices.push(StartIndex);
  58239. indices.push(StartIndex + 2);
  58240. indices.push(StartIndex + 1);
  58241. indices.push(StartIndex + 1);
  58242. indices.push(StartIndex + 2);
  58243. indices.push(StartIndex + 3);
  58244. }
  58245. StartIndex += 4;
  58246. }
  58247. ;
  58248. };
  58249. return PolygonMeshBuilder;
  58250. }());
  58251. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  58252. })(BABYLON || (BABYLON = {}));
  58253. //# sourceMappingURL=babylon.polygonMesh.js.map
  58254. var BABYLON;
  58255. (function (BABYLON) {
  58256. // Unique ID when we import meshes from Babylon to CSG
  58257. var currentCSGMeshId = 0;
  58258. // # class Vertex
  58259. // Represents a vertex of a polygon. Use your own vertex class instead of this
  58260. // one to provide additional features like texture coordinates and vertex
  58261. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  58262. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  58263. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  58264. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  58265. // is not used anywhere else.
  58266. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  58267. var Vertex = (function () {
  58268. function Vertex(pos, normal, uv) {
  58269. this.pos = pos;
  58270. this.normal = normal;
  58271. this.uv = uv;
  58272. }
  58273. Vertex.prototype.clone = function () {
  58274. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  58275. };
  58276. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  58277. // orientation of a polygon is flipped.
  58278. Vertex.prototype.flip = function () {
  58279. this.normal = this.normal.scale(-1);
  58280. };
  58281. // Create a new vertex between this vertex and `other` by linearly
  58282. // interpolating all properties using a parameter of `t`. Subclasses should
  58283. // override this to interpolate additional properties.
  58284. Vertex.prototype.interpolate = function (other, t) {
  58285. 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));
  58286. };
  58287. return Vertex;
  58288. }());
  58289. // # class Plane
  58290. // Represents a plane in 3D space.
  58291. var Plane = (function () {
  58292. function Plane(normal, w) {
  58293. this.normal = normal;
  58294. this.w = w;
  58295. }
  58296. Plane.FromPoints = function (a, b, c) {
  58297. var v0 = c.subtract(a);
  58298. var v1 = b.subtract(a);
  58299. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  58300. return null;
  58301. }
  58302. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  58303. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  58304. };
  58305. Plane.prototype.clone = function () {
  58306. return new Plane(this.normal.clone(), this.w);
  58307. };
  58308. Plane.prototype.flip = function () {
  58309. this.normal.scaleInPlace(-1);
  58310. this.w = -this.w;
  58311. };
  58312. // Split `polygon` by this plane if needed, then put the polygon or polygon
  58313. // fragments in the appropriate lists. Coplanar polygons go into either
  58314. // `coplanarFront` or `coplanarBack` depending on their orientation with
  58315. // respect to this plane. Polygons in front or in back of this plane go into
  58316. // either `front` or `back`.
  58317. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  58318. var COPLANAR = 0;
  58319. var FRONT = 1;
  58320. var BACK = 2;
  58321. var SPANNING = 3;
  58322. // Classify each point as well as the entire polygon into one of the above
  58323. // four classes.
  58324. var polygonType = 0;
  58325. var types = [];
  58326. var i;
  58327. var t;
  58328. for (i = 0; i < polygon.vertices.length; i++) {
  58329. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  58330. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  58331. polygonType |= type;
  58332. types.push(type);
  58333. }
  58334. // Put the polygon in the correct list, splitting it when necessary.
  58335. switch (polygonType) {
  58336. case COPLANAR:
  58337. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  58338. break;
  58339. case FRONT:
  58340. front.push(polygon);
  58341. break;
  58342. case BACK:
  58343. back.push(polygon);
  58344. break;
  58345. case SPANNING:
  58346. var f = [], b = [];
  58347. for (i = 0; i < polygon.vertices.length; i++) {
  58348. var j = (i + 1) % polygon.vertices.length;
  58349. var ti = types[i], tj = types[j];
  58350. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  58351. if (ti !== BACK)
  58352. f.push(vi);
  58353. if (ti !== FRONT)
  58354. b.push(ti !== BACK ? vi.clone() : vi);
  58355. if ((ti | tj) === SPANNING) {
  58356. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  58357. var v = vi.interpolate(vj, t);
  58358. f.push(v);
  58359. b.push(v.clone());
  58360. }
  58361. }
  58362. var poly;
  58363. if (f.length >= 3) {
  58364. poly = new Polygon(f, polygon.shared);
  58365. if (poly.plane)
  58366. front.push(poly);
  58367. }
  58368. if (b.length >= 3) {
  58369. poly = new Polygon(b, polygon.shared);
  58370. if (poly.plane)
  58371. back.push(poly);
  58372. }
  58373. break;
  58374. }
  58375. };
  58376. return Plane;
  58377. }());
  58378. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  58379. // point is on the plane.
  58380. Plane.EPSILON = 1e-5;
  58381. // # class Polygon
  58382. // Represents a convex polygon. The vertices used to initialize a polygon must
  58383. // be coplanar and form a convex loop.
  58384. //
  58385. // Each convex polygon has a `shared` property, which is shared between all
  58386. // polygons that are clones of each other or were split from the same polygon.
  58387. // This can be used to define per-polygon properties (such as surface color).
  58388. var Polygon = (function () {
  58389. function Polygon(vertices, shared) {
  58390. this.vertices = vertices;
  58391. this.shared = shared;
  58392. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  58393. }
  58394. Polygon.prototype.clone = function () {
  58395. var vertices = this.vertices.map(function (v) { return v.clone(); });
  58396. return new Polygon(vertices, this.shared);
  58397. };
  58398. Polygon.prototype.flip = function () {
  58399. this.vertices.reverse().map(function (v) { v.flip(); });
  58400. this.plane.flip();
  58401. };
  58402. return Polygon;
  58403. }());
  58404. // # class Node
  58405. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  58406. // by picking a polygon to split along. That polygon (and all other coplanar
  58407. // polygons) are added directly to that node and the other polygons are added to
  58408. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  58409. // no distinction between internal and leaf nodes.
  58410. var Node = (function () {
  58411. function Node(polygons) {
  58412. this.plane = null;
  58413. this.front = null;
  58414. this.back = null;
  58415. this.polygons = [];
  58416. if (polygons) {
  58417. this.build(polygons);
  58418. }
  58419. }
  58420. Node.prototype.clone = function () {
  58421. var node = new Node();
  58422. node.plane = this.plane && this.plane.clone();
  58423. node.front = this.front && this.front.clone();
  58424. node.back = this.back && this.back.clone();
  58425. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  58426. return node;
  58427. };
  58428. // Convert solid space to empty space and empty space to solid space.
  58429. Node.prototype.invert = function () {
  58430. for (var i = 0; i < this.polygons.length; i++) {
  58431. this.polygons[i].flip();
  58432. }
  58433. if (this.plane) {
  58434. this.plane.flip();
  58435. }
  58436. if (this.front) {
  58437. this.front.invert();
  58438. }
  58439. if (this.back) {
  58440. this.back.invert();
  58441. }
  58442. var temp = this.front;
  58443. this.front = this.back;
  58444. this.back = temp;
  58445. };
  58446. // Recursively remove all polygons in `polygons` that are inside this BSP
  58447. // tree.
  58448. Node.prototype.clipPolygons = function (polygons) {
  58449. if (!this.plane)
  58450. return polygons.slice();
  58451. var front = [], back = [];
  58452. for (var i = 0; i < polygons.length; i++) {
  58453. this.plane.splitPolygon(polygons[i], front, back, front, back);
  58454. }
  58455. if (this.front) {
  58456. front = this.front.clipPolygons(front);
  58457. }
  58458. if (this.back) {
  58459. back = this.back.clipPolygons(back);
  58460. }
  58461. else {
  58462. back = [];
  58463. }
  58464. return front.concat(back);
  58465. };
  58466. // Remove all polygons in this BSP tree that are inside the other BSP tree
  58467. // `bsp`.
  58468. Node.prototype.clipTo = function (bsp) {
  58469. this.polygons = bsp.clipPolygons(this.polygons);
  58470. if (this.front)
  58471. this.front.clipTo(bsp);
  58472. if (this.back)
  58473. this.back.clipTo(bsp);
  58474. };
  58475. // Return a list of all polygons in this BSP tree.
  58476. Node.prototype.allPolygons = function () {
  58477. var polygons = this.polygons.slice();
  58478. if (this.front)
  58479. polygons = polygons.concat(this.front.allPolygons());
  58480. if (this.back)
  58481. polygons = polygons.concat(this.back.allPolygons());
  58482. return polygons;
  58483. };
  58484. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  58485. // new polygons are filtered down to the bottom of the tree and become new
  58486. // nodes there. Each set of polygons is partitioned using the first polygon
  58487. // (no heuristic is used to pick a good split).
  58488. Node.prototype.build = function (polygons) {
  58489. if (!polygons.length)
  58490. return;
  58491. if (!this.plane)
  58492. this.plane = polygons[0].plane.clone();
  58493. var front = [], back = [];
  58494. for (var i = 0; i < polygons.length; i++) {
  58495. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  58496. }
  58497. if (front.length) {
  58498. if (!this.front)
  58499. this.front = new Node();
  58500. this.front.build(front);
  58501. }
  58502. if (back.length) {
  58503. if (!this.back)
  58504. this.back = new Node();
  58505. this.back.build(back);
  58506. }
  58507. };
  58508. return Node;
  58509. }());
  58510. var CSG = (function () {
  58511. function CSG() {
  58512. this.polygons = new Array();
  58513. }
  58514. // Convert BABYLON.Mesh to BABYLON.CSG
  58515. CSG.FromMesh = function (mesh) {
  58516. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  58517. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  58518. if (mesh instanceof BABYLON.Mesh) {
  58519. mesh.computeWorldMatrix(true);
  58520. matrix = mesh.getWorldMatrix();
  58521. meshPosition = mesh.position.clone();
  58522. meshRotation = mesh.rotation.clone();
  58523. if (mesh.rotationQuaternion) {
  58524. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  58525. }
  58526. meshScaling = mesh.scaling.clone();
  58527. }
  58528. else {
  58529. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  58530. }
  58531. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58532. var subMeshes = mesh.subMeshes;
  58533. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  58534. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  58535. vertices = [];
  58536. for (var j = 0; j < 3; j++) {
  58537. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  58538. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  58539. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  58540. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  58541. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  58542. vertex = new Vertex(position, normal, uv);
  58543. vertices.push(vertex);
  58544. }
  58545. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  58546. // To handle the case of degenerated triangle
  58547. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  58548. if (polygon.plane)
  58549. polygons.push(polygon);
  58550. }
  58551. }
  58552. var csg = CSG.FromPolygons(polygons);
  58553. csg.matrix = matrix;
  58554. csg.position = meshPosition;
  58555. csg.rotation = meshRotation;
  58556. csg.scaling = meshScaling;
  58557. csg.rotationQuaternion = meshRotationQuaternion;
  58558. currentCSGMeshId++;
  58559. return csg;
  58560. };
  58561. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  58562. CSG.FromPolygons = function (polygons) {
  58563. var csg = new CSG();
  58564. csg.polygons = polygons;
  58565. return csg;
  58566. };
  58567. CSG.prototype.clone = function () {
  58568. var csg = new CSG();
  58569. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  58570. csg.copyTransformAttributes(this);
  58571. return csg;
  58572. };
  58573. CSG.prototype.toPolygons = function () {
  58574. return this.polygons;
  58575. };
  58576. CSG.prototype.union = function (csg) {
  58577. var a = new Node(this.clone().polygons);
  58578. var b = new Node(csg.clone().polygons);
  58579. a.clipTo(b);
  58580. b.clipTo(a);
  58581. b.invert();
  58582. b.clipTo(a);
  58583. b.invert();
  58584. a.build(b.allPolygons());
  58585. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  58586. };
  58587. CSG.prototype.unionInPlace = function (csg) {
  58588. var a = new Node(this.polygons);
  58589. var b = new Node(csg.polygons);
  58590. a.clipTo(b);
  58591. b.clipTo(a);
  58592. b.invert();
  58593. b.clipTo(a);
  58594. b.invert();
  58595. a.build(b.allPolygons());
  58596. this.polygons = a.allPolygons();
  58597. };
  58598. CSG.prototype.subtract = function (csg) {
  58599. var a = new Node(this.clone().polygons);
  58600. var b = new Node(csg.clone().polygons);
  58601. a.invert();
  58602. a.clipTo(b);
  58603. b.clipTo(a);
  58604. b.invert();
  58605. b.clipTo(a);
  58606. b.invert();
  58607. a.build(b.allPolygons());
  58608. a.invert();
  58609. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  58610. };
  58611. CSG.prototype.subtractInPlace = function (csg) {
  58612. var a = new Node(this.polygons);
  58613. var b = new Node(csg.polygons);
  58614. a.invert();
  58615. a.clipTo(b);
  58616. b.clipTo(a);
  58617. b.invert();
  58618. b.clipTo(a);
  58619. b.invert();
  58620. a.build(b.allPolygons());
  58621. a.invert();
  58622. this.polygons = a.allPolygons();
  58623. };
  58624. CSG.prototype.intersect = function (csg) {
  58625. var a = new Node(this.clone().polygons);
  58626. var b = new Node(csg.clone().polygons);
  58627. a.invert();
  58628. b.clipTo(a);
  58629. b.invert();
  58630. a.clipTo(b);
  58631. b.clipTo(a);
  58632. a.build(b.allPolygons());
  58633. a.invert();
  58634. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  58635. };
  58636. CSG.prototype.intersectInPlace = function (csg) {
  58637. var a = new Node(this.polygons);
  58638. var b = new Node(csg.polygons);
  58639. a.invert();
  58640. b.clipTo(a);
  58641. b.invert();
  58642. a.clipTo(b);
  58643. b.clipTo(a);
  58644. a.build(b.allPolygons());
  58645. a.invert();
  58646. this.polygons = a.allPolygons();
  58647. };
  58648. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  58649. // not modified.
  58650. CSG.prototype.inverse = function () {
  58651. var csg = this.clone();
  58652. csg.inverseInPlace();
  58653. return csg;
  58654. };
  58655. CSG.prototype.inverseInPlace = function () {
  58656. this.polygons.map(function (p) { p.flip(); });
  58657. };
  58658. // This is used to keep meshes transformations so they can be restored
  58659. // when we build back a Babylon Mesh
  58660. // NB : All CSG operations are performed in world coordinates
  58661. CSG.prototype.copyTransformAttributes = function (csg) {
  58662. this.matrix = csg.matrix;
  58663. this.position = csg.position;
  58664. this.rotation = csg.rotation;
  58665. this.scaling = csg.scaling;
  58666. this.rotationQuaternion = csg.rotationQuaternion;
  58667. return this;
  58668. };
  58669. // Build Raw mesh from CSG
  58670. // Coordinates here are in world space
  58671. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  58672. var matrix = this.matrix.clone();
  58673. matrix.invert();
  58674. 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;
  58675. if (keepSubMeshes) {
  58676. // Sort Polygons, since subMeshes are indices range
  58677. polygons.sort(function (a, b) {
  58678. if (a.shared.meshId === b.shared.meshId) {
  58679. return a.shared.subMeshId - b.shared.subMeshId;
  58680. }
  58681. else {
  58682. return a.shared.meshId - b.shared.meshId;
  58683. }
  58684. });
  58685. }
  58686. for (var i = 0, il = polygons.length; i < il; i++) {
  58687. polygon = polygons[i];
  58688. // Building SubMeshes
  58689. if (!subMesh_dict[polygon.shared.meshId]) {
  58690. subMesh_dict[polygon.shared.meshId] = {};
  58691. }
  58692. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  58693. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  58694. indexStart: +Infinity,
  58695. indexEnd: -Infinity,
  58696. materialIndex: polygon.shared.materialIndex
  58697. };
  58698. }
  58699. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  58700. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  58701. polygonIndices[0] = 0;
  58702. polygonIndices[1] = j - 1;
  58703. polygonIndices[2] = j;
  58704. for (var k = 0; k < 3; k++) {
  58705. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  58706. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  58707. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  58708. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  58709. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  58710. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  58711. // Check if 2 points can be merged
  58712. if (!(typeof vertex_idx !== 'undefined' &&
  58713. normals[vertex_idx * 3] === localNormal.x &&
  58714. normals[vertex_idx * 3 + 1] === localNormal.y &&
  58715. normals[vertex_idx * 3 + 2] === localNormal.z &&
  58716. uvs[vertex_idx * 2] === uv.x &&
  58717. uvs[vertex_idx * 2 + 1] === uv.y)) {
  58718. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  58719. uvs.push(uv.x, uv.y);
  58720. normals.push(normal.x, normal.y, normal.z);
  58721. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  58722. }
  58723. indices.push(vertex_idx);
  58724. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  58725. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  58726. currentIndex++;
  58727. }
  58728. }
  58729. }
  58730. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  58731. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  58732. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  58733. mesh.setIndices(indices);
  58734. if (keepSubMeshes) {
  58735. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  58736. var materialIndexOffset = 0, materialMaxIndex;
  58737. mesh.subMeshes = new Array();
  58738. for (var m in subMesh_dict) {
  58739. materialMaxIndex = -1;
  58740. for (var sm in subMesh_dict[m]) {
  58741. subMesh_obj = subMesh_dict[m][sm];
  58742. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  58743. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  58744. }
  58745. materialIndexOffset += ++materialMaxIndex;
  58746. }
  58747. }
  58748. return mesh;
  58749. };
  58750. // Build Mesh from CSG taking material and transforms into account
  58751. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  58752. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  58753. mesh.material = material;
  58754. mesh.position.copyFrom(this.position);
  58755. mesh.rotation.copyFrom(this.rotation);
  58756. if (this.rotationQuaternion) {
  58757. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  58758. }
  58759. mesh.scaling.copyFrom(this.scaling);
  58760. mesh.computeWorldMatrix(true);
  58761. return mesh;
  58762. };
  58763. return CSG;
  58764. }());
  58765. BABYLON.CSG = CSG;
  58766. })(BABYLON || (BABYLON = {}));
  58767. //# sourceMappingURL=babylon.csg.js.map
  58768. var BABYLON;
  58769. (function (BABYLON) {
  58770. var LensFlare = (function () {
  58771. function LensFlare(size, position, color, imgUrl, system) {
  58772. this.size = size;
  58773. this.position = position;
  58774. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  58775. this.dispose = function () {
  58776. if (this.texture) {
  58777. this.texture.dispose();
  58778. }
  58779. // Remove from scene
  58780. var index = this._system.lensFlares.indexOf(this);
  58781. this._system.lensFlares.splice(index, 1);
  58782. };
  58783. this.color = color || new BABYLON.Color3(1, 1, 1);
  58784. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  58785. this._system = system;
  58786. system.lensFlares.push(this);
  58787. }
  58788. return LensFlare;
  58789. }());
  58790. BABYLON.LensFlare = LensFlare;
  58791. })(BABYLON || (BABYLON = {}));
  58792. //# sourceMappingURL=babylon.lensFlare.js.map
  58793. var BABYLON;
  58794. (function (BABYLON) {
  58795. var LensFlareSystem = (function () {
  58796. function LensFlareSystem(name, emitter, scene) {
  58797. this.name = name;
  58798. this.lensFlares = new Array();
  58799. this.borderLimit = 300;
  58800. this.viewportBorder = 0;
  58801. this.layerMask = 0x0FFFFFFF;
  58802. this._vertexBuffers = {};
  58803. this._isEnabled = true;
  58804. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58805. this._emitter = emitter;
  58806. this.id = name;
  58807. scene.lensFlareSystems.push(this);
  58808. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  58809. var engine = scene.getEngine();
  58810. // VBO
  58811. var vertices = [];
  58812. vertices.push(1, 1);
  58813. vertices.push(-1, 1);
  58814. vertices.push(-1, -1);
  58815. vertices.push(1, -1);
  58816. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  58817. // Indices
  58818. var indices = [];
  58819. indices.push(0);
  58820. indices.push(1);
  58821. indices.push(2);
  58822. indices.push(0);
  58823. indices.push(2);
  58824. indices.push(3);
  58825. this._indexBuffer = engine.createIndexBuffer(indices);
  58826. // Effects
  58827. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  58828. }
  58829. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  58830. get: function () {
  58831. return this._isEnabled;
  58832. },
  58833. set: function (value) {
  58834. this._isEnabled = value;
  58835. },
  58836. enumerable: true,
  58837. configurable: true
  58838. });
  58839. LensFlareSystem.prototype.getScene = function () {
  58840. return this._scene;
  58841. };
  58842. LensFlareSystem.prototype.getEmitter = function () {
  58843. return this._emitter;
  58844. };
  58845. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  58846. this._emitter = newEmitter;
  58847. };
  58848. LensFlareSystem.prototype.getEmitterPosition = function () {
  58849. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  58850. };
  58851. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  58852. var position = this.getEmitterPosition();
  58853. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  58854. this._positionX = position.x;
  58855. this._positionY = position.y;
  58856. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  58857. if (this.viewportBorder > 0) {
  58858. globalViewport.x -= this.viewportBorder;
  58859. globalViewport.y -= this.viewportBorder;
  58860. globalViewport.width += this.viewportBorder * 2;
  58861. globalViewport.height += this.viewportBorder * 2;
  58862. position.x += this.viewportBorder;
  58863. position.y += this.viewportBorder;
  58864. this._positionX += this.viewportBorder;
  58865. this._positionY += this.viewportBorder;
  58866. }
  58867. if (position.z > 0) {
  58868. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  58869. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  58870. return true;
  58871. }
  58872. return true;
  58873. }
  58874. return false;
  58875. };
  58876. LensFlareSystem.prototype._isVisible = function () {
  58877. if (!this._isEnabled) {
  58878. return false;
  58879. }
  58880. var emitterPosition = this.getEmitterPosition();
  58881. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  58882. var distance = direction.length();
  58883. direction.normalize();
  58884. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  58885. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  58886. return !pickInfo.hit || pickInfo.distance > distance;
  58887. };
  58888. LensFlareSystem.prototype.render = function () {
  58889. if (!this._effect.isReady())
  58890. return false;
  58891. var engine = this._scene.getEngine();
  58892. var viewport = this._scene.activeCamera.viewport;
  58893. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  58894. // Position
  58895. if (!this.computeEffectivePosition(globalViewport)) {
  58896. return false;
  58897. }
  58898. // Visibility
  58899. if (!this._isVisible()) {
  58900. return false;
  58901. }
  58902. // Intensity
  58903. var awayX;
  58904. var awayY;
  58905. if (this._positionX < this.borderLimit + globalViewport.x) {
  58906. awayX = this.borderLimit + globalViewport.x - this._positionX;
  58907. }
  58908. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  58909. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  58910. }
  58911. else {
  58912. awayX = 0;
  58913. }
  58914. if (this._positionY < this.borderLimit + globalViewport.y) {
  58915. awayY = this.borderLimit + globalViewport.y - this._positionY;
  58916. }
  58917. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  58918. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  58919. }
  58920. else {
  58921. awayY = 0;
  58922. }
  58923. var away = (awayX > awayY) ? awayX : awayY;
  58924. away -= this.viewportBorder;
  58925. if (away > this.borderLimit) {
  58926. away = this.borderLimit;
  58927. }
  58928. var intensity = 1.0 - (away / this.borderLimit);
  58929. if (intensity < 0) {
  58930. return false;
  58931. }
  58932. if (intensity > 1.0) {
  58933. intensity = 1.0;
  58934. }
  58935. if (this.viewportBorder > 0) {
  58936. globalViewport.x += this.viewportBorder;
  58937. globalViewport.y += this.viewportBorder;
  58938. globalViewport.width -= this.viewportBorder * 2;
  58939. globalViewport.height -= this.viewportBorder * 2;
  58940. this._positionX -= this.viewportBorder;
  58941. this._positionY -= this.viewportBorder;
  58942. }
  58943. // Position
  58944. var centerX = globalViewport.x + globalViewport.width / 2;
  58945. var centerY = globalViewport.y + globalViewport.height / 2;
  58946. var distX = centerX - this._positionX;
  58947. var distY = centerY - this._positionY;
  58948. // Effects
  58949. engine.enableEffect(this._effect);
  58950. engine.setState(false);
  58951. engine.setDepthBuffer(false);
  58952. // VBOs
  58953. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  58954. // Flares
  58955. for (var index = 0; index < this.lensFlares.length; index++) {
  58956. var flare = this.lensFlares[index];
  58957. engine.setAlphaMode(flare.alphaMode);
  58958. var x = centerX - (distX * flare.position);
  58959. var y = centerY - (distY * flare.position);
  58960. var cw = flare.size;
  58961. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  58962. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  58963. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  58964. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  58965. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  58966. // Texture
  58967. this._effect.setTexture("textureSampler", flare.texture);
  58968. // Color
  58969. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  58970. // Draw order
  58971. engine.draw(true, 0, 6);
  58972. }
  58973. engine.setDepthBuffer(true);
  58974. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  58975. return true;
  58976. };
  58977. LensFlareSystem.prototype.dispose = function () {
  58978. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  58979. if (vertexBuffer) {
  58980. vertexBuffer.dispose();
  58981. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  58982. }
  58983. if (this._indexBuffer) {
  58984. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  58985. this._indexBuffer = null;
  58986. }
  58987. while (this.lensFlares.length) {
  58988. this.lensFlares[0].dispose();
  58989. }
  58990. // Remove from scene
  58991. var index = this._scene.lensFlareSystems.indexOf(this);
  58992. this._scene.lensFlareSystems.splice(index, 1);
  58993. };
  58994. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  58995. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  58996. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  58997. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  58998. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  58999. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  59000. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  59001. var parsedFlare = parsedLensFlareSystem.flares[index];
  59002. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  59003. }
  59004. return lensFlareSystem;
  59005. };
  59006. LensFlareSystem.prototype.serialize = function () {
  59007. var serializationObject = {};
  59008. serializationObject.id = this.id;
  59009. serializationObject.name = this.name;
  59010. serializationObject.emitterId = this.getEmitter().id;
  59011. serializationObject.borderLimit = this.borderLimit;
  59012. serializationObject.flares = [];
  59013. for (var index = 0; index < this.lensFlares.length; index++) {
  59014. var flare = this.lensFlares[index];
  59015. serializationObject.flares.push({
  59016. size: flare.size,
  59017. position: flare.position,
  59018. color: flare.color.asArray(),
  59019. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  59020. });
  59021. }
  59022. return serializationObject;
  59023. };
  59024. return LensFlareSystem;
  59025. }());
  59026. BABYLON.LensFlareSystem = LensFlareSystem;
  59027. })(BABYLON || (BABYLON = {}));
  59028. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  59029. var BABYLON;
  59030. (function (BABYLON) {
  59031. /**
  59032. * This is a holder class for the physics joint created by the physics plugin.
  59033. * It holds a set of functions to control the underlying joint.
  59034. */
  59035. var PhysicsJoint = (function () {
  59036. function PhysicsJoint(type, jointData) {
  59037. this.type = type;
  59038. this.jointData = jointData;
  59039. jointData.nativeParams = jointData.nativeParams || {};
  59040. }
  59041. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  59042. get: function () {
  59043. return this._physicsJoint;
  59044. },
  59045. set: function (newJoint) {
  59046. if (this._physicsJoint) {
  59047. //remove from the wolrd
  59048. }
  59049. this._physicsJoint = newJoint;
  59050. },
  59051. enumerable: true,
  59052. configurable: true
  59053. });
  59054. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  59055. set: function (physicsPlugin) {
  59056. this._physicsPlugin = physicsPlugin;
  59057. },
  59058. enumerable: true,
  59059. configurable: true
  59060. });
  59061. /**
  59062. * Execute a function that is physics-plugin specific.
  59063. * @param {Function} func the function that will be executed.
  59064. * It accepts two parameters: the physics world and the physics joint.
  59065. */
  59066. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  59067. func(this._physicsPlugin.world, this._physicsJoint);
  59068. };
  59069. return PhysicsJoint;
  59070. }());
  59071. //TODO check if the native joints are the same
  59072. //Joint Types
  59073. PhysicsJoint.DistanceJoint = 0;
  59074. PhysicsJoint.HingeJoint = 1;
  59075. PhysicsJoint.BallAndSocketJoint = 2;
  59076. PhysicsJoint.WheelJoint = 3;
  59077. PhysicsJoint.SliderJoint = 4;
  59078. //OIMO
  59079. PhysicsJoint.PrismaticJoint = 5;
  59080. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  59081. PhysicsJoint.UniversalJoint = 6;
  59082. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  59083. //Cannon
  59084. //Similar to a Ball-Joint. Different in params
  59085. PhysicsJoint.PointToPointJoint = 8;
  59086. //Cannon only at the moment
  59087. PhysicsJoint.SpringJoint = 9;
  59088. PhysicsJoint.LockJoint = 10;
  59089. BABYLON.PhysicsJoint = PhysicsJoint;
  59090. /**
  59091. * A class representing a physics distance joint.
  59092. */
  59093. var DistanceJoint = (function (_super) {
  59094. __extends(DistanceJoint, _super);
  59095. function DistanceJoint(jointData) {
  59096. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  59097. }
  59098. /**
  59099. * Update the predefined distance.
  59100. */
  59101. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  59102. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  59103. };
  59104. return DistanceJoint;
  59105. }(PhysicsJoint));
  59106. BABYLON.DistanceJoint = DistanceJoint;
  59107. var MotorEnabledJoint = (function (_super) {
  59108. __extends(MotorEnabledJoint, _super);
  59109. function MotorEnabledJoint(type, jointData) {
  59110. return _super.call(this, type, jointData) || this;
  59111. }
  59112. /**
  59113. * Set the motor values.
  59114. * Attention, this function is plugin specific. Engines won't react 100% the same.
  59115. * @param {number} force the force to apply
  59116. * @param {number} maxForce max force for this motor.
  59117. */
  59118. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  59119. this._physicsPlugin.setMotor(this, force, maxForce);
  59120. };
  59121. /**
  59122. * Set the motor's limits.
  59123. * Attention, this function is plugin specific. Engines won't react 100% the same.
  59124. */
  59125. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  59126. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  59127. };
  59128. return MotorEnabledJoint;
  59129. }(PhysicsJoint));
  59130. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  59131. /**
  59132. * This class represents a single hinge physics joint
  59133. */
  59134. var HingeJoint = (function (_super) {
  59135. __extends(HingeJoint, _super);
  59136. function HingeJoint(jointData) {
  59137. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  59138. }
  59139. /**
  59140. * Set the motor values.
  59141. * Attention, this function is plugin specific. Engines won't react 100% the same.
  59142. * @param {number} force the force to apply
  59143. * @param {number} maxForce max force for this motor.
  59144. */
  59145. HingeJoint.prototype.setMotor = function (force, maxForce) {
  59146. this._physicsPlugin.setMotor(this, force, maxForce);
  59147. };
  59148. /**
  59149. * Set the motor's limits.
  59150. * Attention, this function is plugin specific. Engines won't react 100% the same.
  59151. */
  59152. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  59153. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  59154. };
  59155. return HingeJoint;
  59156. }(MotorEnabledJoint));
  59157. BABYLON.HingeJoint = HingeJoint;
  59158. /**
  59159. * This class represents a dual hinge physics joint (same as wheel joint)
  59160. */
  59161. var Hinge2Joint = (function (_super) {
  59162. __extends(Hinge2Joint, _super);
  59163. function Hinge2Joint(jointData) {
  59164. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  59165. }
  59166. /**
  59167. * Set the motor values.
  59168. * Attention, this function is plugin specific. Engines won't react 100% the same.
  59169. * @param {number} force the force to apply
  59170. * @param {number} maxForce max force for this motor.
  59171. * @param {motorIndex} the motor's index, 0 or 1.
  59172. */
  59173. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  59174. if (motorIndex === void 0) { motorIndex = 0; }
  59175. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  59176. };
  59177. /**
  59178. * Set the motor limits.
  59179. * Attention, this function is plugin specific. Engines won't react 100% the same.
  59180. * @param {number} upperLimit the upper limit
  59181. * @param {number} lowerLimit lower limit
  59182. * @param {motorIndex} the motor's index, 0 or 1.
  59183. */
  59184. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  59185. if (motorIndex === void 0) { motorIndex = 0; }
  59186. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  59187. };
  59188. return Hinge2Joint;
  59189. }(MotorEnabledJoint));
  59190. BABYLON.Hinge2Joint = Hinge2Joint;
  59191. })(BABYLON || (BABYLON = {}));
  59192. //# sourceMappingURL=babylon.physicsJoint.js.map
  59193. var BABYLON;
  59194. (function (BABYLON) {
  59195. var PhysicsImpostor = (function () {
  59196. function PhysicsImpostor(object, type, _options, _scene) {
  59197. if (_options === void 0) { _options = { mass: 0 }; }
  59198. var _this = this;
  59199. this.object = object;
  59200. this.type = type;
  59201. this._options = _options;
  59202. this._scene = _scene;
  59203. this._bodyUpdateRequired = false;
  59204. this._onBeforePhysicsStepCallbacks = new Array();
  59205. this._onAfterPhysicsStepCallbacks = new Array();
  59206. this._onPhysicsCollideCallbacks = [];
  59207. this._deltaPosition = BABYLON.Vector3.Zero();
  59208. this._isDisposed = false;
  59209. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  59210. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  59211. /**
  59212. * this function is executed by the physics engine.
  59213. */
  59214. this.beforeStep = function () {
  59215. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  59216. //conjugate deltaRotation
  59217. if (_this._deltaRotationConjugated) {
  59218. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  59219. }
  59220. else {
  59221. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  59222. }
  59223. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  59224. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  59225. func(_this);
  59226. });
  59227. };
  59228. /**
  59229. * this function is executed by the physics engine.
  59230. */
  59231. this.afterStep = function () {
  59232. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  59233. func(_this);
  59234. });
  59235. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  59236. _this.object.position.addInPlace(_this._deltaPosition);
  59237. if (_this._deltaRotation) {
  59238. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  59239. }
  59240. };
  59241. /**
  59242. * Legacy collision detection event support
  59243. */
  59244. this.onCollideEvent = null;
  59245. //event and body object due to cannon's event-based architecture.
  59246. this.onCollide = function (e) {
  59247. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  59248. return;
  59249. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  59250. if (otherImpostor) {
  59251. // Legacy collision detection event support
  59252. if (_this.onCollideEvent) {
  59253. _this.onCollideEvent(_this, otherImpostor);
  59254. }
  59255. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  59256. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  59257. }).forEach(function (obj) {
  59258. obj.callback(_this, otherImpostor);
  59259. });
  59260. }
  59261. };
  59262. //sanity check!
  59263. if (!this.object) {
  59264. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  59265. return;
  59266. }
  59267. //legacy support for old syntax.
  59268. if (!this._scene && object.getScene) {
  59269. this._scene = object.getScene();
  59270. }
  59271. this._physicsEngine = this._scene.getPhysicsEngine();
  59272. if (!this._physicsEngine) {
  59273. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  59274. }
  59275. else {
  59276. //set the object's quaternion, if not set
  59277. if (!this.object.rotationQuaternion) {
  59278. if (this.object.rotation) {
  59279. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  59280. }
  59281. else {
  59282. this.object.rotationQuaternion = new BABYLON.Quaternion();
  59283. }
  59284. }
  59285. //default options params
  59286. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  59287. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  59288. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  59289. this._joints = [];
  59290. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  59291. if (!this.object.parent) {
  59292. this._init();
  59293. }
  59294. else if (this.object.parent.physicsImpostor) {
  59295. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  59296. }
  59297. }
  59298. }
  59299. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  59300. get: function () {
  59301. return this._isDisposed;
  59302. },
  59303. enumerable: true,
  59304. configurable: true
  59305. });
  59306. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  59307. get: function () {
  59308. return this._physicsEngine.getPhysicsPlugin().getBodyMass(this);
  59309. },
  59310. set: function (value) {
  59311. this.setMass(value);
  59312. },
  59313. enumerable: true,
  59314. configurable: true
  59315. });
  59316. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  59317. get: function () {
  59318. return this._physicsEngine.getPhysicsPlugin().getBodyFriction(this);
  59319. },
  59320. set: function (value) {
  59321. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  59322. },
  59323. enumerable: true,
  59324. configurable: true
  59325. });
  59326. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  59327. get: function () {
  59328. return this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this);
  59329. },
  59330. set: function (value) {
  59331. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  59332. },
  59333. enumerable: true,
  59334. configurable: true
  59335. });
  59336. /**
  59337. * This function will completly initialize this impostor.
  59338. * It will create a new body - but only if this mesh has no parent.
  59339. * If it has, this impostor will not be used other than to define the impostor
  59340. * of the child mesh.
  59341. */
  59342. PhysicsImpostor.prototype._init = function () {
  59343. this._physicsEngine.removeImpostor(this);
  59344. this.physicsBody = null;
  59345. this._parent = this._parent || this._getPhysicsParent();
  59346. if (!this.parent) {
  59347. this._physicsEngine.addImpostor(this);
  59348. }
  59349. };
  59350. PhysicsImpostor.prototype._getPhysicsParent = function () {
  59351. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  59352. var parentMesh = this.object.parent;
  59353. return parentMesh.physicsImpostor;
  59354. }
  59355. return;
  59356. };
  59357. /**
  59358. * Should a new body be generated.
  59359. */
  59360. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  59361. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  59362. };
  59363. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  59364. this.forceUpdate();
  59365. };
  59366. /**
  59367. * Force a regeneration of this or the parent's impostor's body.
  59368. * Use under cautious - This will remove all joints already implemented.
  59369. */
  59370. PhysicsImpostor.prototype.forceUpdate = function () {
  59371. this._init();
  59372. if (this.parent) {
  59373. this.parent.forceUpdate();
  59374. }
  59375. };
  59376. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  59377. /*public get mesh(): AbstractMesh {
  59378. return this._mesh;
  59379. }*/
  59380. /**
  59381. * Gets the body that holds this impostor. Either its own, or its parent.
  59382. */
  59383. get: function () {
  59384. return this._parent ? this._parent.physicsBody : this._physicsBody;
  59385. },
  59386. /**
  59387. * Set the physics body. Used mainly by the physics engine/plugin
  59388. */
  59389. set: function (physicsBody) {
  59390. if (this._physicsBody) {
  59391. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  59392. }
  59393. this._physicsBody = physicsBody;
  59394. this.resetUpdateFlags();
  59395. },
  59396. enumerable: true,
  59397. configurable: true
  59398. });
  59399. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  59400. get: function () {
  59401. return this._parent;
  59402. },
  59403. set: function (value) {
  59404. this._parent = value;
  59405. },
  59406. enumerable: true,
  59407. configurable: true
  59408. });
  59409. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  59410. this._bodyUpdateRequired = false;
  59411. };
  59412. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  59413. if (this.object.getBoundingInfo) {
  59414. var q = this.object.rotationQuaternion;
  59415. //reset rotation
  59416. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  59417. //calculate the world matrix with no rotation
  59418. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  59419. var size = this.object.getBoundingInfo().boundingBox.extendSizeWorld.scale(2);
  59420. //bring back the rotation
  59421. this.object.rotationQuaternion = q;
  59422. //calculate the world matrix with the new rotation
  59423. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  59424. return size;
  59425. }
  59426. else {
  59427. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  59428. }
  59429. };
  59430. PhysicsImpostor.prototype.getObjectCenter = function () {
  59431. if (this.object.getBoundingInfo) {
  59432. return this.object.getBoundingInfo().boundingBox.centerWorld;
  59433. }
  59434. else {
  59435. return this.object.position;
  59436. }
  59437. };
  59438. /**
  59439. * Get a specific parametes from the options parameter.
  59440. */
  59441. PhysicsImpostor.prototype.getParam = function (paramName) {
  59442. return this._options[paramName];
  59443. };
  59444. /**
  59445. * Sets a specific parameter in the options given to the physics plugin
  59446. */
  59447. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  59448. this._options[paramName] = value;
  59449. this._bodyUpdateRequired = true;
  59450. };
  59451. /**
  59452. * Specifically change the body's mass option. Won't recreate the physics body object
  59453. */
  59454. PhysicsImpostor.prototype.setMass = function (mass) {
  59455. if (this.getParam("mass") !== mass) {
  59456. this.setParam("mass", mass);
  59457. }
  59458. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  59459. };
  59460. PhysicsImpostor.prototype.getLinearVelocity = function () {
  59461. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  59462. };
  59463. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  59464. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  59465. };
  59466. PhysicsImpostor.prototype.getAngularVelocity = function () {
  59467. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  59468. };
  59469. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  59470. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  59471. };
  59472. /**
  59473. * Execute a function with the physics plugin native code.
  59474. * Provide a function the will have two variables - the world object and the physics body object.
  59475. */
  59476. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  59477. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  59478. };
  59479. /**
  59480. * Register a function that will be executed before the physics world is stepping forward.
  59481. */
  59482. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  59483. this._onBeforePhysicsStepCallbacks.push(func);
  59484. };
  59485. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  59486. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  59487. if (index > -1) {
  59488. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  59489. }
  59490. else {
  59491. BABYLON.Tools.Warn("Function to remove was not found");
  59492. }
  59493. };
  59494. /**
  59495. * Register a function that will be executed after the physics step
  59496. */
  59497. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  59498. this._onAfterPhysicsStepCallbacks.push(func);
  59499. };
  59500. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  59501. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  59502. if (index > -1) {
  59503. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  59504. }
  59505. else {
  59506. BABYLON.Tools.Warn("Function to remove was not found");
  59507. }
  59508. };
  59509. /**
  59510. * register a function that will be executed when this impostor collides against a different body.
  59511. */
  59512. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  59513. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  59514. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  59515. };
  59516. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  59517. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  59518. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  59519. if (index > -1) {
  59520. this._onPhysicsCollideCallbacks.splice(index, 1);
  59521. }
  59522. else {
  59523. BABYLON.Tools.Warn("Function to remove was not found");
  59524. }
  59525. };
  59526. /**
  59527. * Apply a force
  59528. */
  59529. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  59530. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  59531. };
  59532. /**
  59533. * Apply an impulse
  59534. */
  59535. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  59536. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  59537. };
  59538. /**
  59539. * A help function to create a joint.
  59540. */
  59541. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  59542. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  59543. this.addJoint(otherImpostor, joint);
  59544. };
  59545. /**
  59546. * Add a joint to this impostor with a different impostor.
  59547. */
  59548. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  59549. this._joints.push({
  59550. otherImpostor: otherImpostor,
  59551. joint: joint
  59552. });
  59553. this._physicsEngine.addJoint(this, otherImpostor, joint);
  59554. };
  59555. /**
  59556. * Will keep this body still, in a sleep mode.
  59557. */
  59558. PhysicsImpostor.prototype.sleep = function () {
  59559. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  59560. };
  59561. /**
  59562. * Wake the body up.
  59563. */
  59564. PhysicsImpostor.prototype.wakeUp = function () {
  59565. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  59566. };
  59567. PhysicsImpostor.prototype.clone = function (newObject) {
  59568. if (!newObject)
  59569. return null;
  59570. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  59571. };
  59572. PhysicsImpostor.prototype.dispose = function () {
  59573. var _this = this;
  59574. //no dispose if no physics engine is available.
  59575. if (!this._physicsEngine) {
  59576. return;
  59577. }
  59578. this._joints.forEach(function (j) {
  59579. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  59580. });
  59581. //dispose the physics body
  59582. this._physicsEngine.removeImpostor(this);
  59583. if (this.parent) {
  59584. this.parent.forceUpdate();
  59585. }
  59586. else {
  59587. /*this._object.getChildMeshes().forEach(function(mesh) {
  59588. if (mesh.physicsImpostor) {
  59589. if (disposeChildren) {
  59590. mesh.physicsImpostor.dispose();
  59591. mesh.physicsImpostor = null;
  59592. }
  59593. }
  59594. })*/
  59595. }
  59596. this._isDisposed = true;
  59597. };
  59598. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  59599. this._deltaPosition.copyFrom(position);
  59600. };
  59601. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  59602. if (!this._deltaRotation) {
  59603. this._deltaRotation = new BABYLON.Quaternion();
  59604. }
  59605. this._deltaRotation.copyFrom(rotation);
  59606. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  59607. };
  59608. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  59609. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  59610. };
  59611. PhysicsImpostor.prototype.getRadius = function () {
  59612. return this._physicsEngine.getPhysicsPlugin().getRadius(this);
  59613. };
  59614. /**
  59615. * Sync a bone with this impostor
  59616. * @param bone The bone to sync to the impostor.
  59617. * @param boneMesh The mesh that the bone is influencing.
  59618. * @param jointPivot The pivot of the joint / bone in local space.
  59619. * @param distToJoint Optional distance from the impostor to the joint.
  59620. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  59621. */
  59622. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  59623. var tempVec = PhysicsImpostor._tmpVecs[0];
  59624. var mesh = this.object;
  59625. if (adjustRotation) {
  59626. var tempQuat = PhysicsImpostor._tmpQuat;
  59627. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  59628. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  59629. }
  59630. else {
  59631. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  59632. }
  59633. tempVec.x = 0;
  59634. tempVec.y = 0;
  59635. tempVec.z = 0;
  59636. if (jointPivot) {
  59637. tempVec.x = jointPivot.x;
  59638. tempVec.y = jointPivot.y;
  59639. tempVec.z = jointPivot.z;
  59640. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  59641. if (distToJoint === undefined || distToJoint === null) {
  59642. distToJoint = jointPivot.length();
  59643. }
  59644. tempVec.x *= distToJoint;
  59645. tempVec.y *= distToJoint;
  59646. tempVec.z *= distToJoint;
  59647. }
  59648. if (bone.getParent()) {
  59649. tempVec.addInPlace(mesh.getAbsolutePosition());
  59650. bone.setAbsolutePosition(tempVec, boneMesh);
  59651. }
  59652. else {
  59653. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  59654. boneMesh.position.x -= tempVec.x;
  59655. boneMesh.position.y -= tempVec.y;
  59656. boneMesh.position.z -= tempVec.z;
  59657. }
  59658. };
  59659. /**
  59660. * Sync impostor to a bone
  59661. * @param bone The bone that the impostor will be synced to.
  59662. * @param boneMesh The mesh that the bone is influencing.
  59663. * @param jointPivot The pivot of the joint / bone in local space.
  59664. * @param distToJoint Optional distance from the impostor to the joint.
  59665. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  59666. * @param boneAxis Optional vector3 axis the bone is aligned with
  59667. */
  59668. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  59669. var mesh = this.object;
  59670. if (adjustRotation) {
  59671. var tempQuat = PhysicsImpostor._tmpQuat;
  59672. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  59673. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  59674. }
  59675. else {
  59676. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  59677. }
  59678. var pos = PhysicsImpostor._tmpVecs[0];
  59679. var boneDir = PhysicsImpostor._tmpVecs[1];
  59680. if (!boneAxis) {
  59681. boneAxis = PhysicsImpostor._tmpVecs[2];
  59682. boneAxis.x = 0;
  59683. boneAxis.y = 1;
  59684. boneAxis.z = 0;
  59685. }
  59686. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  59687. bone.getAbsolutePositionToRef(boneMesh, pos);
  59688. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  59689. distToJoint = jointPivot.length();
  59690. }
  59691. if (distToJoint !== undefined && distToJoint !== null) {
  59692. pos.x += boneDir.x * distToJoint;
  59693. pos.y += boneDir.y * distToJoint;
  59694. pos.z += boneDir.z * distToJoint;
  59695. }
  59696. mesh.setAbsolutePosition(pos);
  59697. };
  59698. return PhysicsImpostor;
  59699. }());
  59700. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  59701. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  59702. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59703. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  59704. //Impostor types
  59705. PhysicsImpostor.NoImpostor = 0;
  59706. PhysicsImpostor.SphereImpostor = 1;
  59707. PhysicsImpostor.BoxImpostor = 2;
  59708. PhysicsImpostor.PlaneImpostor = 3;
  59709. PhysicsImpostor.MeshImpostor = 4;
  59710. PhysicsImpostor.CylinderImpostor = 7;
  59711. PhysicsImpostor.ParticleImpostor = 8;
  59712. PhysicsImpostor.HeightmapImpostor = 9;
  59713. BABYLON.PhysicsImpostor = PhysicsImpostor;
  59714. })(BABYLON || (BABYLON = {}));
  59715. //# sourceMappingURL=babylon.physicsImpostor.js.map
  59716. var BABYLON;
  59717. (function (BABYLON) {
  59718. var PhysicsEngine = (function () {
  59719. function PhysicsEngine(gravity, _physicsPlugin) {
  59720. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  59721. this._physicsPlugin = _physicsPlugin;
  59722. //new methods and parameters
  59723. this._impostors = [];
  59724. this._joints = [];
  59725. if (!this._physicsPlugin.isSupported()) {
  59726. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  59727. + "Please make sure it is included.");
  59728. }
  59729. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  59730. this.setGravity(gravity);
  59731. this.setTimeStep();
  59732. }
  59733. PhysicsEngine.prototype.setGravity = function (gravity) {
  59734. this.gravity = gravity;
  59735. this._physicsPlugin.setGravity(this.gravity);
  59736. };
  59737. /**
  59738. * Set the time step of the physics engine.
  59739. * default is 1/60.
  59740. * To slow it down, enter 1/600 for example.
  59741. * To speed it up, 1/30
  59742. * @param {number} newTimeStep the new timestep to apply to this world.
  59743. */
  59744. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  59745. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  59746. this._physicsPlugin.setTimeStep(newTimeStep);
  59747. };
  59748. /**
  59749. * Get the time step of the physics engine.
  59750. */
  59751. PhysicsEngine.prototype.getTimeStep = function () {
  59752. return this._physicsPlugin.getTimeStep();
  59753. };
  59754. PhysicsEngine.prototype.dispose = function () {
  59755. this._impostors.forEach(function (impostor) {
  59756. impostor.dispose();
  59757. });
  59758. this._physicsPlugin.dispose();
  59759. };
  59760. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  59761. return this._physicsPlugin.name;
  59762. };
  59763. /**
  59764. * Adding a new impostor for the impostor tracking.
  59765. * This will be done by the impostor itself.
  59766. * @param {PhysicsImpostor} impostor the impostor to add
  59767. */
  59768. PhysicsEngine.prototype.addImpostor = function (impostor) {
  59769. impostor.uniqueId = this._impostors.push(impostor);
  59770. //if no parent, generate the body
  59771. if (!impostor.parent) {
  59772. this._physicsPlugin.generatePhysicsBody(impostor);
  59773. }
  59774. };
  59775. /**
  59776. * Remove an impostor from the engine.
  59777. * This impostor and its mesh will not longer be updated by the physics engine.
  59778. * @param {PhysicsImpostor} impostor the impostor to remove
  59779. */
  59780. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  59781. var index = this._impostors.indexOf(impostor);
  59782. if (index > -1) {
  59783. var removed = this._impostors.splice(index, 1);
  59784. //Is it needed?
  59785. if (removed.length) {
  59786. //this will also remove it from the world.
  59787. removed[0].physicsBody = null;
  59788. }
  59789. }
  59790. };
  59791. /**
  59792. * Add a joint to the physics engine
  59793. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  59794. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  59795. * @param {PhysicsJoint} the joint that will connect both impostors.
  59796. */
  59797. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  59798. var impostorJoint = {
  59799. mainImpostor: mainImpostor,
  59800. connectedImpostor: connectedImpostor,
  59801. joint: joint
  59802. };
  59803. joint.physicsPlugin = this._physicsPlugin;
  59804. this._joints.push(impostorJoint);
  59805. this._physicsPlugin.generateJoint(impostorJoint);
  59806. };
  59807. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  59808. var matchingJoints = this._joints.filter(function (impostorJoint) {
  59809. return (impostorJoint.connectedImpostor === connectedImpostor
  59810. && impostorJoint.joint === joint
  59811. && impostorJoint.mainImpostor === mainImpostor);
  59812. });
  59813. if (matchingJoints.length) {
  59814. this._physicsPlugin.removeJoint(matchingJoints[0]);
  59815. //TODO remove it from the list as well
  59816. }
  59817. };
  59818. /**
  59819. * Called by the scene. no need to call it.
  59820. */
  59821. PhysicsEngine.prototype._step = function (delta) {
  59822. var _this = this;
  59823. //check if any mesh has no body / requires an update
  59824. this._impostors.forEach(function (impostor) {
  59825. if (impostor.isBodyInitRequired()) {
  59826. _this._physicsPlugin.generatePhysicsBody(impostor);
  59827. }
  59828. });
  59829. if (delta > 0.1) {
  59830. delta = 0.1;
  59831. }
  59832. else if (delta <= 0) {
  59833. delta = 1.0 / 60.0;
  59834. }
  59835. this._physicsPlugin.executeStep(delta, this._impostors);
  59836. };
  59837. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  59838. return this._physicsPlugin;
  59839. };
  59840. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  59841. for (var i = 0; i < this._impostors.length; ++i) {
  59842. if (this._impostors[i].object === object) {
  59843. return this._impostors[i];
  59844. }
  59845. }
  59846. };
  59847. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  59848. for (var i = 0; i < this._impostors.length; ++i) {
  59849. if (this._impostors[i].physicsBody === body) {
  59850. return this._impostors[i];
  59851. }
  59852. }
  59853. };
  59854. return PhysicsEngine;
  59855. }());
  59856. // Statics
  59857. PhysicsEngine.Epsilon = 0.001;
  59858. BABYLON.PhysicsEngine = PhysicsEngine;
  59859. })(BABYLON || (BABYLON = {}));
  59860. //# sourceMappingURL=babylon.physicsEngine.js.map
  59861. var BABYLON;
  59862. (function (BABYLON) {
  59863. var CannonJSPlugin = (function () {
  59864. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  59865. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  59866. if (iterations === void 0) { iterations = 10; }
  59867. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  59868. this.name = "CannonJSPlugin";
  59869. this._physicsMaterials = [];
  59870. this._fixedTimeStep = 1 / 60;
  59871. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  59872. this._currentCollisionGroup = 2;
  59873. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  59874. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  59875. this._tmpPosition = BABYLON.Vector3.Zero();
  59876. this._tmpQuaternion = new BABYLON.Quaternion();
  59877. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  59878. this._tmpDeltaRotation = new BABYLON.Quaternion();
  59879. this._tmpUnityRotation = new BABYLON.Quaternion();
  59880. if (!this.isSupported()) {
  59881. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  59882. return;
  59883. }
  59884. this.world = new CANNON.World();
  59885. this.world.broadphase = new CANNON.NaiveBroadphase();
  59886. this.world.solver.iterations = iterations;
  59887. }
  59888. CannonJSPlugin.prototype.setGravity = function (gravity) {
  59889. this.world.gravity.copy(gravity);
  59890. };
  59891. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  59892. this._fixedTimeStep = timeStep;
  59893. };
  59894. CannonJSPlugin.prototype.getTimeStep = function () {
  59895. return this._fixedTimeStep;
  59896. };
  59897. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  59898. // Delta is in seconds, should be provided in milliseconds
  59899. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  59900. };
  59901. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  59902. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  59903. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  59904. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  59905. };
  59906. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  59907. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  59908. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  59909. impostor.physicsBody.applyForce(impulse, worldPoint);
  59910. };
  59911. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  59912. //parent-child relationship. Does this impostor has a parent impostor?
  59913. if (impostor.parent) {
  59914. if (impostor.physicsBody) {
  59915. this.removePhysicsBody(impostor);
  59916. //TODO is that needed?
  59917. impostor.forceUpdate();
  59918. }
  59919. return;
  59920. }
  59921. //should a new body be created for this impostor?
  59922. if (impostor.isBodyInitRequired()) {
  59923. var shape = this._createShape(impostor);
  59924. //unregister events, if body is being changed
  59925. var oldBody = impostor.physicsBody;
  59926. if (oldBody) {
  59927. this.removePhysicsBody(impostor);
  59928. }
  59929. //create the body and material
  59930. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  59931. var bodyCreationObject = {
  59932. mass: impostor.getParam("mass"),
  59933. material: material
  59934. };
  59935. // A simple extend, in case native options were used.
  59936. var nativeOptions = impostor.getParam("nativeOptions");
  59937. for (var key in nativeOptions) {
  59938. if (nativeOptions.hasOwnProperty(key)) {
  59939. bodyCreationObject[key] = nativeOptions[key];
  59940. }
  59941. }
  59942. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  59943. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  59944. this.world.addEventListener("preStep", impostor.beforeStep);
  59945. this.world.addEventListener("postStep", impostor.afterStep);
  59946. impostor.physicsBody.addShape(shape);
  59947. this.world.add(impostor.physicsBody);
  59948. //try to keep the body moving in the right direction by taking old properties.
  59949. //Should be tested!
  59950. if (oldBody) {
  59951. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  59952. impostor.physicsBody[param].copy(oldBody[param]);
  59953. });
  59954. }
  59955. this._processChildMeshes(impostor);
  59956. }
  59957. //now update the body's transformation
  59958. this._updatePhysicsBodyTransformation(impostor);
  59959. };
  59960. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  59961. var _this = this;
  59962. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  59963. if (meshChildren.length) {
  59964. var processMesh = function (localPosition, mesh) {
  59965. var childImpostor = mesh.getPhysicsImpostor();
  59966. if (childImpostor) {
  59967. var parent = childImpostor.parent;
  59968. if (parent !== mainImpostor) {
  59969. var localPosition = mesh.position;
  59970. if (childImpostor.physicsBody) {
  59971. _this.removePhysicsBody(childImpostor);
  59972. childImpostor.physicsBody = null;
  59973. }
  59974. childImpostor.parent = mainImpostor;
  59975. childImpostor.resetUpdateFlags();
  59976. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  59977. //Add the mass of the children.
  59978. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  59979. }
  59980. }
  59981. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  59982. };
  59983. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  59984. }
  59985. };
  59986. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  59987. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  59988. this.world.removeEventListener("preStep", impostor.beforeStep);
  59989. this.world.removeEventListener("postStep", impostor.afterStep);
  59990. this.world.remove(impostor.physicsBody);
  59991. };
  59992. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  59993. var mainBody = impostorJoint.mainImpostor.physicsBody;
  59994. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  59995. if (!mainBody || !connectedBody) {
  59996. return;
  59997. }
  59998. var constraint;
  59999. var jointData = impostorJoint.joint.jointData;
  60000. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  60001. var constraintData = {
  60002. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  60003. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  60004. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  60005. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  60006. maxForce: jointData.nativeParams.maxForce,
  60007. collideConnected: !!jointData.collision
  60008. };
  60009. switch (impostorJoint.joint.type) {
  60010. case BABYLON.PhysicsJoint.HingeJoint:
  60011. case BABYLON.PhysicsJoint.Hinge2Joint:
  60012. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  60013. break;
  60014. case BABYLON.PhysicsJoint.DistanceJoint:
  60015. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  60016. break;
  60017. case BABYLON.PhysicsJoint.SpringJoint:
  60018. var springData = jointData;
  60019. constraint = new CANNON.Spring(mainBody, connectedBody, {
  60020. restLength: springData.length,
  60021. stiffness: springData.stiffness,
  60022. damping: springData.damping,
  60023. localAnchorA: constraintData.pivotA,
  60024. localAnchorB: constraintData.pivotB
  60025. });
  60026. break;
  60027. case BABYLON.PhysicsJoint.LockJoint:
  60028. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  60029. break;
  60030. case BABYLON.PhysicsJoint.PointToPointJoint:
  60031. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  60032. default:
  60033. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  60034. break;
  60035. }
  60036. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  60037. constraint.collideConnected = !!jointData.collision;
  60038. impostorJoint.joint.physicsJoint = constraint;
  60039. //don't add spring as constraint, as it is not one.
  60040. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  60041. this.world.addConstraint(constraint);
  60042. }
  60043. else {
  60044. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  60045. constraint.applyForce();
  60046. });
  60047. }
  60048. };
  60049. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  60050. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  60051. };
  60052. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  60053. var index;
  60054. var mat;
  60055. for (index = 0; index < this._physicsMaterials.length; index++) {
  60056. mat = this._physicsMaterials[index];
  60057. if (mat.friction === friction && mat.restitution === restitution) {
  60058. return mat;
  60059. }
  60060. }
  60061. var currentMat = new CANNON.Material(name);
  60062. currentMat.friction = friction;
  60063. currentMat.restitution = restitution;
  60064. this._physicsMaterials.push(currentMat);
  60065. return currentMat;
  60066. };
  60067. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  60068. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  60069. };
  60070. CannonJSPlugin.prototype._createShape = function (impostor) {
  60071. var object = impostor.object;
  60072. var returnValue;
  60073. var extendSize = impostor.getObjectExtendSize();
  60074. switch (impostor.type) {
  60075. case BABYLON.PhysicsImpostor.SphereImpostor:
  60076. var radiusX = extendSize.x;
  60077. var radiusY = extendSize.y;
  60078. var radiusZ = extendSize.z;
  60079. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  60080. break;
  60081. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  60082. case BABYLON.PhysicsImpostor.CylinderImpostor:
  60083. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  60084. break;
  60085. case BABYLON.PhysicsImpostor.BoxImpostor:
  60086. var box = extendSize.scale(0.5);
  60087. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  60088. break;
  60089. case BABYLON.PhysicsImpostor.PlaneImpostor:
  60090. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  60091. returnValue = new CANNON.Plane();
  60092. break;
  60093. case BABYLON.PhysicsImpostor.MeshImpostor:
  60094. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  60095. var rawFaces = object.getIndices ? object.getIndices() : [];
  60096. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  60097. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  60098. break;
  60099. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  60100. returnValue = this._createHeightmap(object);
  60101. break;
  60102. case BABYLON.PhysicsImpostor.ParticleImpostor:
  60103. returnValue = new CANNON.Particle();
  60104. break;
  60105. }
  60106. return returnValue;
  60107. };
  60108. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  60109. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60110. var matrix = [];
  60111. //For now pointDepth will not be used and will be automatically calculated.
  60112. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  60113. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  60114. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSizeWorld.x, object.getBoundingInfo().boundingBox.extendSizeWorld.z);
  60115. var elementSize = dim * 2 / arraySize;
  60116. var minY = object.getBoundingInfo().boundingBox.extendSizeWorld.y;
  60117. for (var i = 0; i < pos.length; i = i + 3) {
  60118. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  60119. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  60120. var y = pos[i + 1] + minY;
  60121. if (!matrix[x]) {
  60122. matrix[x] = [];
  60123. }
  60124. if (!matrix[x][z]) {
  60125. matrix[x][z] = y;
  60126. }
  60127. matrix[x][z] = Math.max(y, matrix[x][z]);
  60128. }
  60129. for (var x = 0; x <= arraySize; ++x) {
  60130. if (!matrix[x]) {
  60131. var loc = 1;
  60132. while (!matrix[(x + loc) % arraySize]) {
  60133. loc++;
  60134. }
  60135. matrix[x] = matrix[(x + loc) % arraySize].slice();
  60136. //console.log("missing x", x);
  60137. }
  60138. for (var z = 0; z <= arraySize; ++z) {
  60139. if (!matrix[x][z]) {
  60140. var loc = 1;
  60141. var newValue;
  60142. while (newValue === undefined) {
  60143. newValue = matrix[x][(z + loc++) % arraySize];
  60144. }
  60145. matrix[x][z] = newValue;
  60146. }
  60147. }
  60148. }
  60149. var shape = new CANNON.Heightfield(matrix, {
  60150. elementSize: elementSize
  60151. });
  60152. //For future reference, needed for body transformation
  60153. shape.minY = minY;
  60154. return shape;
  60155. };
  60156. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  60157. var object = impostor.object;
  60158. //make sure it is updated...
  60159. object.computeWorldMatrix && object.computeWorldMatrix(true);
  60160. // The delta between the mesh position and the mesh bounding box center
  60161. var center = impostor.getObjectCenter();
  60162. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  60163. this._tmpPosition.copyFrom(center);
  60164. var quaternion = object.rotationQuaternion;
  60165. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  60166. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  60167. //-90 DEG in X, precalculated
  60168. quaternion = quaternion.multiply(this._minus90X);
  60169. //Invert! (Precalculated, 90 deg in X)
  60170. //No need to clone. this will never change.
  60171. impostor.setDeltaRotation(this._plus90X);
  60172. }
  60173. //If it is a heightfield, if should be centered.
  60174. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  60175. var mesh = object;
  60176. //calculate the correct body position:
  60177. var rotationQuaternion = mesh.rotationQuaternion;
  60178. mesh.rotationQuaternion = this._tmpUnityRotation;
  60179. mesh.computeWorldMatrix(true);
  60180. //get original center with no rotation
  60181. var c = center.clone();
  60182. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  60183. //rotation is back
  60184. mesh.rotationQuaternion = rotationQuaternion;
  60185. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  60186. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSizeWorld.x, 0, -mesh.getBoundingInfo().boundingBox.extendSizeWorld.z);
  60187. mesh.setPivotMatrix(p);
  60188. mesh.computeWorldMatrix(true);
  60189. //calculate the translation
  60190. var translation = mesh.getBoundingInfo().boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  60191. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSizeWorld.y, translation.z);
  60192. //add it inverted to the delta
  60193. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.centerWorld.subtract(c));
  60194. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSizeWorld.y;
  60195. mesh.setPivotMatrix(oldPivot);
  60196. mesh.computeWorldMatrix(true);
  60197. }
  60198. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  60199. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  60200. this._tmpPosition.copyFrom(object.position);
  60201. }
  60202. impostor.setDeltaPosition(this._tmpDeltaPosition);
  60203. //Now update the impostor object
  60204. impostor.physicsBody.position.copy(this._tmpPosition);
  60205. impostor.physicsBody.quaternion.copy(quaternion);
  60206. };
  60207. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  60208. impostor.object.position.copyFrom(impostor.physicsBody.position);
  60209. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  60210. };
  60211. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  60212. impostor.physicsBody.position.copy(newPosition);
  60213. impostor.physicsBody.quaternion.copy(newRotation);
  60214. };
  60215. CannonJSPlugin.prototype.isSupported = function () {
  60216. return window.CANNON !== undefined;
  60217. };
  60218. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  60219. impostor.physicsBody.velocity.copy(velocity);
  60220. };
  60221. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  60222. impostor.physicsBody.angularVelocity.copy(velocity);
  60223. };
  60224. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  60225. var v = impostor.physicsBody.velocity;
  60226. if (!v)
  60227. return null;
  60228. return new BABYLON.Vector3(v.x, v.y, v.z);
  60229. };
  60230. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  60231. var v = impostor.physicsBody.angularVelocity;
  60232. if (!v)
  60233. return null;
  60234. return new BABYLON.Vector3(v.x, v.y, v.z);
  60235. };
  60236. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  60237. impostor.physicsBody.mass = mass;
  60238. impostor.physicsBody.updateMassProperties();
  60239. };
  60240. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  60241. return impostor.physicsBody.mass;
  60242. };
  60243. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  60244. return impostor.physicsBody.material.friction;
  60245. };
  60246. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  60247. impostor.physicsBody.material.friction = friction;
  60248. };
  60249. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  60250. return impostor.physicsBody.material.restitution;
  60251. };
  60252. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  60253. impostor.physicsBody.material.restitution = restitution;
  60254. };
  60255. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  60256. impostor.physicsBody.sleep();
  60257. };
  60258. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  60259. impostor.physicsBody.wakeUp();
  60260. };
  60261. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  60262. joint.physicsJoint.distance = maxDistance;
  60263. };
  60264. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  60265. if (!motorIndex) {
  60266. joint.physicsJoint.enableMotor();
  60267. }
  60268. };
  60269. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  60270. if (!motorIndex) {
  60271. joint.physicsJoint.disableMotor();
  60272. }
  60273. };
  60274. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  60275. if (!motorIndex) {
  60276. joint.physicsJoint.enableMotor();
  60277. joint.physicsJoint.setMotorSpeed(speed);
  60278. if (maxForce) {
  60279. this.setLimit(joint, maxForce);
  60280. }
  60281. }
  60282. };
  60283. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  60284. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  60285. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  60286. };
  60287. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  60288. var body = impostor.physicsBody;
  60289. mesh.position.x = body.position.x;
  60290. mesh.position.y = body.position.y;
  60291. mesh.position.z = body.position.z;
  60292. mesh.rotationQuaternion.x = body.quaternion.x;
  60293. mesh.rotationQuaternion.y = body.quaternion.y;
  60294. mesh.rotationQuaternion.z = body.quaternion.z;
  60295. mesh.rotationQuaternion.w = body.quaternion.w;
  60296. };
  60297. CannonJSPlugin.prototype.getRadius = function (impostor) {
  60298. var shape = impostor.physicsBody.shapes[0];
  60299. return shape.boundingSphereRadius;
  60300. };
  60301. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  60302. var shape = impostor.physicsBody.shapes[0];
  60303. result.x = shape.halfExtents.x * 2;
  60304. result.y = shape.halfExtents.y * 2;
  60305. result.z = shape.halfExtents.z * 2;
  60306. };
  60307. CannonJSPlugin.prototype.dispose = function () {
  60308. };
  60309. return CannonJSPlugin;
  60310. }());
  60311. BABYLON.CannonJSPlugin = CannonJSPlugin;
  60312. })(BABYLON || (BABYLON = {}));
  60313. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  60314. var BABYLON;
  60315. (function (BABYLON) {
  60316. var OimoJSPlugin = (function () {
  60317. function OimoJSPlugin(iterations) {
  60318. this.name = "OimoJSPlugin";
  60319. this._tmpImpostorsArray = [];
  60320. this._tmpPositionVector = BABYLON.Vector3.Zero();
  60321. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  60322. this.world.worldscale(1);
  60323. this.world.clear();
  60324. //making sure no stats are calculated
  60325. this.world.isNoStat = true;
  60326. }
  60327. OimoJSPlugin.prototype.setGravity = function (gravity) {
  60328. this.world.gravity.copy(gravity);
  60329. };
  60330. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  60331. this.world.timeStep = timeStep;
  60332. };
  60333. OimoJSPlugin.prototype.getTimeStep = function () {
  60334. return this.world.timeStep;
  60335. };
  60336. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  60337. var _this = this;
  60338. impostors.forEach(function (impostor) {
  60339. impostor.beforeStep();
  60340. });
  60341. this.world.step();
  60342. impostors.forEach(function (impostor) {
  60343. impostor.afterStep();
  60344. //update the ordered impostors array
  60345. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  60346. });
  60347. //check for collisions
  60348. var contact = this.world.contacts;
  60349. while (contact !== null) {
  60350. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  60351. contact = contact.next;
  60352. continue;
  60353. }
  60354. //is this body colliding with any other? get the impostor
  60355. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  60356. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  60357. if (!mainImpostor || !collidingImpostor) {
  60358. contact = contact.next;
  60359. continue;
  60360. }
  60361. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  60362. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  60363. contact = contact.next;
  60364. }
  60365. };
  60366. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  60367. var mass = impostor.physicsBody.massInfo.mass;
  60368. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  60369. };
  60370. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  60371. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  60372. this.applyImpulse(impostor, force, contactPoint);
  60373. };
  60374. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  60375. var _this = this;
  60376. //parent-child relationship. Does this impostor has a parent impostor?
  60377. if (impostor.parent) {
  60378. if (impostor.physicsBody) {
  60379. this.removePhysicsBody(impostor);
  60380. //TODO is that needed?
  60381. impostor.forceUpdate();
  60382. }
  60383. return;
  60384. }
  60385. if (impostor.isBodyInitRequired()) {
  60386. var bodyConfig = {
  60387. name: impostor.uniqueId,
  60388. //Oimo must have mass, also for static objects.
  60389. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  60390. size: [],
  60391. type: [],
  60392. pos: [],
  60393. rot: [],
  60394. move: impostor.getParam("mass") !== 0,
  60395. //Supporting older versions of Oimo
  60396. world: this.world
  60397. };
  60398. var impostors = [impostor];
  60399. var addToArray = function (parent) {
  60400. if (!parent.getChildMeshes)
  60401. return;
  60402. parent.getChildMeshes().forEach(function (m) {
  60403. if (m.physicsImpostor) {
  60404. impostors.push(m.physicsImpostor);
  60405. m.physicsImpostor._init();
  60406. }
  60407. });
  60408. };
  60409. addToArray(impostor.object);
  60410. var checkWithEpsilon_1 = function (value) {
  60411. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  60412. };
  60413. impostors.forEach(function (i) {
  60414. //get the correct bounding box
  60415. var oldQuaternion = i.object.rotationQuaternion;
  60416. var rot = new OIMO.Euler().setFromQuaternion({
  60417. x: impostor.object.rotationQuaternion.x,
  60418. y: impostor.object.rotationQuaternion.y,
  60419. z: impostor.object.rotationQuaternion.z,
  60420. s: impostor.object.rotationQuaternion.w
  60421. });
  60422. var extendSize = i.getObjectExtendSize();
  60423. if (i === impostor) {
  60424. var center = impostor.getObjectCenter();
  60425. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  60426. //Can also use Array.prototype.push.apply
  60427. bodyConfig.pos.push(center.x);
  60428. bodyConfig.pos.push(center.y);
  60429. bodyConfig.pos.push(center.z);
  60430. //tmp solution
  60431. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  60432. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  60433. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  60434. }
  60435. else {
  60436. bodyConfig.pos.push(i.object.position.x);
  60437. bodyConfig.pos.push(i.object.position.y);
  60438. bodyConfig.pos.push(i.object.position.z);
  60439. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  60440. bodyConfig.rot.push(0);
  60441. bodyConfig.rot.push(0);
  60442. bodyConfig.rot.push(0);
  60443. }
  60444. // register mesh
  60445. switch (i.type) {
  60446. case BABYLON.PhysicsImpostor.ParticleImpostor:
  60447. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  60448. case BABYLON.PhysicsImpostor.SphereImpostor:
  60449. var radiusX = extendSize.x;
  60450. var radiusY = extendSize.y;
  60451. var radiusZ = extendSize.z;
  60452. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  60453. bodyConfig.type.push('sphere');
  60454. //due to the way oimo works with compounds, add 3 times
  60455. bodyConfig.size.push(size);
  60456. bodyConfig.size.push(size);
  60457. bodyConfig.size.push(size);
  60458. break;
  60459. case BABYLON.PhysicsImpostor.CylinderImpostor:
  60460. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  60461. var sizeY = checkWithEpsilon_1(extendSize.y);
  60462. bodyConfig.type.push('cylinder');
  60463. bodyConfig.size.push(sizeX);
  60464. bodyConfig.size.push(sizeY);
  60465. //due to the way oimo works with compounds, add one more value.
  60466. bodyConfig.size.push(sizeY);
  60467. break;
  60468. case BABYLON.PhysicsImpostor.PlaneImpostor:
  60469. case BABYLON.PhysicsImpostor.BoxImpostor:
  60470. default:
  60471. var sizeX = checkWithEpsilon_1(extendSize.x);
  60472. var sizeY = checkWithEpsilon_1(extendSize.y);
  60473. var sizeZ = checkWithEpsilon_1(extendSize.z);
  60474. bodyConfig.type.push('box');
  60475. bodyConfig.size.push(sizeX);
  60476. bodyConfig.size.push(sizeY);
  60477. bodyConfig.size.push(sizeZ);
  60478. break;
  60479. }
  60480. //actually not needed, but hey...
  60481. i.object.rotationQuaternion = oldQuaternion;
  60482. });
  60483. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  60484. }
  60485. else {
  60486. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  60487. }
  60488. impostor.setDeltaPosition(this._tmpPositionVector);
  60489. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  60490. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  60491. };
  60492. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  60493. //impostor.physicsBody.dispose();
  60494. //Same as : (older oimo versions)
  60495. this.world.removeRigidBody(impostor.physicsBody);
  60496. };
  60497. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  60498. var mainBody = impostorJoint.mainImpostor.physicsBody;
  60499. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  60500. if (!mainBody || !connectedBody) {
  60501. return;
  60502. }
  60503. var jointData = impostorJoint.joint.jointData;
  60504. var options = jointData.nativeParams || {};
  60505. var type;
  60506. var nativeJointData = {
  60507. body1: mainBody,
  60508. body2: connectedBody,
  60509. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  60510. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  60511. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  60512. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  60513. min: options.min,
  60514. max: options.max,
  60515. collision: options.collision || jointData.collision,
  60516. spring: options.spring,
  60517. //supporting older version of Oimo
  60518. world: this.world
  60519. };
  60520. switch (impostorJoint.joint.type) {
  60521. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  60522. type = "jointBall";
  60523. break;
  60524. case BABYLON.PhysicsJoint.SpringJoint:
  60525. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  60526. var springData = jointData;
  60527. nativeJointData.min = springData.length || nativeJointData.min;
  60528. //Max should also be set, just make sure it is at least min
  60529. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  60530. case BABYLON.PhysicsJoint.DistanceJoint:
  60531. type = "jointDistance";
  60532. nativeJointData.max = jointData.maxDistance;
  60533. break;
  60534. case BABYLON.PhysicsJoint.PrismaticJoint:
  60535. type = "jointPrisme";
  60536. break;
  60537. case BABYLON.PhysicsJoint.SliderJoint:
  60538. type = "jointSlide";
  60539. break;
  60540. case BABYLON.PhysicsJoint.WheelJoint:
  60541. type = "jointWheel";
  60542. break;
  60543. case BABYLON.PhysicsJoint.HingeJoint:
  60544. default:
  60545. type = "jointHinge";
  60546. break;
  60547. }
  60548. nativeJointData.type = type;
  60549. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  60550. };
  60551. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  60552. //Bug in Oimo prevents us from disposing a joint in the playground
  60553. //joint.joint.physicsJoint.dispose();
  60554. //So we will bruteforce it!
  60555. try {
  60556. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  60557. }
  60558. catch (e) {
  60559. BABYLON.Tools.Warn(e);
  60560. }
  60561. };
  60562. OimoJSPlugin.prototype.isSupported = function () {
  60563. return OIMO !== undefined;
  60564. };
  60565. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  60566. if (!impostor.physicsBody.sleeping) {
  60567. //TODO check that
  60568. if (impostor.physicsBody.shapes.next) {
  60569. var parentShape = this._getLastShape(impostor.physicsBody);
  60570. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  60571. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  60572. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  60573. }
  60574. else {
  60575. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  60576. }
  60577. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  60578. impostor.object.rotationQuaternion.normalize();
  60579. }
  60580. };
  60581. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  60582. var body = impostor.physicsBody;
  60583. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  60584. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  60585. body.syncShapes();
  60586. body.awake();
  60587. };
  60588. OimoJSPlugin.prototype._getLastShape = function (body) {
  60589. var lastShape = body.shapes;
  60590. while (lastShape.next) {
  60591. lastShape = lastShape.next;
  60592. }
  60593. return lastShape;
  60594. };
  60595. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  60596. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  60597. };
  60598. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  60599. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  60600. };
  60601. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  60602. var v = impostor.physicsBody.linearVelocity;
  60603. if (!v)
  60604. return null;
  60605. return new BABYLON.Vector3(v.x, v.y, v.z);
  60606. };
  60607. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  60608. var v = impostor.physicsBody.angularVelocity;
  60609. if (!v)
  60610. return null;
  60611. return new BABYLON.Vector3(v.x, v.y, v.z);
  60612. };
  60613. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  60614. var staticBody = mass === 0;
  60615. //this will actually set the body's density and not its mass.
  60616. //But this is how oimo treats the mass variable.
  60617. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  60618. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  60619. };
  60620. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  60621. return impostor.physicsBody.shapes.density;
  60622. };
  60623. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  60624. return impostor.physicsBody.shapes.friction;
  60625. };
  60626. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  60627. impostor.physicsBody.shapes.friction = friction;
  60628. };
  60629. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  60630. return impostor.physicsBody.shapes.restitution;
  60631. };
  60632. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  60633. impostor.physicsBody.shapes.restitution = restitution;
  60634. };
  60635. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  60636. impostor.physicsBody.sleep();
  60637. };
  60638. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  60639. impostor.physicsBody.awake();
  60640. };
  60641. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  60642. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  60643. if (minDistance !== void 0) {
  60644. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  60645. }
  60646. };
  60647. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  60648. //TODO separate rotational and transational motors.
  60649. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  60650. if (motor) {
  60651. motor.setMotor(speed, maxForce);
  60652. }
  60653. };
  60654. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  60655. //TODO separate rotational and transational motors.
  60656. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  60657. if (motor) {
  60658. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  60659. }
  60660. };
  60661. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  60662. var body = impostor.physicsBody;
  60663. mesh.position.x = body.position.x;
  60664. mesh.position.y = body.position.y;
  60665. mesh.position.z = body.position.z;
  60666. mesh.rotationQuaternion.x = body.orientation.x;
  60667. mesh.rotationQuaternion.y = body.orientation.y;
  60668. mesh.rotationQuaternion.z = body.orientation.z;
  60669. mesh.rotationQuaternion.w = body.orientation.s;
  60670. };
  60671. OimoJSPlugin.prototype.getRadius = function (impostor) {
  60672. return impostor.physicsBody.shapes.radius;
  60673. };
  60674. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  60675. var shape = impostor.physicsBody.shapes;
  60676. result.x = shape.halfWidth * 2;
  60677. result.y = shape.halfHeight * 2;
  60678. result.z = shape.halfDepth * 2;
  60679. };
  60680. OimoJSPlugin.prototype.dispose = function () {
  60681. this.world.clear();
  60682. };
  60683. return OimoJSPlugin;
  60684. }());
  60685. BABYLON.OimoJSPlugin = OimoJSPlugin;
  60686. })(BABYLON || (BABYLON = {}));
  60687. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  60688. var BABYLON;
  60689. (function (BABYLON) {
  60690. var Internals;
  60691. (function (Internals) {
  60692. /*
  60693. * Based on jsTGALoader - Javascript loader for TGA file
  60694. * By Vincent Thibault
  60695. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  60696. */
  60697. var TGATools = (function () {
  60698. function TGATools() {
  60699. }
  60700. TGATools.GetTGAHeader = function (data) {
  60701. var offset = 0;
  60702. var header = {
  60703. id_length: data[offset++],
  60704. colormap_type: data[offset++],
  60705. image_type: data[offset++],
  60706. colormap_index: data[offset++] | data[offset++] << 8,
  60707. colormap_length: data[offset++] | data[offset++] << 8,
  60708. colormap_size: data[offset++],
  60709. origin: [
  60710. data[offset++] | data[offset++] << 8,
  60711. data[offset++] | data[offset++] << 8
  60712. ],
  60713. width: data[offset++] | data[offset++] << 8,
  60714. height: data[offset++] | data[offset++] << 8,
  60715. pixel_size: data[offset++],
  60716. flags: data[offset++]
  60717. };
  60718. return header;
  60719. };
  60720. TGATools.UploadContent = function (gl, data) {
  60721. // Not enough data to contain header ?
  60722. if (data.length < 19) {
  60723. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  60724. return;
  60725. }
  60726. // Read Header
  60727. var offset = 18;
  60728. var header = TGATools.GetTGAHeader(data);
  60729. // Assume it's a valid Targa file.
  60730. if (header.id_length + offset > data.length) {
  60731. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  60732. return;
  60733. }
  60734. // Skip not needed data
  60735. offset += header.id_length;
  60736. var use_rle = false;
  60737. var use_pal = false;
  60738. var use_rgb = false;
  60739. var use_grey = false;
  60740. // Get some informations.
  60741. switch (header.image_type) {
  60742. case TGATools._TYPE_RLE_INDEXED:
  60743. use_rle = true;
  60744. case TGATools._TYPE_INDEXED:
  60745. use_pal = true;
  60746. break;
  60747. case TGATools._TYPE_RLE_RGB:
  60748. use_rle = true;
  60749. case TGATools._TYPE_RGB:
  60750. use_rgb = true;
  60751. break;
  60752. case TGATools._TYPE_RLE_GREY:
  60753. use_rle = true;
  60754. case TGATools._TYPE_GREY:
  60755. use_grey = true;
  60756. break;
  60757. }
  60758. var pixel_data;
  60759. var numAlphaBits = header.flags & 0xf;
  60760. var pixel_size = header.pixel_size >> 3;
  60761. var pixel_total = header.width * header.height * pixel_size;
  60762. // Read palettes
  60763. var palettes;
  60764. if (use_pal) {
  60765. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  60766. }
  60767. // Read LRE
  60768. if (use_rle) {
  60769. pixel_data = new Uint8Array(pixel_total);
  60770. var c, count, i;
  60771. var localOffset = 0;
  60772. var pixels = new Uint8Array(pixel_size);
  60773. while (offset < pixel_total && localOffset < pixel_total) {
  60774. c = data[offset++];
  60775. count = (c & 0x7f) + 1;
  60776. // RLE pixels
  60777. if (c & 0x80) {
  60778. // Bind pixel tmp array
  60779. for (i = 0; i < pixel_size; ++i) {
  60780. pixels[i] = data[offset++];
  60781. }
  60782. // Copy pixel array
  60783. for (i = 0; i < count; ++i) {
  60784. pixel_data.set(pixels, localOffset + i * pixel_size);
  60785. }
  60786. localOffset += pixel_size * count;
  60787. }
  60788. else {
  60789. count *= pixel_size;
  60790. for (i = 0; i < count; ++i) {
  60791. pixel_data[localOffset + i] = data[offset++];
  60792. }
  60793. localOffset += count;
  60794. }
  60795. }
  60796. }
  60797. else {
  60798. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  60799. }
  60800. // Load to texture
  60801. var x_start, y_start, x_step, y_step, y_end, x_end;
  60802. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  60803. default:
  60804. case TGATools._ORIGIN_UL:
  60805. x_start = 0;
  60806. x_step = 1;
  60807. x_end = header.width;
  60808. y_start = 0;
  60809. y_step = 1;
  60810. y_end = header.height;
  60811. break;
  60812. case TGATools._ORIGIN_BL:
  60813. x_start = 0;
  60814. x_step = 1;
  60815. x_end = header.width;
  60816. y_start = header.height - 1;
  60817. y_step = -1;
  60818. y_end = -1;
  60819. break;
  60820. case TGATools._ORIGIN_UR:
  60821. x_start = header.width - 1;
  60822. x_step = -1;
  60823. x_end = -1;
  60824. y_start = 0;
  60825. y_step = 1;
  60826. y_end = header.height;
  60827. break;
  60828. case TGATools._ORIGIN_BR:
  60829. x_start = header.width - 1;
  60830. x_step = -1;
  60831. x_end = -1;
  60832. y_start = header.height - 1;
  60833. y_step = -1;
  60834. y_end = -1;
  60835. break;
  60836. }
  60837. // Load the specify method
  60838. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  60839. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  60840. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  60841. };
  60842. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  60843. var image = pixel_data, colormap = palettes;
  60844. var width = header.width, height = header.height;
  60845. var color, i = 0, x, y;
  60846. var imageData = new Uint8Array(width * height * 4);
  60847. for (y = y_start; y !== y_end; y += y_step) {
  60848. for (x = x_start; x !== x_end; x += x_step, i++) {
  60849. color = image[i];
  60850. imageData[(x + width * y) * 4 + 3] = 255;
  60851. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  60852. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  60853. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  60854. }
  60855. }
  60856. return imageData;
  60857. };
  60858. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  60859. var image = pixel_data;
  60860. var width = header.width, height = header.height;
  60861. var color, i = 0, x, y;
  60862. var imageData = new Uint8Array(width * height * 4);
  60863. for (y = y_start; y !== y_end; y += y_step) {
  60864. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  60865. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  60866. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  60867. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  60868. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  60869. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  60870. }
  60871. }
  60872. return imageData;
  60873. };
  60874. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  60875. var image = pixel_data;
  60876. var width = header.width, height = header.height;
  60877. var i = 0, x, y;
  60878. var imageData = new Uint8Array(width * height * 4);
  60879. for (y = y_start; y !== y_end; y += y_step) {
  60880. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  60881. imageData[(x + width * y) * 4 + 3] = 255;
  60882. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  60883. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  60884. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  60885. }
  60886. }
  60887. return imageData;
  60888. };
  60889. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  60890. var image = pixel_data;
  60891. var width = header.width, height = header.height;
  60892. var i = 0, x, y;
  60893. var imageData = new Uint8Array(width * height * 4);
  60894. for (y = y_start; y !== y_end; y += y_step) {
  60895. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  60896. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  60897. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  60898. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  60899. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  60900. }
  60901. }
  60902. return imageData;
  60903. };
  60904. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  60905. var image = pixel_data;
  60906. var width = header.width, height = header.height;
  60907. var color, i = 0, x, y;
  60908. var imageData = new Uint8Array(width * height * 4);
  60909. for (y = y_start; y !== y_end; y += y_step) {
  60910. for (x = x_start; x !== x_end; x += x_step, i++) {
  60911. color = image[i];
  60912. imageData[(x + width * y) * 4 + 0] = color;
  60913. imageData[(x + width * y) * 4 + 1] = color;
  60914. imageData[(x + width * y) * 4 + 2] = color;
  60915. imageData[(x + width * y) * 4 + 3] = 255;
  60916. }
  60917. }
  60918. return imageData;
  60919. };
  60920. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  60921. var image = pixel_data;
  60922. var width = header.width, height = header.height;
  60923. var i = 0, x, y;
  60924. var imageData = new Uint8Array(width * height * 4);
  60925. for (y = y_start; y !== y_end; y += y_step) {
  60926. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  60927. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  60928. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  60929. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  60930. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  60931. }
  60932. }
  60933. return imageData;
  60934. };
  60935. return TGATools;
  60936. }());
  60937. TGATools._TYPE_NO_DATA = 0;
  60938. TGATools._TYPE_INDEXED = 1;
  60939. TGATools._TYPE_RGB = 2;
  60940. TGATools._TYPE_GREY = 3;
  60941. TGATools._TYPE_RLE_INDEXED = 9;
  60942. TGATools._TYPE_RLE_RGB = 10;
  60943. TGATools._TYPE_RLE_GREY = 11;
  60944. TGATools._ORIGIN_MASK = 0x30;
  60945. TGATools._ORIGIN_SHIFT = 0x04;
  60946. TGATools._ORIGIN_BL = 0x00;
  60947. TGATools._ORIGIN_BR = 0x01;
  60948. TGATools._ORIGIN_UL = 0x02;
  60949. TGATools._ORIGIN_UR = 0x03;
  60950. Internals.TGATools = TGATools;
  60951. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  60952. })(BABYLON || (BABYLON = {}));
  60953. //# sourceMappingURL=babylon.tga.js.map
  60954. var BABYLON;
  60955. (function (BABYLON) {
  60956. var Internals;
  60957. (function (Internals) {
  60958. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  60959. // All values and structures referenced from:
  60960. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  60961. var DDS_MAGIC = 0x20534444;
  60962. 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;
  60963. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  60964. 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;
  60965. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  60966. function FourCCToInt32(value) {
  60967. return value.charCodeAt(0) +
  60968. (value.charCodeAt(1) << 8) +
  60969. (value.charCodeAt(2) << 16) +
  60970. (value.charCodeAt(3) << 24);
  60971. }
  60972. function Int32ToFourCC(value) {
  60973. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  60974. }
  60975. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  60976. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  60977. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  60978. var FOURCC_DX10 = FourCCToInt32("DX10");
  60979. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  60980. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  60981. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  60982. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  60983. var headerLengthInt = 31; // The header length in 32 bit ints
  60984. // Offsets into the header array
  60985. var off_magic = 0;
  60986. var off_size = 1;
  60987. var off_flags = 2;
  60988. var off_height = 3;
  60989. var off_width = 4;
  60990. var off_mipmapCount = 7;
  60991. var off_pfFlags = 20;
  60992. var off_pfFourCC = 21;
  60993. var off_RGBbpp = 22;
  60994. var off_RMask = 23;
  60995. var off_GMask = 24;
  60996. var off_BMask = 25;
  60997. var off_AMask = 26;
  60998. var off_caps1 = 27;
  60999. var off_caps2 = 28;
  61000. var off_caps3 = 29;
  61001. var off_caps4 = 30;
  61002. var off_dxgiFormat = 32;
  61003. ;
  61004. var DDSTools = (function () {
  61005. function DDSTools() {
  61006. }
  61007. DDSTools.GetDDSInfo = function (arrayBuffer) {
  61008. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  61009. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  61010. var mipmapCount = 1;
  61011. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  61012. mipmapCount = Math.max(1, header[off_mipmapCount]);
  61013. }
  61014. var fourCC = header[off_pfFourCC];
  61015. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  61016. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  61017. switch (fourCC) {
  61018. case FOURCC_D3DFMT_R16G16B16A16F:
  61019. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  61020. break;
  61021. case FOURCC_D3DFMT_R32G32B32A32F:
  61022. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  61023. break;
  61024. case FOURCC_DX10:
  61025. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  61026. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  61027. break;
  61028. }
  61029. }
  61030. return {
  61031. width: header[off_width],
  61032. height: header[off_height],
  61033. mipmapCount: mipmapCount,
  61034. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  61035. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  61036. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  61037. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  61038. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || FOURCC_DXT1 === FOURCC_DXT5),
  61039. dxgiFormat: dxgiFormat,
  61040. textureType: textureType
  61041. };
  61042. };
  61043. DDSTools._ToHalfFloat = function (value) {
  61044. if (!DDSTools._FloatView) {
  61045. DDSTools._FloatView = new Float32Array(1);
  61046. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  61047. }
  61048. DDSTools._FloatView[0] = value;
  61049. var x = DDSTools._Int32View[0];
  61050. var bits = (x >> 16) & 0x8000; /* Get the sign */
  61051. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  61052. var e = (x >> 23) & 0xff; /* Using int is faster here */
  61053. /* If zero, or denormal, or exponent underflows too much for a denormal
  61054. * half, return signed zero. */
  61055. if (e < 103) {
  61056. return bits;
  61057. }
  61058. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  61059. if (e > 142) {
  61060. bits |= 0x7c00;
  61061. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  61062. * not Inf, so make sure we set one mantissa bit too. */
  61063. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  61064. return bits;
  61065. }
  61066. /* If exponent underflows but not too much, return a denormal */
  61067. if (e < 113) {
  61068. m |= 0x0800;
  61069. /* Extra rounding may overflow and set mantissa to 0 and exponent
  61070. * to 1, which is OK. */
  61071. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  61072. return bits;
  61073. }
  61074. bits |= ((e - 112) << 10) | (m >> 1);
  61075. bits += m & 1;
  61076. return bits;
  61077. };
  61078. DDSTools._FromHalfFloat = function (value) {
  61079. var s = (value & 0x8000) >> 15;
  61080. var e = (value & 0x7C00) >> 10;
  61081. var f = value & 0x03FF;
  61082. if (e === 0) {
  61083. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  61084. }
  61085. else if (e == 0x1F) {
  61086. return f ? NaN : ((s ? -1 : 1) * Infinity);
  61087. }
  61088. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  61089. };
  61090. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  61091. var destArray = new Float32Array(dataLength);
  61092. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  61093. var index = 0;
  61094. for (var y = 0; y < height; y++) {
  61095. for (var x = 0; x < width; x++) {
  61096. var srcPos = (x + y * width) * 4;
  61097. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  61098. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  61099. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  61100. if (DDSTools.StoreLODInAlphaChannel) {
  61101. destArray[index + 3] = lod;
  61102. }
  61103. else {
  61104. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  61105. }
  61106. index += 4;
  61107. }
  61108. }
  61109. return destArray;
  61110. };
  61111. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  61112. if (DDSTools.StoreLODInAlphaChannel) {
  61113. var destArray = new Uint16Array(dataLength);
  61114. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  61115. var index = 0;
  61116. for (var y = 0; y < height; y++) {
  61117. for (var x = 0; x < width; x++) {
  61118. var srcPos = (x + y * width) * 4;
  61119. destArray[index] = srcData[srcPos];
  61120. destArray[index + 1] = srcData[srcPos + 1];
  61121. destArray[index + 2] = srcData[srcPos + 2];
  61122. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  61123. index += 4;
  61124. }
  61125. }
  61126. return destArray;
  61127. }
  61128. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  61129. };
  61130. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  61131. if (DDSTools.StoreLODInAlphaChannel) {
  61132. var destArray = new Float32Array(dataLength);
  61133. var srcData = new Float32Array(arrayBuffer, dataOffset);
  61134. var index = 0;
  61135. for (var y = 0; y < height; y++) {
  61136. for (var x = 0; x < width; x++) {
  61137. var srcPos = (x + y * width) * 4;
  61138. destArray[index] = srcData[srcPos];
  61139. destArray[index + 1] = srcData[srcPos + 1];
  61140. destArray[index + 2] = srcData[srcPos + 2];
  61141. destArray[index + 3] = lod;
  61142. index += 4;
  61143. }
  61144. }
  61145. return destArray;
  61146. }
  61147. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  61148. };
  61149. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  61150. var destArray = new Uint8Array(dataLength);
  61151. var srcData = new Float32Array(arrayBuffer, dataOffset);
  61152. var index = 0;
  61153. for (var y = 0; y < height; y++) {
  61154. for (var x = 0; x < width; x++) {
  61155. var srcPos = (x + y * width) * 4;
  61156. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  61157. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  61158. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  61159. if (DDSTools.StoreLODInAlphaChannel) {
  61160. destArray[index + 3] = lod;
  61161. }
  61162. else {
  61163. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  61164. }
  61165. index += 4;
  61166. }
  61167. }
  61168. return destArray;
  61169. };
  61170. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  61171. var destArray = new Uint8Array(dataLength);
  61172. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  61173. var index = 0;
  61174. for (var y = 0; y < height; y++) {
  61175. for (var x = 0; x < width; x++) {
  61176. var srcPos = (x + y * width) * 4;
  61177. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  61178. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  61179. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  61180. if (DDSTools.StoreLODInAlphaChannel) {
  61181. destArray[index + 3] = lod;
  61182. }
  61183. else {
  61184. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  61185. }
  61186. index += 4;
  61187. }
  61188. }
  61189. return destArray;
  61190. };
  61191. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  61192. var byteArray = new Uint8Array(dataLength);
  61193. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  61194. var index = 0;
  61195. for (var y = 0; y < height; y++) {
  61196. for (var x = 0; x < width; x++) {
  61197. var srcPos = (x + y * width) * 4;
  61198. byteArray[index] = srcData[srcPos + 2];
  61199. byteArray[index + 1] = srcData[srcPos + 1];
  61200. byteArray[index + 2] = srcData[srcPos];
  61201. byteArray[index + 3] = srcData[srcPos + 3];
  61202. index += 4;
  61203. }
  61204. }
  61205. return byteArray;
  61206. };
  61207. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  61208. var byteArray = new Uint8Array(dataLength);
  61209. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  61210. var index = 0;
  61211. for (var y = 0; y < height; y++) {
  61212. for (var x = 0; x < width; x++) {
  61213. var srcPos = (x + y * width) * 3;
  61214. byteArray[index] = srcData[srcPos + 2];
  61215. byteArray[index + 1] = srcData[srcPos + 1];
  61216. byteArray[index + 2] = srcData[srcPos];
  61217. index += 3;
  61218. }
  61219. }
  61220. return byteArray;
  61221. };
  61222. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  61223. var byteArray = new Uint8Array(dataLength);
  61224. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  61225. var index = 0;
  61226. for (var y = 0; y < height; y++) {
  61227. for (var x = 0; x < width; x++) {
  61228. var srcPos = (x + y * width);
  61229. byteArray[index] = srcData[srcPos];
  61230. index++;
  61231. }
  61232. }
  61233. return byteArray;
  61234. };
  61235. DDSTools.UploadDDSLevels = function (engine, arrayBuffer, info, loadMipmaps, faces, lodIndex) {
  61236. if (lodIndex === void 0) { lodIndex = -1; }
  61237. var gl = engine._gl;
  61238. var ext = engine.getCaps().s3tc;
  61239. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, format, width, height, dataLength, dataOffset, byteArray, mipmapCount, mip;
  61240. if (header[off_magic] != DDS_MAGIC) {
  61241. BABYLON.Tools.Error("Invalid magic number in DDS header");
  61242. return;
  61243. }
  61244. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  61245. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  61246. return;
  61247. }
  61248. if (info.isCompressed && !ext) {
  61249. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  61250. return;
  61251. }
  61252. var bpp = header[off_RGBbpp];
  61253. dataOffset = header[off_size] + 4;
  61254. var computeFormats = false;
  61255. if (info.isFourCC) {
  61256. fourCC = header[off_pfFourCC];
  61257. switch (fourCC) {
  61258. case FOURCC_DXT1:
  61259. blockBytes = 8;
  61260. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  61261. break;
  61262. case FOURCC_DXT3:
  61263. blockBytes = 16;
  61264. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  61265. break;
  61266. case FOURCC_DXT5:
  61267. blockBytes = 16;
  61268. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  61269. break;
  61270. case FOURCC_D3DFMT_R16G16B16A16F:
  61271. computeFormats = true;
  61272. break;
  61273. case FOURCC_D3DFMT_R32G32B32A32F:
  61274. computeFormats = true;
  61275. break;
  61276. case FOURCC_DX10:
  61277. // There is an additionnal header so dataOffset need to be changed
  61278. dataOffset += 5 * 4; // 5 uints
  61279. var supported = false;
  61280. switch (info.dxgiFormat) {
  61281. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  61282. computeFormats = true;
  61283. supported = true;
  61284. break;
  61285. case DXGI_FORMAT_B8G8R8X8_UNORM:
  61286. info.isRGB = true;
  61287. info.isFourCC = false;
  61288. bpp = 32;
  61289. supported = true;
  61290. break;
  61291. }
  61292. if (supported) {
  61293. break;
  61294. }
  61295. default:
  61296. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  61297. return;
  61298. }
  61299. }
  61300. if (computeFormats) {
  61301. format = engine._getWebGLTextureType(info.textureType);
  61302. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  61303. }
  61304. mipmapCount = 1;
  61305. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  61306. mipmapCount = Math.max(1, header[off_mipmapCount]);
  61307. }
  61308. for (var face = 0; face < faces; face++) {
  61309. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  61310. width = header[off_width];
  61311. height = header[off_height];
  61312. for (mip = 0; mip < mipmapCount; ++mip) {
  61313. if (lodIndex === -1 || lodIndex === mip) {
  61314. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  61315. var i = (lodIndex === -1) ? mip : 0;
  61316. if (!info.isCompressed && info.isFourCC) {
  61317. dataLength = width * height * 4;
  61318. var floatArray;
  61319. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  61320. if (bpp === 128) {
  61321. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  61322. }
  61323. else if (bpp === 64) {
  61324. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  61325. }
  61326. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  61327. format = engine._getWebGLTextureType(info.textureType);
  61328. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  61329. }
  61330. else {
  61331. if (bpp === 128) {
  61332. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  61333. }
  61334. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  61335. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  61336. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  61337. format = engine._getWebGLTextureType(info.textureType);
  61338. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  61339. }
  61340. else {
  61341. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  61342. }
  61343. }
  61344. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  61345. }
  61346. else if (info.isRGB) {
  61347. if (bpp === 24) {
  61348. dataLength = width * height * 3;
  61349. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  61350. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  61351. }
  61352. else {
  61353. dataLength = width * height * 4;
  61354. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  61355. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  61356. }
  61357. }
  61358. else if (info.isLuminance) {
  61359. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  61360. var unpaddedRowSize = width;
  61361. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  61362. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  61363. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  61364. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  61365. }
  61366. else {
  61367. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  61368. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  61369. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  61370. }
  61371. }
  61372. dataOffset += width * height * (bpp / 8);
  61373. width *= 0.5;
  61374. height *= 0.5;
  61375. width = Math.max(1.0, width);
  61376. height = Math.max(1.0, height);
  61377. }
  61378. }
  61379. };
  61380. return DDSTools;
  61381. }());
  61382. DDSTools.StoreLODInAlphaChannel = false;
  61383. Internals.DDSTools = DDSTools;
  61384. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  61385. })(BABYLON || (BABYLON = {}));
  61386. //# sourceMappingURL=babylon.dds.js.map
  61387. var BABYLON;
  61388. (function (BABYLON) {
  61389. var Internals;
  61390. (function (Internals) {
  61391. /**
  61392. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  61393. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  61394. */
  61395. var KhronosTextureContainer = (function () {
  61396. /**
  61397. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  61398. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  61399. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  61400. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  61401. */
  61402. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  61403. this.arrayBuffer = arrayBuffer;
  61404. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  61405. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  61406. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  61407. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  61408. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  61409. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  61410. BABYLON.Tools.Error("texture missing KTX identifier");
  61411. return;
  61412. }
  61413. // load the reset of the header in native 32 bit int
  61414. var header = new Int32Array(this.arrayBuffer, 12, 13);
  61415. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  61416. var oppositeEndianess = header[0] === 0x01020304;
  61417. // read all the header elements in order they exist in the file, without modification (sans endainness)
  61418. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  61419. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  61420. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  61421. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  61422. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  61423. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  61424. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  61425. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  61426. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  61427. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  61428. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  61429. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  61430. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  61431. if (this.glType !== 0) {
  61432. BABYLON.Tools.Error("only compressed formats currently supported");
  61433. return;
  61434. }
  61435. else {
  61436. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  61437. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  61438. }
  61439. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  61440. BABYLON.Tools.Error("only 2D textures currently supported");
  61441. return;
  61442. }
  61443. if (this.numberOfArrayElements !== 0) {
  61444. BABYLON.Tools.Error("texture arrays not currently supported");
  61445. return;
  61446. }
  61447. if (this.numberOfFaces !== facesExpected) {
  61448. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  61449. return;
  61450. }
  61451. // we now have a completely validated file, so could use existence of loadType as success
  61452. // would need to make this more elaborate & adjust checks above to support more than one load type
  61453. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  61454. }
  61455. // not as fast hardware based, but will probably never need to use
  61456. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  61457. return ((val & 0xFF) << 24)
  61458. | ((val & 0xFF00) << 8)
  61459. | ((val >> 8) & 0xFF00)
  61460. | ((val >> 24) & 0xFF);
  61461. };
  61462. /**
  61463. * It is assumed that the texture has already been created & is currently bound
  61464. */
  61465. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  61466. switch (this.loadType) {
  61467. case KhronosTextureContainer.COMPRESSED_2D:
  61468. this._upload2DCompressedLevels(gl, loadMipmaps);
  61469. break;
  61470. case KhronosTextureContainer.TEX_2D:
  61471. case KhronosTextureContainer.COMPRESSED_3D:
  61472. case KhronosTextureContainer.TEX_3D:
  61473. }
  61474. };
  61475. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  61476. // initialize width & height for level 1
  61477. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  61478. var width = this.pixelWidth;
  61479. var height = this.pixelHeight;
  61480. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  61481. for (var level = 0; level < mipmapCount; level++) {
  61482. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  61483. for (var face = 0; face < this.numberOfFaces; face++) {
  61484. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  61485. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  61486. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  61487. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  61488. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  61489. }
  61490. width = Math.max(1.0, width * 0.5);
  61491. height = Math.max(1.0, height * 0.5);
  61492. }
  61493. };
  61494. return KhronosTextureContainer;
  61495. }());
  61496. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  61497. // load types
  61498. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  61499. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  61500. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  61501. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  61502. Internals.KhronosTextureContainer = KhronosTextureContainer;
  61503. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  61504. })(BABYLON || (BABYLON = {}));
  61505. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  61506. var BABYLON;
  61507. (function (BABYLON) {
  61508. var DynamicFloatArrayElementInfo = (function () {
  61509. function DynamicFloatArrayElementInfo() {
  61510. }
  61511. return DynamicFloatArrayElementInfo;
  61512. }());
  61513. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  61514. /**
  61515. * 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.
  61516. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  61517. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  61518. * 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.
  61519. * 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.
  61520. * 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".
  61521. */
  61522. var DynamicFloatArray = (function () {
  61523. /**
  61524. * Construct an instance of the dynamic float array
  61525. * @param stride size of one element in float (i.e. not bytes!)
  61526. * @param initialElementCount the number of available entries at construction
  61527. */
  61528. function DynamicFloatArray(stride, initialElementCount) {
  61529. this.compareValueOffset = null;
  61530. this.sortingAscending = true;
  61531. this._stride = stride;
  61532. this.buffer = new Float32Array(stride * initialElementCount);
  61533. this._lastUsed = 0;
  61534. this._firstFree = 0;
  61535. this._allEntries = new Array(initialElementCount);
  61536. this._freeEntries = new Array(initialElementCount);
  61537. for (var i = 0; i < initialElementCount; i++) {
  61538. var element = new DynamicFloatArrayElementInfo();
  61539. element.offset = i * stride;
  61540. this._allEntries[i] = element;
  61541. this._freeEntries[initialElementCount - i - 1] = element;
  61542. }
  61543. }
  61544. /**
  61545. * Allocate an element in the array.
  61546. * @return the element info instance that contains the offset into the main buffer of the element's location.
  61547. * Beware, this offset may change when you call pack()
  61548. */
  61549. DynamicFloatArray.prototype.allocElement = function () {
  61550. if (this._freeEntries.length === 0) {
  61551. this._growBuffer();
  61552. }
  61553. var el = this._freeEntries.pop();
  61554. this._lastUsed = Math.max(el.offset, this._lastUsed);
  61555. if (el.offset === this._firstFree) {
  61556. if (this._freeEntries.length > 0) {
  61557. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  61558. }
  61559. else {
  61560. this._firstFree += this._stride;
  61561. }
  61562. }
  61563. return el;
  61564. };
  61565. /**
  61566. * Free the element corresponding to the given element info
  61567. * @param elInfo the element that describe the allocated element
  61568. */
  61569. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  61570. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  61571. this._freeEntries.push(elInfo);
  61572. };
  61573. /**
  61574. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  61575. * 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().
  61576. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  61577. */
  61578. DynamicFloatArray.prototype.pack = function () {
  61579. // no free slot? no need to pack
  61580. if (this._freeEntries.length === 0) {
  61581. return this.buffer;
  61582. }
  61583. // If the buffer is already packed the last used will always be lower than the first free
  61584. // 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.
  61585. if (this._lastUsed < this._firstFree) {
  61586. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  61587. return elementsBuffer_1;
  61588. }
  61589. var s = this._stride;
  61590. // 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
  61591. var lastFree = new DynamicFloatArrayElementInfo();
  61592. lastFree.offset = this.totalElementCount * s;
  61593. this._freeEntries.push(lastFree);
  61594. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  61595. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  61596. var firstFreeSlotOffset = sortedFree[0].offset;
  61597. var freeZoneSize = 1;
  61598. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  61599. var prevOffset = sortedFree[0].offset;
  61600. for (var i = 1; i < sortedFree.length; i++) {
  61601. // 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
  61602. if (firstFreeSlotOffset >= occupiedZoneSize) {
  61603. break;
  61604. }
  61605. var curFree = sortedFree[i];
  61606. var curOffset = curFree.offset;
  61607. // Compute the distance between this offset and the previous
  61608. var distance = curOffset - prevOffset;
  61609. // If the distance is the stride size, they are adjacent, it good, move to the next
  61610. if (distance === s) {
  61611. // Free zone is one element bigger
  61612. ++freeZoneSize;
  61613. // as we're about to iterate to the next, the cur becomes the previous...
  61614. prevOffset = curOffset;
  61615. continue;
  61616. }
  61617. // Distance is bigger, which means there's x element between the previous free and this one
  61618. var usedRange = (distance / s) - 1;
  61619. // Two cases the free zone is smaller than the data to move or bigger
  61620. // Copy what can fit in the free zone
  61621. var curMoveOffset = curOffset - s;
  61622. var copyCount = Math.min(freeZoneSize, usedRange);
  61623. for (var j = 0; j < copyCount; j++) {
  61624. var freeI = firstFreeSlotOffset / s;
  61625. var curI = curMoveOffset / s;
  61626. var moveEl = sortedAll[curI];
  61627. this._moveElement(moveEl, firstFreeSlotOffset);
  61628. var replacedEl = sortedAll[freeI];
  61629. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  61630. replacedEl.offset = curMoveOffset;
  61631. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  61632. sortedAll[freeI] = moveEl;
  61633. sortedAll[curI] = replacedEl;
  61634. curMoveOffset -= s;
  61635. firstFreeSlotOffset += s;
  61636. }
  61637. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  61638. if (freeZoneSize <= usedRange) {
  61639. firstFreeSlotOffset = curMoveOffset + s;
  61640. freeZoneSize = 1 + copyCount;
  61641. }
  61642. else {
  61643. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  61644. }
  61645. // as we're about to iterate to the next, the cur becomes the previous...
  61646. prevOffset = curOffset;
  61647. }
  61648. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  61649. this._lastUsed = firstFreeSlotOffset - s;
  61650. this._firstFree = firstFreeSlotOffset;
  61651. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  61652. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  61653. this._allEntries = sortedAll;
  61654. return elementsBuffer;
  61655. };
  61656. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  61657. for (var i = 0; i < this._stride; i++) {
  61658. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  61659. }
  61660. element.offset = destOffset;
  61661. };
  61662. DynamicFloatArray.prototype._growBuffer = function () {
  61663. // Allocate the new buffer with 50% more entries, copy the content of the current one
  61664. var newElCount = Math.floor(this.totalElementCount * 1.5);
  61665. var newBuffer = new Float32Array(newElCount * this._stride);
  61666. newBuffer.set(this.buffer);
  61667. var curCount = this.totalElementCount;
  61668. var addedCount = newElCount - this.totalElementCount;
  61669. for (var i = 0; i < addedCount; i++) {
  61670. var element = new DynamicFloatArrayElementInfo();
  61671. element.offset = (curCount + i) * this.stride;
  61672. this._allEntries.push(element);
  61673. this._freeEntries[addedCount - i - 1] = element;
  61674. }
  61675. this._firstFree = curCount * this.stride;
  61676. this.buffer = newBuffer;
  61677. };
  61678. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  61679. /**
  61680. * Get the total count of entries that can fit in the current buffer
  61681. * @returns the elements count
  61682. */
  61683. get: function () {
  61684. return this._allEntries.length;
  61685. },
  61686. enumerable: true,
  61687. configurable: true
  61688. });
  61689. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  61690. /**
  61691. * Get the count of free entries that can still be allocated without resizing the buffer
  61692. * @returns the free elements count
  61693. */
  61694. get: function () {
  61695. return this._freeEntries.length;
  61696. },
  61697. enumerable: true,
  61698. configurable: true
  61699. });
  61700. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  61701. /**
  61702. * Get the count of allocated elements
  61703. * @returns the allocated elements count
  61704. */
  61705. get: function () {
  61706. return this._allEntries.length - this._freeEntries.length;
  61707. },
  61708. enumerable: true,
  61709. configurable: true
  61710. });
  61711. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  61712. /**
  61713. * Return the size of one element in float
  61714. * @returns the size in float
  61715. */
  61716. get: function () {
  61717. return this._stride;
  61718. },
  61719. enumerable: true,
  61720. configurable: true
  61721. });
  61722. DynamicFloatArray.prototype.sort = function () {
  61723. var _this = this;
  61724. if (!this.compareValueOffset) {
  61725. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  61726. }
  61727. var count = this.usedElementCount;
  61728. // Do we have to (re)create the sort table?
  61729. if (!this._sortTable || this._sortTable.length < count) {
  61730. // 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...
  61731. var newCount = Math.min(this.totalElementCount, count * 2);
  61732. this._sortTable = new Array(newCount);
  61733. }
  61734. if (!this._sortedTable || this._sortedTable.length !== count) {
  61735. this._sortedTable = new Array(count);
  61736. }
  61737. // Because, you know...
  61738. this.pack();
  61739. //let stride = this.stride;
  61740. //for (let i = 0; i < count; i++) {
  61741. // let si = this._sortTable[i];
  61742. // if (!si) {
  61743. // si = new SortInfo();
  61744. // this._sortTable[i] = si;
  61745. // }
  61746. // si.entry = this._allEntries[i];
  61747. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  61748. // si.swapedOffset = null;
  61749. // this._sortedTable[i] = si;
  61750. //}
  61751. var curOffset = 0;
  61752. var stride = this.stride;
  61753. for (var i = 0; i < count; i++, curOffset += stride) {
  61754. var si = this._sortTable[i];
  61755. if (!si) {
  61756. si = new SortInfo();
  61757. this._sortTable[i] = si;
  61758. }
  61759. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  61760. si.offset = curOffset;
  61761. si.swapedOffset = null;
  61762. this._sortedTable[i] = si;
  61763. }
  61764. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  61765. if (this.sortingAscending) {
  61766. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  61767. }
  61768. else {
  61769. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  61770. }
  61771. var swapElements = function (src, dst) {
  61772. for (var i = 0; i < stride; i++) {
  61773. var tps = _this.buffer[dst + i];
  61774. _this.buffer[dst + i] = _this.buffer[src + i];
  61775. _this.buffer[src + i] = tps;
  61776. }
  61777. };
  61778. // 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:
  61779. // 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),
  61780. // and I still want something with a good algorithm complexity.
  61781. // 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,
  61782. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  61783. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  61784. // 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
  61785. // until we find a SortInfo object without a swapedOffset which means we got the right location
  61786. // 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
  61787. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  61788. for (var i = 0; i < count; i++) {
  61789. // Get the element to move
  61790. var sourceSI = this._sortedTable[i];
  61791. var destSI = this._sortTable[i];
  61792. var sourceOff = sourceSI.offset;
  61793. // If the source changed location, find the new one
  61794. if (sourceSI.swapedOffset) {
  61795. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  61796. var curSI = sourceSI;
  61797. while (curSI.swapedOffset) {
  61798. curSI = this._sortTable[curSI.swapedOffset / stride];
  61799. }
  61800. // Finally get the right location
  61801. sourceOff = curSI.offset;
  61802. }
  61803. // Tag the element being replaced with its new location
  61804. destSI.swapedOffset = sourceOff;
  61805. // Swap elements (only if needed)
  61806. if (sourceOff !== destSI.offset) {
  61807. swapElements(sourceOff, destSI.offset);
  61808. }
  61809. // Update the offset in the corresponding DFAE
  61810. //sourceSI.entry.offset = destSI.entry.offset;
  61811. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  61812. }
  61813. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  61814. return true;
  61815. };
  61816. return DynamicFloatArray;
  61817. }());
  61818. BABYLON.DynamicFloatArray = DynamicFloatArray;
  61819. var SortInfo = (function () {
  61820. function SortInfo() {
  61821. this.compareData = this.offset = this.swapedOffset = null;
  61822. }
  61823. return SortInfo;
  61824. }());
  61825. })(BABYLON || (BABYLON = {}));
  61826. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  61827. var BABYLON;
  61828. (function (BABYLON) {
  61829. var Debug;
  61830. (function (Debug) {
  61831. /**
  61832. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  61833. */
  61834. var SkeletonViewer = (function () {
  61835. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  61836. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  61837. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  61838. this.skeleton = skeleton;
  61839. this.mesh = mesh;
  61840. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  61841. this.renderingGroupId = renderingGroupId;
  61842. this.color = BABYLON.Color3.White();
  61843. this._debugLines = [];
  61844. this._isEnabled = false;
  61845. this._scene = scene;
  61846. this.update();
  61847. this._renderFunction = this.update.bind(this);
  61848. }
  61849. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  61850. get: function () {
  61851. return this._isEnabled;
  61852. },
  61853. set: function (value) {
  61854. if (this._isEnabled === value) {
  61855. return;
  61856. }
  61857. this._isEnabled = value;
  61858. if (value) {
  61859. this._scene.registerBeforeRender(this._renderFunction);
  61860. }
  61861. else {
  61862. this._scene.unregisterBeforeRender(this._renderFunction);
  61863. }
  61864. },
  61865. enumerable: true,
  61866. configurable: true
  61867. });
  61868. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  61869. if (x === void 0) { x = 0; }
  61870. if (y === void 0) { y = 0; }
  61871. if (z === void 0) { z = 0; }
  61872. var tmat = BABYLON.Tmp.Matrix[0];
  61873. var parentBone = bone.getParent();
  61874. tmat.copyFrom(bone.getLocalMatrix());
  61875. if (x !== 0 || y !== 0 || z !== 0) {
  61876. var tmat2 = BABYLON.Tmp.Matrix[1];
  61877. BABYLON.Matrix.IdentityToRef(tmat2);
  61878. tmat2.m[12] = x;
  61879. tmat2.m[13] = y;
  61880. tmat2.m[14] = z;
  61881. tmat2.multiplyToRef(tmat, tmat);
  61882. }
  61883. if (parentBone) {
  61884. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  61885. }
  61886. tmat.multiplyToRef(meshMat, tmat);
  61887. position.x = tmat.m[12];
  61888. position.y = tmat.m[13];
  61889. position.z = tmat.m[14];
  61890. };
  61891. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  61892. var len = bones.length;
  61893. var meshPos = this.mesh.position;
  61894. for (var i = 0; i < len; i++) {
  61895. var bone = bones[i];
  61896. var points = this._debugLines[i];
  61897. if (!points) {
  61898. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61899. this._debugLines[i] = points;
  61900. }
  61901. this._getBonePosition(points[0], bone, meshMat);
  61902. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  61903. points[0].subtractInPlace(meshPos);
  61904. points[1].subtractInPlace(meshPos);
  61905. }
  61906. };
  61907. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  61908. var len = bones.length;
  61909. var boneNum = 0;
  61910. var meshPos = this.mesh.position;
  61911. for (var i = len - 1; i >= 0; i--) {
  61912. var childBone = bones[i];
  61913. var parentBone = childBone.getParent();
  61914. if (!parentBone) {
  61915. continue;
  61916. }
  61917. var points = this._debugLines[boneNum];
  61918. if (!points) {
  61919. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61920. this._debugLines[boneNum] = points;
  61921. }
  61922. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  61923. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  61924. points[0].subtractInPlace(meshPos);
  61925. points[1].subtractInPlace(meshPos);
  61926. boneNum++;
  61927. }
  61928. };
  61929. SkeletonViewer.prototype.update = function () {
  61930. if (this.autoUpdateBonesMatrices) {
  61931. this.skeleton.computeAbsoluteTransforms();
  61932. }
  61933. if (this.skeleton.bones[0].length === undefined) {
  61934. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  61935. }
  61936. else {
  61937. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  61938. }
  61939. if (!this._debugMesh) {
  61940. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  61941. this._debugMesh.renderingGroupId = this.renderingGroupId;
  61942. }
  61943. else {
  61944. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  61945. }
  61946. this._debugMesh.position.copyFrom(this.mesh.position);
  61947. this._debugMesh.color = this.color;
  61948. };
  61949. SkeletonViewer.prototype.dispose = function () {
  61950. if (this._debugMesh) {
  61951. this.isEnabled = false;
  61952. this._debugMesh.dispose();
  61953. this._debugMesh = null;
  61954. }
  61955. };
  61956. return SkeletonViewer;
  61957. }());
  61958. Debug.SkeletonViewer = SkeletonViewer;
  61959. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  61960. })(BABYLON || (BABYLON = {}));
  61961. //# sourceMappingURL=babylon.skeletonViewer.js.map
  61962. var BABYLON;
  61963. (function (BABYLON) {
  61964. var Debug;
  61965. (function (Debug) {
  61966. var AxesViewer = (function () {
  61967. function AxesViewer(scene, scaleLines) {
  61968. if (scaleLines === void 0) { scaleLines = 1; }
  61969. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61970. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61971. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61972. this.scaleLines = 1;
  61973. this.scaleLines = scaleLines;
  61974. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  61975. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  61976. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  61977. this._xmesh.renderingGroupId = 2;
  61978. this._ymesh.renderingGroupId = 2;
  61979. this._zmesh.renderingGroupId = 2;
  61980. this._xmesh.material.checkReadyOnlyOnce = true;
  61981. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  61982. this._ymesh.material.checkReadyOnlyOnce = true;
  61983. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  61984. this._zmesh.material.checkReadyOnlyOnce = true;
  61985. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  61986. this.scene = scene;
  61987. }
  61988. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  61989. var scaleLines = this.scaleLines;
  61990. this._xmesh.position.copyFrom(position);
  61991. this._ymesh.position.copyFrom(position);
  61992. this._zmesh.position.copyFrom(position);
  61993. var point2 = this._xline[1];
  61994. point2.x = xaxis.x * scaleLines;
  61995. point2.y = xaxis.y * scaleLines;
  61996. point2.z = xaxis.z * scaleLines;
  61997. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  61998. point2 = this._yline[1];
  61999. point2.x = yaxis.x * scaleLines;
  62000. point2.y = yaxis.y * scaleLines;
  62001. point2.z = yaxis.z * scaleLines;
  62002. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  62003. point2 = this._zline[1];
  62004. point2.x = zaxis.x * scaleLines;
  62005. point2.y = zaxis.y * scaleLines;
  62006. point2.z = zaxis.z * scaleLines;
  62007. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  62008. };
  62009. AxesViewer.prototype.dispose = function () {
  62010. if (this._xmesh) {
  62011. this._xmesh.dispose();
  62012. this._ymesh.dispose();
  62013. this._zmesh.dispose();
  62014. this._xmesh = null;
  62015. this._ymesh = null;
  62016. this._zmesh = null;
  62017. this._xline = null;
  62018. this._yline = null;
  62019. this._zline = null;
  62020. this.scene = null;
  62021. }
  62022. };
  62023. return AxesViewer;
  62024. }());
  62025. Debug.AxesViewer = AxesViewer;
  62026. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62027. })(BABYLON || (BABYLON = {}));
  62028. //# sourceMappingURL=babylon.axesViewer.js.map
  62029. var BABYLON;
  62030. (function (BABYLON) {
  62031. var Debug;
  62032. (function (Debug) {
  62033. var BoneAxesViewer = (function (_super) {
  62034. __extends(BoneAxesViewer, _super);
  62035. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  62036. if (scaleLines === void 0) { scaleLines = 1; }
  62037. var _this = _super.call(this, scene, scaleLines) || this;
  62038. _this.pos = BABYLON.Vector3.Zero();
  62039. _this.xaxis = BABYLON.Vector3.Zero();
  62040. _this.yaxis = BABYLON.Vector3.Zero();
  62041. _this.zaxis = BABYLON.Vector3.Zero();
  62042. _this.mesh = mesh;
  62043. _this.bone = bone;
  62044. return _this;
  62045. }
  62046. BoneAxesViewer.prototype.update = function () {
  62047. var bone = this.bone;
  62048. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  62049. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  62050. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  62051. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  62052. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  62053. };
  62054. BoneAxesViewer.prototype.dispose = function () {
  62055. if (this.pos) {
  62056. this.pos = null;
  62057. this.xaxis = null;
  62058. this.yaxis = null;
  62059. this.zaxis = null;
  62060. this.mesh = null;
  62061. this.bone = null;
  62062. _super.prototype.dispose.call(this);
  62063. }
  62064. };
  62065. return BoneAxesViewer;
  62066. }(Debug.AxesViewer));
  62067. Debug.BoneAxesViewer = BoneAxesViewer;
  62068. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62069. })(BABYLON || (BABYLON = {}));
  62070. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  62071. var BABYLON;
  62072. (function (BABYLON) {
  62073. var RayHelper = (function () {
  62074. function RayHelper(ray) {
  62075. this.ray = ray;
  62076. }
  62077. RayHelper.CreateAndShow = function (ray, scene, color) {
  62078. var helper = new RayHelper(ray);
  62079. helper.show(scene, color);
  62080. return helper;
  62081. };
  62082. RayHelper.prototype.show = function (scene, color) {
  62083. if (!this._renderFunction) {
  62084. var ray = this.ray;
  62085. this._renderFunction = this._render.bind(this);
  62086. this._scene = scene;
  62087. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  62088. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  62089. this._scene.registerBeforeRender(this._renderFunction);
  62090. }
  62091. if (color) {
  62092. this._renderLine.color.copyFrom(color);
  62093. }
  62094. };
  62095. RayHelper.prototype.hide = function () {
  62096. if (this._renderFunction) {
  62097. this._scene.unregisterBeforeRender(this._renderFunction);
  62098. this._scene = null;
  62099. this._renderFunction = null;
  62100. this._renderLine.dispose();
  62101. this._renderLine = null;
  62102. this._renderPoints = null;
  62103. }
  62104. };
  62105. RayHelper.prototype._render = function () {
  62106. var ray = this.ray;
  62107. var point = this._renderPoints[1];
  62108. var len = Math.min(ray.length, 1000000);
  62109. point.copyFrom(ray.direction);
  62110. point.scaleInPlace(len);
  62111. point.addInPlace(ray.origin);
  62112. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  62113. };
  62114. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  62115. this._attachedToMesh = mesh;
  62116. var ray = this.ray;
  62117. if (!ray.direction) {
  62118. ray.direction = BABYLON.Vector3.Zero();
  62119. }
  62120. if (!ray.origin) {
  62121. ray.origin = BABYLON.Vector3.Zero();
  62122. }
  62123. if (length) {
  62124. ray.length = length;
  62125. }
  62126. if (!meshSpaceOrigin) {
  62127. meshSpaceOrigin = BABYLON.Vector3.Zero();
  62128. }
  62129. if (!meshSpaceDirection) {
  62130. // -1 so that this will work with Mesh.lookAt
  62131. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  62132. }
  62133. if (!this._meshSpaceDirection) {
  62134. this._meshSpaceDirection = meshSpaceDirection.clone();
  62135. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  62136. }
  62137. else {
  62138. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  62139. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  62140. }
  62141. if (!this._updateToMeshFunction) {
  62142. this._updateToMeshFunction = this._updateToMesh.bind(this);
  62143. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  62144. }
  62145. this._updateToMesh();
  62146. };
  62147. RayHelper.prototype.detachFromMesh = function () {
  62148. if (this._attachedToMesh) {
  62149. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  62150. this._attachedToMesh = null;
  62151. this._updateToMeshFunction = null;
  62152. }
  62153. };
  62154. RayHelper.prototype._updateToMesh = function () {
  62155. var ray = this.ray;
  62156. if (this._attachedToMesh._isDisposed) {
  62157. this.detachFromMesh();
  62158. return;
  62159. }
  62160. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  62161. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  62162. };
  62163. RayHelper.prototype.dispose = function () {
  62164. this.hide();
  62165. this.detachFromMesh();
  62166. this.ray = null;
  62167. };
  62168. return RayHelper;
  62169. }());
  62170. BABYLON.RayHelper = RayHelper;
  62171. })(BABYLON || (BABYLON = {}));
  62172. //# sourceMappingURL=babylon.rayHelper.js.map
  62173. var BABYLON;
  62174. (function (BABYLON) {
  62175. var DebugLayer = (function () {
  62176. function DebugLayer(scene) {
  62177. this._scene = scene;
  62178. }
  62179. /** Creates the inspector window. */
  62180. DebugLayer.prototype._createInspector = function (config) {
  62181. if (config === void 0) { config = {}; }
  62182. var popup = config.popup || false;
  62183. var initialTab = config.initialTab || 0;
  62184. var parentElement = config.parentElement || null;
  62185. if (!this._inspector) {
  62186. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  62187. } // else nothing to do,; instance is already existing
  62188. };
  62189. DebugLayer.prototype.isVisible = function () {
  62190. if (!this._inspector) {
  62191. return false;
  62192. }
  62193. return true;
  62194. };
  62195. DebugLayer.prototype.hide = function () {
  62196. if (this._inspector) {
  62197. try {
  62198. this._inspector.dispose();
  62199. }
  62200. catch (e) {
  62201. // If the inspector has been removed directly from the inspector tool
  62202. }
  62203. this._inspector = null;
  62204. }
  62205. };
  62206. DebugLayer.prototype.show = function (config) {
  62207. if (config === void 0) { config = {}; }
  62208. if (typeof INSPECTOR == 'undefined') {
  62209. // Load inspector and add it to the DOM
  62210. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  62211. }
  62212. else {
  62213. // Otherwise creates the inspector
  62214. this._createInspector(config);
  62215. }
  62216. };
  62217. return DebugLayer;
  62218. }());
  62219. // Get protocol used - http or https
  62220. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  62221. BABYLON.DebugLayer = DebugLayer;
  62222. })(BABYLON || (BABYLON = {}));
  62223. //# sourceMappingURL=babylon.debugLayer.js.map
  62224. var BABYLON;
  62225. (function (BABYLON) {
  62226. var Debug;
  62227. (function (Debug) {
  62228. var PhysicsViewer = (function () {
  62229. function PhysicsViewer(scene) {
  62230. this._impostors = [];
  62231. this._meshes = [];
  62232. this._numMeshes = 0;
  62233. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  62234. this._physicsEnginePlugin = this._scene.getPhysicsEngine().getPhysicsPlugin();
  62235. }
  62236. PhysicsViewer.prototype._updateDebugMeshes = function () {
  62237. var plugin = this._physicsEnginePlugin;
  62238. for (var i = 0; i < this._numMeshes; i++) {
  62239. if (this._impostors[i].isDisposed) {
  62240. this.hideImpostor(this._impostors[i--]);
  62241. }
  62242. else {
  62243. plugin.syncMeshWithImpostor(this._meshes[i], this._impostors[i]);
  62244. }
  62245. }
  62246. };
  62247. PhysicsViewer.prototype.showImpostor = function (impostor) {
  62248. for (var i = 0; i < this._numMeshes; i++) {
  62249. if (this._impostors[i] == impostor) {
  62250. return;
  62251. }
  62252. }
  62253. var debugMesh = this._getDebugMesh(impostor, this._scene);
  62254. if (debugMesh) {
  62255. this._impostors[this._numMeshes] = impostor;
  62256. this._meshes[this._numMeshes] = debugMesh;
  62257. if (this._numMeshes === 0) {
  62258. this._renderFunction = this._updateDebugMeshes.bind(this);
  62259. this._scene.registerBeforeRender(this._renderFunction);
  62260. }
  62261. this._numMeshes++;
  62262. }
  62263. };
  62264. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  62265. var removed = false;
  62266. for (var i = 0; i < this._numMeshes; i++) {
  62267. if (this._impostors[i] == impostor) {
  62268. this._scene.removeMesh(this._meshes[i]);
  62269. this._meshes[i].dispose();
  62270. this._numMeshes--;
  62271. if (this._numMeshes > 0) {
  62272. this._meshes[i] = this._meshes[this._numMeshes];
  62273. this._impostors[i] = this._impostors[this._numMeshes];
  62274. this._meshes[this._numMeshes] = null;
  62275. this._impostors[this._numMeshes] = null;
  62276. }
  62277. else {
  62278. this._meshes[0] = null;
  62279. this._impostors[0] = null;
  62280. }
  62281. removed = true;
  62282. break;
  62283. }
  62284. }
  62285. if (removed && this._numMeshes === 0) {
  62286. this._scene.unregisterBeforeRender(this._renderFunction);
  62287. }
  62288. };
  62289. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  62290. if (!this._debugMaterial) {
  62291. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  62292. this._debugMaterial.wireframe = true;
  62293. }
  62294. return this._debugMaterial;
  62295. };
  62296. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  62297. if (!this._debugBoxMesh) {
  62298. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  62299. this._debugBoxMesh.renderingGroupId = 1;
  62300. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  62301. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  62302. scene.removeMesh(this._debugBoxMesh);
  62303. }
  62304. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  62305. };
  62306. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  62307. if (!this._debugSphereMesh) {
  62308. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  62309. this._debugSphereMesh.renderingGroupId = 1;
  62310. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  62311. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  62312. scene.removeMesh(this._debugSphereMesh);
  62313. }
  62314. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  62315. };
  62316. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  62317. var body = impostor.physicsBody;
  62318. var shape = body.shapes[0];
  62319. var mesh;
  62320. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  62321. mesh = this._getDebugBoxMesh(scene);
  62322. impostor.getBoxSizeToRef(mesh.scaling);
  62323. }
  62324. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  62325. mesh = this._getDebugSphereMesh(scene);
  62326. var radius = impostor.getRadius();
  62327. mesh.scaling.x = radius * 2;
  62328. mesh.scaling.y = radius * 2;
  62329. mesh.scaling.z = radius * 2;
  62330. }
  62331. return mesh;
  62332. };
  62333. PhysicsViewer.prototype.dispose = function () {
  62334. for (var i = 0; i < this._numMeshes; i++) {
  62335. this.hideImpostor(this._impostors[i]);
  62336. }
  62337. if (this._debugBoxMesh) {
  62338. this._debugBoxMesh.dispose();
  62339. }
  62340. if (this._debugSphereMesh) {
  62341. this._debugSphereMesh.dispose();
  62342. }
  62343. if (this._debugMaterial) {
  62344. this._debugMaterial.dispose();
  62345. }
  62346. this._impostors.length = 0;
  62347. this._scene = null;
  62348. this._physicsEnginePlugin = null;
  62349. };
  62350. return PhysicsViewer;
  62351. }());
  62352. Debug.PhysicsViewer = PhysicsViewer;
  62353. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62354. })(BABYLON || (BABYLON = {}));
  62355. //# sourceMappingURL=babylon.physicsViewer.js.map
  62356. var BABYLON;
  62357. (function (BABYLON) {
  62358. var BoundingBoxRenderer = (function () {
  62359. function BoundingBoxRenderer(scene) {
  62360. this.frontColor = new BABYLON.Color3(1, 1, 1);
  62361. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  62362. this.showBackLines = true;
  62363. this.renderList = new BABYLON.SmartArray(32);
  62364. this._vertexBuffers = {};
  62365. this._scene = scene;
  62366. }
  62367. BoundingBoxRenderer.prototype._prepareRessources = function () {
  62368. if (this._colorShader) {
  62369. return;
  62370. }
  62371. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  62372. attributes: [BABYLON.VertexBuffer.PositionKind],
  62373. uniforms: ["world", "viewProjection", "color"]
  62374. });
  62375. var engine = this._scene.getEngine();
  62376. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  62377. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  62378. 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]);
  62379. };
  62380. BoundingBoxRenderer.prototype.reset = function () {
  62381. this.renderList.reset();
  62382. };
  62383. BoundingBoxRenderer.prototype.render = function () {
  62384. if (this.renderList.length === 0) {
  62385. return;
  62386. }
  62387. this._prepareRessources();
  62388. if (!this._colorShader.isReady()) {
  62389. return;
  62390. }
  62391. var engine = this._scene.getEngine();
  62392. engine.setDepthWrite(false);
  62393. this._colorShader._preBind();
  62394. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  62395. var boundingBox = this.renderList.data[boundingBoxIndex];
  62396. var min = boundingBox.minimum;
  62397. var max = boundingBox.maximum;
  62398. var diff = max.subtract(min);
  62399. var median = min.add(diff.scale(0.5));
  62400. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  62401. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  62402. .multiply(boundingBox.getWorldMatrix());
  62403. // VBOs
  62404. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  62405. if (this.showBackLines) {
  62406. // Back
  62407. engine.setDepthFunctionToGreaterOrEqual();
  62408. this._scene.resetCachedMaterial();
  62409. this._colorShader.setColor4("color", this.backColor.toColor4());
  62410. this._colorShader.bind(worldMatrix);
  62411. // Draw order
  62412. engine.draw(false, 0, 24);
  62413. }
  62414. // Front
  62415. engine.setDepthFunctionToLess();
  62416. this._scene.resetCachedMaterial();
  62417. this._colorShader.setColor4("color", this.frontColor.toColor4());
  62418. this._colorShader.bind(worldMatrix);
  62419. // Draw order
  62420. engine.draw(false, 0, 24);
  62421. }
  62422. this._colorShader.unbind();
  62423. engine.setDepthFunctionToLessOrEqual();
  62424. engine.setDepthWrite(true);
  62425. };
  62426. BoundingBoxRenderer.prototype.dispose = function () {
  62427. if (!this._colorShader) {
  62428. return;
  62429. }
  62430. this.renderList.dispose();
  62431. this._colorShader.dispose();
  62432. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  62433. if (buffer) {
  62434. buffer.dispose();
  62435. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  62436. }
  62437. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  62438. };
  62439. return BoundingBoxRenderer;
  62440. }());
  62441. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  62442. })(BABYLON || (BABYLON = {}));
  62443. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  62444. var BABYLON;
  62445. (function (BABYLON) {
  62446. var MorphTarget = (function () {
  62447. function MorphTarget(name, influence) {
  62448. if (influence === void 0) { influence = 0; }
  62449. this.name = name;
  62450. this.animations = new Array();
  62451. this.onInfluenceChanged = new BABYLON.Observable();
  62452. this.influence = influence;
  62453. }
  62454. Object.defineProperty(MorphTarget.prototype, "influence", {
  62455. get: function () {
  62456. return this._influence;
  62457. },
  62458. set: function (influence) {
  62459. if (this._influence === influence) {
  62460. return;
  62461. }
  62462. var previous = this._influence;
  62463. this._influence = influence;
  62464. if (this.onInfluenceChanged.hasObservers) {
  62465. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  62466. }
  62467. },
  62468. enumerable: true,
  62469. configurable: true
  62470. });
  62471. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  62472. get: function () {
  62473. return this._normals !== undefined;
  62474. },
  62475. enumerable: true,
  62476. configurable: true
  62477. });
  62478. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  62479. get: function () {
  62480. return this._tangents !== undefined;
  62481. },
  62482. enumerable: true,
  62483. configurable: true
  62484. });
  62485. MorphTarget.prototype.setPositions = function (data) {
  62486. this._positions = new Float32Array(data);
  62487. };
  62488. MorphTarget.prototype.getPositions = function () {
  62489. return this._positions;
  62490. };
  62491. MorphTarget.prototype.setNormals = function (data) {
  62492. this._normals = new Float32Array(data);
  62493. };
  62494. MorphTarget.prototype.getNormals = function () {
  62495. return this._normals;
  62496. };
  62497. MorphTarget.prototype.setTangents = function (data) {
  62498. this._tangents = new Float32Array(data);
  62499. };
  62500. MorphTarget.prototype.getTangents = function () {
  62501. return this._tangents;
  62502. };
  62503. /**
  62504. * Serializes the current target into a Serialization object.
  62505. * Returns the serialized object.
  62506. */
  62507. MorphTarget.prototype.serialize = function () {
  62508. var serializationObject = {};
  62509. serializationObject.name = this.name;
  62510. serializationObject.influence = this.influence;
  62511. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  62512. if (this.hasNormals) {
  62513. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  62514. }
  62515. if (this.hasTangents) {
  62516. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  62517. }
  62518. return serializationObject;
  62519. };
  62520. // Statics
  62521. MorphTarget.Parse = function (serializationObject) {
  62522. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  62523. result.setPositions(serializationObject.positions);
  62524. if (serializationObject.normals) {
  62525. result.setNormals(serializationObject.normals);
  62526. }
  62527. if (serializationObject.tangents) {
  62528. result.setTangents(serializationObject.tangents);
  62529. }
  62530. return result;
  62531. };
  62532. MorphTarget.FromMesh = function (mesh, name, influence) {
  62533. if (!name) {
  62534. name = mesh.name;
  62535. }
  62536. var result = new MorphTarget(name, influence);
  62537. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  62538. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  62539. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  62540. }
  62541. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  62542. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  62543. }
  62544. return result;
  62545. };
  62546. return MorphTarget;
  62547. }());
  62548. BABYLON.MorphTarget = MorphTarget;
  62549. })(BABYLON || (BABYLON = {}));
  62550. //# sourceMappingURL=babylon.morphTarget.js.map
  62551. var BABYLON;
  62552. (function (BABYLON) {
  62553. var MorphTargetManager = (function () {
  62554. function MorphTargetManager(scene) {
  62555. this._targets = new Array();
  62556. this._targetObservable = new Array();
  62557. this._activeTargets = new BABYLON.SmartArray(16);
  62558. this._supportsNormals = false;
  62559. this._supportsTangents = false;
  62560. this._vertexCount = 0;
  62561. this._uniqueId = 0;
  62562. this._tempInfluences = new Array();
  62563. if (!scene) {
  62564. scene = BABYLON.Engine.LastCreatedScene;
  62565. }
  62566. this._scene = scene;
  62567. this._scene.morphTargetManagers.push(this);
  62568. this._uniqueId = scene.getUniqueId();
  62569. }
  62570. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  62571. get: function () {
  62572. return this._uniqueId;
  62573. },
  62574. enumerable: true,
  62575. configurable: true
  62576. });
  62577. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  62578. get: function () {
  62579. return this._vertexCount;
  62580. },
  62581. enumerable: true,
  62582. configurable: true
  62583. });
  62584. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  62585. get: function () {
  62586. return this._supportsNormals;
  62587. },
  62588. enumerable: true,
  62589. configurable: true
  62590. });
  62591. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  62592. get: function () {
  62593. return this._supportsTangents;
  62594. },
  62595. enumerable: true,
  62596. configurable: true
  62597. });
  62598. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  62599. get: function () {
  62600. return this._targets.length;
  62601. },
  62602. enumerable: true,
  62603. configurable: true
  62604. });
  62605. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  62606. get: function () {
  62607. return this._activeTargets.length;
  62608. },
  62609. enumerable: true,
  62610. configurable: true
  62611. });
  62612. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  62613. get: function () {
  62614. return this._influences;
  62615. },
  62616. enumerable: true,
  62617. configurable: true
  62618. });
  62619. MorphTargetManager.prototype.getActiveTarget = function (index) {
  62620. return this._activeTargets.data[index];
  62621. };
  62622. MorphTargetManager.prototype.getTarget = function (index) {
  62623. return this._targets[index];
  62624. };
  62625. MorphTargetManager.prototype.addTarget = function (target) {
  62626. var _this = this;
  62627. if (this._vertexCount) {
  62628. if (this._vertexCount !== target.getPositions().length / 3) {
  62629. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  62630. return;
  62631. }
  62632. }
  62633. this._targets.push(target);
  62634. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  62635. _this._syncActiveTargets(needUpdate);
  62636. }));
  62637. this._syncActiveTargets(true);
  62638. };
  62639. MorphTargetManager.prototype.removeTarget = function (target) {
  62640. var index = this._targets.indexOf(target);
  62641. if (index >= 0) {
  62642. this._targets.splice(index, 1);
  62643. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  62644. this._vertexCount = 0;
  62645. this._syncActiveTargets(true);
  62646. }
  62647. };
  62648. /**
  62649. * Serializes the current manager into a Serialization object.
  62650. * Returns the serialized object.
  62651. */
  62652. MorphTargetManager.prototype.serialize = function () {
  62653. var serializationObject = {};
  62654. serializationObject.id = this.uniqueId;
  62655. serializationObject.targets = [];
  62656. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  62657. var target = _a[_i];
  62658. serializationObject.targets.push(target.serialize());
  62659. }
  62660. return serializationObject;
  62661. };
  62662. MorphTargetManager.prototype._onInfluenceChanged = function (needUpdate) {
  62663. this._syncActiveTargets(needUpdate);
  62664. };
  62665. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  62666. var influenceCount = 0;
  62667. this._activeTargets.reset();
  62668. this._supportsNormals = true;
  62669. this._supportsTangents = true;
  62670. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  62671. var target = _a[_i];
  62672. if (target.influence > 0) {
  62673. this._activeTargets.push(target);
  62674. this._tempInfluences[influenceCount++] = target.influence;
  62675. this._supportsNormals = this._supportsNormals && target.hasNormals;
  62676. this._supportsTangents = this._supportsTangents && target.hasTangents;
  62677. if (this._vertexCount === 0) {
  62678. this._vertexCount = target.getPositions().length / 3;
  62679. }
  62680. }
  62681. }
  62682. if (!this._influences || this._influences.length !== influenceCount) {
  62683. this._influences = new Float32Array(influenceCount);
  62684. }
  62685. for (var index = 0; index < influenceCount; index++) {
  62686. this._influences[index] = this._tempInfluences[index];
  62687. }
  62688. if (needUpdate) {
  62689. // Flag meshes as dirty to resync with the active targets
  62690. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  62691. var mesh = _c[_b];
  62692. if (mesh.morphTargetManager === this) {
  62693. mesh._syncGeometryWithMorphTargetManager();
  62694. }
  62695. }
  62696. }
  62697. };
  62698. // Statics
  62699. MorphTargetManager.Parse = function (serializationObject, scene) {
  62700. var result = new MorphTargetManager(scene);
  62701. result._uniqueId = serializationObject.id;
  62702. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  62703. var targetData = _a[_i];
  62704. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  62705. }
  62706. return result;
  62707. };
  62708. return MorphTargetManager;
  62709. }());
  62710. BABYLON.MorphTargetManager = MorphTargetManager;
  62711. })(BABYLON || (BABYLON = {}));
  62712. //# sourceMappingURL=babylon.morphTargetManager.js.map
  62713. var BABYLON;
  62714. (function (BABYLON) {
  62715. /**
  62716. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  62717. * It can help converting any input color in a desired output one. This can then be used to create effects
  62718. * from sepia, black and white to sixties or futuristic rendering...
  62719. *
  62720. * The only supported format is currently 3dl.
  62721. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  62722. */
  62723. var ColorGradingTexture = (function (_super) {
  62724. __extends(ColorGradingTexture, _super);
  62725. /**
  62726. * Instantiates a ColorGradingTexture from the following parameters.
  62727. *
  62728. * @param url The location of the color gradind data (currently only supporting 3dl)
  62729. * @param scene The scene the texture will be used in
  62730. */
  62731. function ColorGradingTexture(url, scene) {
  62732. var _this = _super.call(this, scene) || this;
  62733. if (!url) {
  62734. return _this;
  62735. }
  62736. _this._textureMatrix = BABYLON.Matrix.Identity();
  62737. _this.name = url;
  62738. _this.url = url;
  62739. _this.hasAlpha = false;
  62740. _this.isCube = false;
  62741. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62742. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62743. _this.anisotropicFilteringLevel = 1;
  62744. _this._texture = _this._getFromCache(url, true);
  62745. if (!_this._texture) {
  62746. if (!scene.useDelayedTextureLoading) {
  62747. _this.loadTexture();
  62748. }
  62749. else {
  62750. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  62751. }
  62752. }
  62753. return _this;
  62754. }
  62755. /**
  62756. * Returns the texture matrix used in most of the material.
  62757. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  62758. */
  62759. ColorGradingTexture.prototype.getTextureMatrix = function () {
  62760. return this._textureMatrix;
  62761. };
  62762. /**
  62763. * Occurs when the file being loaded is a .3dl LUT file.
  62764. */
  62765. ColorGradingTexture.prototype.load3dlTexture = function () {
  62766. var _this = this;
  62767. var mipLevels = 0;
  62768. var floatArrayView = null;
  62769. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  62770. this._texture = texture;
  62771. var callback = function (text) {
  62772. var data;
  62773. var tempData;
  62774. var line;
  62775. var lines = text.split('\n');
  62776. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  62777. var maxColor = 0;
  62778. for (var i = 0; i < lines.length; i++) {
  62779. line = lines[i];
  62780. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  62781. continue;
  62782. if (line.indexOf('#') === 0)
  62783. continue;
  62784. var words = line.split(" ");
  62785. if (size === 0) {
  62786. // Number of space + one
  62787. size = words.length;
  62788. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  62789. tempData = new Float32Array(size * size * size * 4);
  62790. continue;
  62791. }
  62792. if (size != 0) {
  62793. var r = Math.max(parseInt(words[0]), 0);
  62794. var g = Math.max(parseInt(words[1]), 0);
  62795. var b = Math.max(parseInt(words[2]), 0);
  62796. maxColor = Math.max(r, maxColor);
  62797. maxColor = Math.max(g, maxColor);
  62798. maxColor = Math.max(b, maxColor);
  62799. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  62800. tempData[pixelStorageIndex + 0] = r;
  62801. tempData[pixelStorageIndex + 1] = g;
  62802. tempData[pixelStorageIndex + 2] = b;
  62803. pixelIndexSlice++;
  62804. if (pixelIndexSlice % size == 0) {
  62805. pixelIndexH++;
  62806. pixelIndexSlice = 0;
  62807. if (pixelIndexH % size == 0) {
  62808. pixelIndexW++;
  62809. pixelIndexH = 0;
  62810. }
  62811. }
  62812. }
  62813. }
  62814. for (var i = 0; i < tempData.length; i++) {
  62815. if (i > 0 && (i + 1) % 4 === 0) {
  62816. data[i] = 255;
  62817. }
  62818. else {
  62819. var value = tempData[i];
  62820. data[i] = (value / maxColor * 255);
  62821. }
  62822. }
  62823. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  62824. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  62825. };
  62826. BABYLON.Tools.LoadFile(this.url, callback);
  62827. return this._texture;
  62828. };
  62829. /**
  62830. * Starts the loading process of the texture.
  62831. */
  62832. ColorGradingTexture.prototype.loadTexture = function () {
  62833. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  62834. this.load3dlTexture();
  62835. }
  62836. };
  62837. /**
  62838. * Clones the color gradind texture.
  62839. */
  62840. ColorGradingTexture.prototype.clone = function () {
  62841. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  62842. // Base texture
  62843. newTexture.level = this.level;
  62844. return newTexture;
  62845. };
  62846. /**
  62847. * Called during delayed load for textures.
  62848. */
  62849. ColorGradingTexture.prototype.delayLoad = function () {
  62850. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  62851. return;
  62852. }
  62853. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  62854. this._texture = this._getFromCache(this.url, true);
  62855. if (!this._texture) {
  62856. this.loadTexture();
  62857. }
  62858. };
  62859. /**
  62860. * Parses a color grading texture serialized by Babylon.
  62861. * @param parsedTexture The texture information being parsedTexture
  62862. * @param scene The scene to load the texture in
  62863. * @param rootUrl The root url of the data assets to load
  62864. * @return A color gradind texture
  62865. */
  62866. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  62867. var texture = null;
  62868. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  62869. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  62870. texture.name = parsedTexture.name;
  62871. texture.level = parsedTexture.level;
  62872. }
  62873. return texture;
  62874. };
  62875. /**
  62876. * Serializes the LUT texture to json format.
  62877. */
  62878. ColorGradingTexture.prototype.serialize = function () {
  62879. if (!this.name) {
  62880. return null;
  62881. }
  62882. var serializationObject = {};
  62883. serializationObject.name = this.name;
  62884. serializationObject.level = this.level;
  62885. serializationObject.customType = "BABYLON.ColorGradingTexture";
  62886. return serializationObject;
  62887. };
  62888. return ColorGradingTexture;
  62889. }(BABYLON.BaseTexture));
  62890. /**
  62891. * Empty line regex stored for GC.
  62892. */
  62893. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  62894. BABYLON.ColorGradingTexture = ColorGradingTexture;
  62895. })(BABYLON || (BABYLON = {}));
  62896. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  62897. var BABYLON;
  62898. (function (BABYLON) {
  62899. /**
  62900. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  62901. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  62902. * 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;
  62903. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  62904. */
  62905. var ColorCurves = (function () {
  62906. function ColorCurves() {
  62907. this._dirty = true;
  62908. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  62909. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  62910. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  62911. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  62912. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  62913. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  62914. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  62915. this._globalHue = 30;
  62916. this._globalDensity = 0;
  62917. this._globalSaturation = 0;
  62918. this._globalExposure = 0;
  62919. this._highlightsHue = 30;
  62920. this._highlightsDensity = 0;
  62921. this._highlightsSaturation = 0;
  62922. this._highlightsExposure = 0;
  62923. this._midtonesHue = 30;
  62924. this._midtonesDensity = 0;
  62925. this._midtonesSaturation = 0;
  62926. this._midtonesExposure = 0;
  62927. this._shadowsHue = 30;
  62928. this._shadowsDensity = 0;
  62929. this._shadowsSaturation = 0;
  62930. this._shadowsExposure = 0;
  62931. }
  62932. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  62933. /**
  62934. * Gets the global Hue value.
  62935. * 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).
  62936. */
  62937. get: function () {
  62938. return this._globalHue;
  62939. },
  62940. /**
  62941. * Sets the global Hue value.
  62942. * 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).
  62943. */
  62944. set: function (value) {
  62945. this._globalHue = value;
  62946. this._dirty = true;
  62947. },
  62948. enumerable: true,
  62949. configurable: true
  62950. });
  62951. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  62952. /**
  62953. * Gets the global Density value.
  62954. * 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.
  62955. * Values less than zero provide a filter of opposite hue.
  62956. */
  62957. get: function () {
  62958. return this._globalDensity;
  62959. },
  62960. /**
  62961. * Sets the global Density value.
  62962. * 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.
  62963. * Values less than zero provide a filter of opposite hue.
  62964. */
  62965. set: function (value) {
  62966. this._globalDensity = value;
  62967. this._dirty = true;
  62968. },
  62969. enumerable: true,
  62970. configurable: true
  62971. });
  62972. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  62973. /**
  62974. * Gets the global Saturation value.
  62975. * 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.
  62976. */
  62977. get: function () {
  62978. return this._globalSaturation;
  62979. },
  62980. /**
  62981. * Sets the global Saturation value.
  62982. * 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.
  62983. */
  62984. set: function (value) {
  62985. this._globalSaturation = value;
  62986. this._dirty = true;
  62987. },
  62988. enumerable: true,
  62989. configurable: true
  62990. });
  62991. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  62992. /**
  62993. * Gets the highlights Hue value.
  62994. * 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).
  62995. */
  62996. get: function () {
  62997. return this._highlightsHue;
  62998. },
  62999. /**
  63000. * Sets the highlights Hue value.
  63001. * 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).
  63002. */
  63003. set: function (value) {
  63004. this._highlightsHue = value;
  63005. this._dirty = true;
  63006. },
  63007. enumerable: true,
  63008. configurable: true
  63009. });
  63010. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  63011. /**
  63012. * Gets the highlights Density value.
  63013. * 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.
  63014. * Values less than zero provide a filter of opposite hue.
  63015. */
  63016. get: function () {
  63017. return this._highlightsDensity;
  63018. },
  63019. /**
  63020. * Sets the highlights Density value.
  63021. * 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.
  63022. * Values less than zero provide a filter of opposite hue.
  63023. */
  63024. set: function (value) {
  63025. this._highlightsDensity = value;
  63026. this._dirty = true;
  63027. },
  63028. enumerable: true,
  63029. configurable: true
  63030. });
  63031. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  63032. /**
  63033. * Gets the highlights Saturation value.
  63034. * 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.
  63035. */
  63036. get: function () {
  63037. return this._highlightsSaturation;
  63038. },
  63039. /**
  63040. * Sets the highlights Saturation value.
  63041. * 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.
  63042. */
  63043. set: function (value) {
  63044. this._highlightsSaturation = value;
  63045. this._dirty = true;
  63046. },
  63047. enumerable: true,
  63048. configurable: true
  63049. });
  63050. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  63051. /**
  63052. * Gets the highlights Exposure value.
  63053. * 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.
  63054. */
  63055. get: function () {
  63056. return this._highlightsExposure;
  63057. },
  63058. /**
  63059. * Sets the highlights Exposure value.
  63060. * 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.
  63061. */
  63062. set: function (value) {
  63063. this._highlightsExposure = value;
  63064. this._dirty = true;
  63065. },
  63066. enumerable: true,
  63067. configurable: true
  63068. });
  63069. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  63070. /**
  63071. * Gets the midtones Hue value.
  63072. * 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).
  63073. */
  63074. get: function () {
  63075. return this._midtonesHue;
  63076. },
  63077. /**
  63078. * Sets the midtones Hue value.
  63079. * 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).
  63080. */
  63081. set: function (value) {
  63082. this._midtonesHue = value;
  63083. this._dirty = true;
  63084. },
  63085. enumerable: true,
  63086. configurable: true
  63087. });
  63088. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  63089. /**
  63090. * Gets the midtones Density value.
  63091. * 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.
  63092. * Values less than zero provide a filter of opposite hue.
  63093. */
  63094. get: function () {
  63095. return this._midtonesDensity;
  63096. },
  63097. /**
  63098. * Sets the midtones Density value.
  63099. * 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.
  63100. * Values less than zero provide a filter of opposite hue.
  63101. */
  63102. set: function (value) {
  63103. this._midtonesDensity = value;
  63104. this._dirty = true;
  63105. },
  63106. enumerable: true,
  63107. configurable: true
  63108. });
  63109. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  63110. /**
  63111. * Gets the midtones Saturation value.
  63112. * 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.
  63113. */
  63114. get: function () {
  63115. return this._midtonesSaturation;
  63116. },
  63117. /**
  63118. * Sets the midtones Saturation value.
  63119. * 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.
  63120. */
  63121. set: function (value) {
  63122. this._midtonesSaturation = value;
  63123. this._dirty = true;
  63124. },
  63125. enumerable: true,
  63126. configurable: true
  63127. });
  63128. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  63129. /**
  63130. * Gets the midtones Exposure value.
  63131. * 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.
  63132. */
  63133. get: function () {
  63134. return this._midtonesExposure;
  63135. },
  63136. /**
  63137. * Sets the midtones Exposure value.
  63138. * 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.
  63139. */
  63140. set: function (value) {
  63141. this._midtonesExposure = value;
  63142. this._dirty = true;
  63143. },
  63144. enumerable: true,
  63145. configurable: true
  63146. });
  63147. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  63148. /**
  63149. * Gets the shadows Hue value.
  63150. * 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).
  63151. */
  63152. get: function () {
  63153. return this._shadowsHue;
  63154. },
  63155. /**
  63156. * Sets the shadows Hue value.
  63157. * 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).
  63158. */
  63159. set: function (value) {
  63160. this._shadowsHue = value;
  63161. this._dirty = true;
  63162. },
  63163. enumerable: true,
  63164. configurable: true
  63165. });
  63166. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  63167. /**
  63168. * Gets the shadows Density value.
  63169. * 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.
  63170. * Values less than zero provide a filter of opposite hue.
  63171. */
  63172. get: function () {
  63173. return this._shadowsDensity;
  63174. },
  63175. /**
  63176. * Sets the shadows Density value.
  63177. * 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.
  63178. * Values less than zero provide a filter of opposite hue.
  63179. */
  63180. set: function (value) {
  63181. this._shadowsDensity = value;
  63182. this._dirty = true;
  63183. },
  63184. enumerable: true,
  63185. configurable: true
  63186. });
  63187. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  63188. /**
  63189. * Gets the shadows Saturation value.
  63190. * 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.
  63191. */
  63192. get: function () {
  63193. return this._shadowsSaturation;
  63194. },
  63195. /**
  63196. * Sets the shadows Saturation value.
  63197. * 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.
  63198. */
  63199. set: function (value) {
  63200. this._shadowsSaturation = value;
  63201. this._dirty = true;
  63202. },
  63203. enumerable: true,
  63204. configurable: true
  63205. });
  63206. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  63207. /**
  63208. * Gets the shadows Exposure value.
  63209. * 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.
  63210. */
  63211. get: function () {
  63212. return this._shadowsExposure;
  63213. },
  63214. /**
  63215. * Sets the shadows Exposure value.
  63216. * 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.
  63217. */
  63218. set: function (value) {
  63219. this._shadowsExposure = value;
  63220. this._dirty = true;
  63221. },
  63222. enumerable: true,
  63223. configurable: true
  63224. });
  63225. ColorCurves.prototype.getClassName = function () {
  63226. return "ColorCurves";
  63227. };
  63228. /**
  63229. * Binds the color curves to the shader.
  63230. * @param colorCurves The color curve to bind
  63231. * @param effect The effect to bind to
  63232. */
  63233. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  63234. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  63235. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  63236. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  63237. if (colorCurves._dirty) {
  63238. colorCurves._dirty = false;
  63239. // Fill in global info.
  63240. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  63241. // Compute highlights info.
  63242. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  63243. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  63244. // Compute midtones info.
  63245. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  63246. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  63247. // Compute shadows info.
  63248. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  63249. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  63250. // Compute deltas (neutral is midtones).
  63251. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  63252. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  63253. }
  63254. if (effect) {
  63255. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  63256. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  63257. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  63258. }
  63259. };
  63260. /**
  63261. * Prepare the list of uniforms associated with the ColorCurves effects.
  63262. * @param uniformsList The list of uniforms used in the effect
  63263. */
  63264. ColorCurves.PrepareUniforms = function (uniformsList) {
  63265. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  63266. };
  63267. /**
  63268. * Returns color grading data based on a hue, density, saturation and exposure value.
  63269. * @param filterHue The hue of the color filter.
  63270. * @param filterDensity The density of the color filter.
  63271. * @param saturation The saturation.
  63272. * @param exposure The exposure.
  63273. * @param result The result data container.
  63274. */
  63275. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  63276. if (hue == null) {
  63277. return;
  63278. }
  63279. hue = ColorCurves.clamp(hue, 0, 360);
  63280. density = ColorCurves.clamp(density, -100, 100);
  63281. saturation = ColorCurves.clamp(saturation, -100, 100);
  63282. exposure = ColorCurves.clamp(exposure, -100, 100);
  63283. // Remap the slider/config filter density with non-linear mapping and also scale by half
  63284. // so that the maximum filter density is only 50% control. This provides fine control
  63285. // for small values and reasonable range.
  63286. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  63287. density *= 0.5;
  63288. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  63289. if (density < 0) {
  63290. density *= -1;
  63291. hue = (hue + 180) % 360;
  63292. }
  63293. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  63294. result.scaleToRef(2, result);
  63295. result.a = 1 + 0.01 * saturation;
  63296. };
  63297. /**
  63298. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  63299. * @param value The input slider value in range [-100,100].
  63300. * @returns Adjusted value.
  63301. */
  63302. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  63303. value /= 100;
  63304. var x = Math.abs(value);
  63305. x = Math.pow(x, 2);
  63306. if (value < 0) {
  63307. x *= -1;
  63308. }
  63309. x *= 100;
  63310. return x;
  63311. };
  63312. /**
  63313. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  63314. * @param hue The hue (H) input.
  63315. * @param saturation The saturation (S) input.
  63316. * @param brightness The brightness (B) input.
  63317. * @result An RGBA color represented as Vector4.
  63318. */
  63319. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  63320. var h = ColorCurves.clamp(hue, 0, 360);
  63321. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  63322. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  63323. if (s === 0) {
  63324. result.r = v;
  63325. result.g = v;
  63326. result.b = v;
  63327. }
  63328. else {
  63329. // sector 0 to 5
  63330. h /= 60;
  63331. var i = Math.floor(h);
  63332. // fractional part of h
  63333. var f = h - i;
  63334. var p = v * (1 - s);
  63335. var q = v * (1 - s * f);
  63336. var t = v * (1 - s * (1 - f));
  63337. switch (i) {
  63338. case 0:
  63339. result.r = v;
  63340. result.g = t;
  63341. result.b = p;
  63342. break;
  63343. case 1:
  63344. result.r = q;
  63345. result.g = v;
  63346. result.b = p;
  63347. break;
  63348. case 2:
  63349. result.r = p;
  63350. result.g = v;
  63351. result.b = t;
  63352. break;
  63353. case 3:
  63354. result.r = p;
  63355. result.g = q;
  63356. result.b = v;
  63357. break;
  63358. case 4:
  63359. result.r = t;
  63360. result.g = p;
  63361. result.b = v;
  63362. break;
  63363. default:
  63364. result.r = v;
  63365. result.g = p;
  63366. result.b = q;
  63367. break;
  63368. }
  63369. }
  63370. result.a = 1;
  63371. };
  63372. /**
  63373. * Returns a value clamped between min and max
  63374. * @param value The value to clamp
  63375. * @param min The minimum of value
  63376. * @param max The maximum of value
  63377. * @returns The clamped value.
  63378. */
  63379. ColorCurves.clamp = function (value, min, max) {
  63380. return Math.min(Math.max(value, min), max);
  63381. };
  63382. /**
  63383. * Clones the current color curve instance.
  63384. * @return The cloned curves
  63385. */
  63386. ColorCurves.prototype.clone = function () {
  63387. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  63388. };
  63389. /**
  63390. * Serializes the current color curve instance to a json representation.
  63391. * @return a JSON representation
  63392. */
  63393. ColorCurves.prototype.serialize = function () {
  63394. return BABYLON.SerializationHelper.Serialize(this);
  63395. };
  63396. /**
  63397. * Parses the color curve from a json representation.
  63398. * @param source the JSON source to parse
  63399. * @return The parsed curves
  63400. */
  63401. ColorCurves.Parse = function (source) {
  63402. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  63403. };
  63404. return ColorCurves;
  63405. }());
  63406. __decorate([
  63407. BABYLON.serialize()
  63408. ], ColorCurves.prototype, "_globalHue", void 0);
  63409. __decorate([
  63410. BABYLON.serialize()
  63411. ], ColorCurves.prototype, "_globalDensity", void 0);
  63412. __decorate([
  63413. BABYLON.serialize()
  63414. ], ColorCurves.prototype, "_globalSaturation", void 0);
  63415. __decorate([
  63416. BABYLON.serialize()
  63417. ], ColorCurves.prototype, "_globalExposure", void 0);
  63418. __decorate([
  63419. BABYLON.serialize()
  63420. ], ColorCurves.prototype, "_highlightsHue", void 0);
  63421. __decorate([
  63422. BABYLON.serialize()
  63423. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  63424. __decorate([
  63425. BABYLON.serialize()
  63426. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  63427. __decorate([
  63428. BABYLON.serialize()
  63429. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  63430. __decorate([
  63431. BABYLON.serialize()
  63432. ], ColorCurves.prototype, "_midtonesHue", void 0);
  63433. __decorate([
  63434. BABYLON.serialize()
  63435. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  63436. __decorate([
  63437. BABYLON.serialize()
  63438. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  63439. __decorate([
  63440. BABYLON.serialize()
  63441. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  63442. BABYLON.ColorCurves = ColorCurves;
  63443. })(BABYLON || (BABYLON = {}));
  63444. //# sourceMappingURL=babylon.colorCurves.js.map
  63445. var BABYLON;
  63446. (function (BABYLON) {
  63447. var Octree = (function () {
  63448. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  63449. if (maxDepth === void 0) { maxDepth = 2; }
  63450. this.maxDepth = maxDepth;
  63451. this.dynamicContent = new Array();
  63452. this._maxBlockCapacity = maxBlockCapacity || 64;
  63453. this._selectionContent = new BABYLON.SmartArray(1024);
  63454. this._creationFunc = creationFunc;
  63455. }
  63456. // Methods
  63457. Octree.prototype.update = function (worldMin, worldMax, entries) {
  63458. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  63459. };
  63460. Octree.prototype.addMesh = function (entry) {
  63461. for (var index = 0; index < this.blocks.length; index++) {
  63462. var block = this.blocks[index];
  63463. block.addEntry(entry);
  63464. }
  63465. };
  63466. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  63467. this._selectionContent.reset();
  63468. for (var index = 0; index < this.blocks.length; index++) {
  63469. var block = this.blocks[index];
  63470. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  63471. }
  63472. if (allowDuplicate) {
  63473. this._selectionContent.concat(this.dynamicContent);
  63474. }
  63475. else {
  63476. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  63477. }
  63478. return this._selectionContent;
  63479. };
  63480. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  63481. this._selectionContent.reset();
  63482. for (var index = 0; index < this.blocks.length; index++) {
  63483. var block = this.blocks[index];
  63484. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  63485. }
  63486. if (allowDuplicate) {
  63487. this._selectionContent.concat(this.dynamicContent);
  63488. }
  63489. else {
  63490. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  63491. }
  63492. return this._selectionContent;
  63493. };
  63494. Octree.prototype.intersectsRay = function (ray) {
  63495. this._selectionContent.reset();
  63496. for (var index = 0; index < this.blocks.length; index++) {
  63497. var block = this.blocks[index];
  63498. block.intersectsRay(ray, this._selectionContent);
  63499. }
  63500. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  63501. return this._selectionContent;
  63502. };
  63503. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  63504. target.blocks = new Array();
  63505. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  63506. // Segmenting space
  63507. for (var x = 0; x < 2; x++) {
  63508. for (var y = 0; y < 2; y++) {
  63509. for (var z = 0; z < 2; z++) {
  63510. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  63511. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  63512. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  63513. block.addEntries(entries);
  63514. target.blocks.push(block);
  63515. }
  63516. }
  63517. }
  63518. };
  63519. return Octree;
  63520. }());
  63521. Octree.CreationFuncForMeshes = function (entry, block) {
  63522. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  63523. block.entries.push(entry);
  63524. }
  63525. };
  63526. Octree.CreationFuncForSubMeshes = function (entry, block) {
  63527. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  63528. block.entries.push(entry);
  63529. }
  63530. };
  63531. BABYLON.Octree = Octree;
  63532. })(BABYLON || (BABYLON = {}));
  63533. //# sourceMappingURL=babylon.octree.js.map
  63534. var BABYLON;
  63535. (function (BABYLON) {
  63536. var OctreeBlock = (function () {
  63537. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  63538. this.entries = new Array();
  63539. this._boundingVectors = new Array();
  63540. this._capacity = capacity;
  63541. this._depth = depth;
  63542. this._maxDepth = maxDepth;
  63543. this._creationFunc = creationFunc;
  63544. this._minPoint = minPoint;
  63545. this._maxPoint = maxPoint;
  63546. this._boundingVectors.push(minPoint.clone());
  63547. this._boundingVectors.push(maxPoint.clone());
  63548. this._boundingVectors.push(minPoint.clone());
  63549. this._boundingVectors[2].x = maxPoint.x;
  63550. this._boundingVectors.push(minPoint.clone());
  63551. this._boundingVectors[3].y = maxPoint.y;
  63552. this._boundingVectors.push(minPoint.clone());
  63553. this._boundingVectors[4].z = maxPoint.z;
  63554. this._boundingVectors.push(maxPoint.clone());
  63555. this._boundingVectors[5].z = minPoint.z;
  63556. this._boundingVectors.push(maxPoint.clone());
  63557. this._boundingVectors[6].x = minPoint.x;
  63558. this._boundingVectors.push(maxPoint.clone());
  63559. this._boundingVectors[7].y = minPoint.y;
  63560. }
  63561. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  63562. // Property
  63563. get: function () {
  63564. return this._capacity;
  63565. },
  63566. enumerable: true,
  63567. configurable: true
  63568. });
  63569. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  63570. get: function () {
  63571. return this._minPoint;
  63572. },
  63573. enumerable: true,
  63574. configurable: true
  63575. });
  63576. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  63577. get: function () {
  63578. return this._maxPoint;
  63579. },
  63580. enumerable: true,
  63581. configurable: true
  63582. });
  63583. // Methods
  63584. OctreeBlock.prototype.addEntry = function (entry) {
  63585. if (this.blocks) {
  63586. for (var index = 0; index < this.blocks.length; index++) {
  63587. var block = this.blocks[index];
  63588. block.addEntry(entry);
  63589. }
  63590. return;
  63591. }
  63592. this._creationFunc(entry, this);
  63593. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  63594. this.createInnerBlocks();
  63595. }
  63596. };
  63597. OctreeBlock.prototype.addEntries = function (entries) {
  63598. for (var index = 0; index < entries.length; index++) {
  63599. var mesh = entries[index];
  63600. this.addEntry(mesh);
  63601. }
  63602. };
  63603. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  63604. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  63605. if (this.blocks) {
  63606. for (var index = 0; index < this.blocks.length; index++) {
  63607. var block = this.blocks[index];
  63608. block.select(frustumPlanes, selection, allowDuplicate);
  63609. }
  63610. return;
  63611. }
  63612. if (allowDuplicate) {
  63613. selection.concat(this.entries);
  63614. }
  63615. else {
  63616. selection.concatWithNoDuplicate(this.entries);
  63617. }
  63618. }
  63619. };
  63620. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  63621. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  63622. if (this.blocks) {
  63623. for (var index = 0; index < this.blocks.length; index++) {
  63624. var block = this.blocks[index];
  63625. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  63626. }
  63627. return;
  63628. }
  63629. if (allowDuplicate) {
  63630. selection.concat(this.entries);
  63631. }
  63632. else {
  63633. selection.concatWithNoDuplicate(this.entries);
  63634. }
  63635. }
  63636. };
  63637. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  63638. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  63639. if (this.blocks) {
  63640. for (var index = 0; index < this.blocks.length; index++) {
  63641. var block = this.blocks[index];
  63642. block.intersectsRay(ray, selection);
  63643. }
  63644. return;
  63645. }
  63646. selection.concatWithNoDuplicate(this.entries);
  63647. }
  63648. };
  63649. OctreeBlock.prototype.createInnerBlocks = function () {
  63650. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  63651. };
  63652. return OctreeBlock;
  63653. }());
  63654. BABYLON.OctreeBlock = OctreeBlock;
  63655. })(BABYLON || (BABYLON = {}));
  63656. //# sourceMappingURL=babylon.octreeBlock.js.map
  63657. var BABYLON;
  63658. (function (BABYLON) {
  63659. var SIMDVector3 = (function () {
  63660. function SIMDVector3() {
  63661. }
  63662. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  63663. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  63664. };
  63665. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  63666. var m = transformation.m;
  63667. var m0 = SIMD.Float32x4.load(m, 0);
  63668. var m1 = SIMD.Float32x4.load(m, 4);
  63669. var m2 = SIMD.Float32x4.load(m, 8);
  63670. var m3 = SIMD.Float32x4.load(m, 12);
  63671. 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));
  63672. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  63673. result.x = SIMD.Float32x4.extractLane(r, 0);
  63674. result.y = SIMD.Float32x4.extractLane(r, 1);
  63675. result.z = SIMD.Float32x4.extractLane(r, 2);
  63676. };
  63677. return SIMDVector3;
  63678. }());
  63679. var SIMDMatrix = (function () {
  63680. function SIMDMatrix() {
  63681. }
  63682. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  63683. var tm = this.m;
  63684. var om = other.m;
  63685. var m0 = SIMD.Float32x4.load(om, 0);
  63686. var m1 = SIMD.Float32x4.load(om, 4);
  63687. var m2 = SIMD.Float32x4.load(om, 8);
  63688. var m3 = SIMD.Float32x4.load(om, 12);
  63689. for (var i = 0; i < 16; i += 4) {
  63690. 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)))));
  63691. }
  63692. return this;
  63693. };
  63694. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  63695. var src = this.m;
  63696. var dest = other.m;
  63697. // Load the 4 rows
  63698. var src0 = SIMD.Float32x4.load(src, 0);
  63699. var src1 = SIMD.Float32x4.load(src, 4);
  63700. var src2 = SIMD.Float32x4.load(src, 8);
  63701. var src3 = SIMD.Float32x4.load(src, 12);
  63702. // Transpose the source matrix. Sort of. Not a true transpose operation
  63703. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  63704. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  63705. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  63706. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  63707. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  63708. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  63709. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  63710. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  63711. // This is a true transposition, but it will lead to an incorrect result
  63712. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  63713. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  63714. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  63715. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  63716. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  63717. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  63718. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  63719. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  63720. // ----
  63721. tmp1 = SIMD.Float32x4.mul(row2, row3);
  63722. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  63723. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  63724. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  63725. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  63726. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  63727. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  63728. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  63729. // ----
  63730. tmp1 = SIMD.Float32x4.mul(row1, row2);
  63731. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  63732. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  63733. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  63734. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  63735. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  63736. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  63737. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  63738. // ----
  63739. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  63740. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  63741. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  63742. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  63743. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  63744. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  63745. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  63746. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  63747. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  63748. // ----
  63749. tmp1 = SIMD.Float32x4.mul(row0, row1);
  63750. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  63751. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  63752. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  63753. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  63754. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  63755. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  63756. // ----
  63757. tmp1 = SIMD.Float32x4.mul(row0, row3);
  63758. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  63759. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  63760. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  63761. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  63762. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  63763. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  63764. // ----
  63765. tmp1 = SIMD.Float32x4.mul(row0, row2);
  63766. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  63767. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  63768. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  63769. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  63770. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  63771. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  63772. // Compute determinant
  63773. var det = SIMD.Float32x4.mul(row0, minor0);
  63774. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  63775. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  63776. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  63777. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  63778. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  63779. // These shuffles aren't necessary if the faulty transposition is done
  63780. // up at the top of this function.
  63781. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  63782. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  63783. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  63784. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  63785. // Compute final values by multiplying with 1/det
  63786. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  63787. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  63788. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  63789. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  63790. return this;
  63791. };
  63792. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  63793. var out = result.m;
  63794. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  63795. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  63796. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  63797. // cc.kmVec3Subtract(f, pCenter, pEye);
  63798. var f = SIMD.Float32x4.sub(center, eye);
  63799. // cc.kmVec3Normalize(f, f);
  63800. var tmp = SIMD.Float32x4.mul(f, f);
  63801. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  63802. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  63803. // cc.kmVec3Assign(up, pUp);
  63804. // cc.kmVec3Normalize(up, up);
  63805. tmp = SIMD.Float32x4.mul(up, up);
  63806. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  63807. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  63808. // cc.kmVec3Cross(s, f, up);
  63809. 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)));
  63810. // cc.kmVec3Normalize(s, s);
  63811. tmp = SIMD.Float32x4.mul(s, s);
  63812. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  63813. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  63814. // cc.kmVec3Cross(u, s, f);
  63815. 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)));
  63816. // cc.kmVec3Normalize(s, s);
  63817. tmp = SIMD.Float32x4.mul(s, s);
  63818. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  63819. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  63820. var zero = SIMD.Float32x4.splat(0.0);
  63821. s = SIMD.Float32x4.neg(s);
  63822. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  63823. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  63824. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  63825. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  63826. 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);
  63827. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  63828. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  63829. 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)))));
  63830. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  63831. 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)))));
  63832. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  63833. 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)))));
  63834. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  63835. 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)))));
  63836. };
  63837. return SIMDMatrix;
  63838. }());
  63839. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  63840. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  63841. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  63842. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  63843. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  63844. var SIMDHelper = (function () {
  63845. function SIMDHelper() {
  63846. }
  63847. Object.defineProperty(SIMDHelper, "IsEnabled", {
  63848. get: function () {
  63849. return SIMDHelper._isEnabled;
  63850. },
  63851. enumerable: true,
  63852. configurable: true
  63853. });
  63854. SIMDHelper.DisableSIMD = function () {
  63855. // Replace functions
  63856. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  63857. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  63858. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  63859. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  63860. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  63861. SIMDHelper._isEnabled = false;
  63862. };
  63863. SIMDHelper.EnableSIMD = function () {
  63864. if (self.SIMD === undefined) {
  63865. return;
  63866. }
  63867. // check if polyfills needed
  63868. if (!self.Math.fround) {
  63869. self.Math.fround = (function (array) { return function (x) {
  63870. return array[0] = x, array[0];
  63871. }; })(new Float32Array(1));
  63872. }
  63873. if (!self.Math.imul) {
  63874. self.Math.imul = function (a, b) {
  63875. var ah = (a >>> 16) & 0xffff;
  63876. var al = a & 0xffff;
  63877. var bh = (b >>> 16) & 0xffff;
  63878. var bl = b & 0xffff;
  63879. // the shift by 0 fixes the sign on the high part
  63880. // the final |0 converts the unsigned value into a signed value
  63881. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  63882. };
  63883. }
  63884. // Replace functions
  63885. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  63886. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  63887. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  63888. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  63889. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  63890. SIMDHelper._isEnabled = true;
  63891. };
  63892. return SIMDHelper;
  63893. }());
  63894. SIMDHelper._isEnabled = false;
  63895. BABYLON.SIMDHelper = SIMDHelper;
  63896. })(BABYLON || (BABYLON = {}));
  63897. //# sourceMappingURL=babylon.math.SIMD.js.map
  63898. var BABYLON;
  63899. (function (BABYLON) {
  63900. var VRDistortionCorrectionPostProcess = (function (_super) {
  63901. __extends(VRDistortionCorrectionPostProcess, _super);
  63902. //ANY
  63903. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  63904. var _this = _super.call(this, name, "vrDistortionCorrection", [
  63905. 'LensCenter',
  63906. 'Scale',
  63907. 'ScaleIn',
  63908. 'HmdWarpParam'
  63909. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  63910. _this._isRightEye = isRightEye;
  63911. _this._distortionFactors = vrMetrics.distortionK;
  63912. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  63913. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  63914. _this.onSizeChangedObservable.add(function () {
  63915. _this.aspectRatio = _this.width * .5 / _this.height;
  63916. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  63917. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  63918. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  63919. });
  63920. _this.onApplyObservable.add(function (effect) {
  63921. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  63922. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  63923. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  63924. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  63925. });
  63926. return _this;
  63927. }
  63928. return VRDistortionCorrectionPostProcess;
  63929. }(BABYLON.PostProcess));
  63930. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  63931. })(BABYLON || (BABYLON = {}));
  63932. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  63933. var BABYLON;
  63934. (function (BABYLON) {
  63935. var AnaglyphPostProcess = (function (_super) {
  63936. __extends(AnaglyphPostProcess, _super);
  63937. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  63938. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  63939. _this._passedProcess = rigCameras[0]._rigPostProcess;
  63940. _this.onApplyObservable.add(function (effect) {
  63941. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  63942. });
  63943. return _this;
  63944. }
  63945. return AnaglyphPostProcess;
  63946. }(BABYLON.PostProcess));
  63947. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  63948. })(BABYLON || (BABYLON = {}));
  63949. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  63950. var BABYLON;
  63951. (function (BABYLON) {
  63952. var StereoscopicInterlacePostProcess = (function (_super) {
  63953. __extends(StereoscopicInterlacePostProcess, _super);
  63954. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  63955. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  63956. _this._passedProcess = rigCameras[0]._rigPostProcess;
  63957. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  63958. _this.onSizeChangedObservable.add(function () {
  63959. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  63960. });
  63961. _this.onApplyObservable.add(function (effect) {
  63962. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  63963. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  63964. });
  63965. return _this;
  63966. }
  63967. return StereoscopicInterlacePostProcess;
  63968. }(BABYLON.PostProcess));
  63969. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  63970. })(BABYLON || (BABYLON = {}));
  63971. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  63972. var BABYLON;
  63973. (function (BABYLON) {
  63974. var FreeCameraDeviceOrientationInput = (function () {
  63975. function FreeCameraDeviceOrientationInput() {
  63976. var _this = this;
  63977. this._screenOrientationAngle = 0;
  63978. this._screenQuaternion = new BABYLON.Quaternion();
  63979. this._alpha = 0;
  63980. this._beta = 0;
  63981. this._gamma = 0;
  63982. this._orientationChanged = function () {
  63983. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  63984. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  63985. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  63986. };
  63987. this._deviceOrientation = function (evt) {
  63988. _this._alpha = evt.alpha;
  63989. _this._beta = evt.beta;
  63990. _this._gamma = evt.gamma;
  63991. };
  63992. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  63993. this._orientationChanged();
  63994. }
  63995. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  63996. get: function () {
  63997. return this._camera;
  63998. },
  63999. set: function (camera) {
  64000. this._camera = camera;
  64001. if (!this._camera.rotationQuaternion)
  64002. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  64003. },
  64004. enumerable: true,
  64005. configurable: true
  64006. });
  64007. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  64008. window.addEventListener("orientationchange", this._orientationChanged);
  64009. window.addEventListener("deviceorientation", this._deviceOrientation);
  64010. //In certain cases, the attach control is called AFTER orientation was changed,
  64011. //So this is needed.
  64012. this._orientationChanged();
  64013. };
  64014. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  64015. window.removeEventListener("orientationchange", this._orientationChanged);
  64016. window.removeEventListener("deviceorientation", this._deviceOrientation);
  64017. };
  64018. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  64019. //if no device orientation provided, don't update the rotation.
  64020. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  64021. if (!this._alpha)
  64022. return;
  64023. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  64024. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  64025. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  64026. //Mirror on XY Plane
  64027. this._camera.rotationQuaternion.z *= -1;
  64028. this._camera.rotationQuaternion.w *= -1;
  64029. };
  64030. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  64031. return "FreeCameraDeviceOrientationInput";
  64032. };
  64033. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  64034. return "deviceOrientation";
  64035. };
  64036. return FreeCameraDeviceOrientationInput;
  64037. }());
  64038. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  64039. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  64040. })(BABYLON || (BABYLON = {}));
  64041. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  64042. var BABYLON;
  64043. (function (BABYLON) {
  64044. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  64045. function ArcRotateCameraVRDeviceOrientationInput() {
  64046. this.alphaCorrection = 1;
  64047. this.betaCorrection = 1;
  64048. this.gammaCorrection = 1;
  64049. this._alpha = 0;
  64050. this._beta = 0;
  64051. this._gamma = 0;
  64052. this._dirty = false;
  64053. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  64054. }
  64055. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  64056. this.camera.attachControl(element, noPreventDefault);
  64057. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  64058. };
  64059. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  64060. var camera = this.camera;
  64061. this._alpha = +evt.alpha | 0;
  64062. this._beta = +evt.beta | 0;
  64063. this._gamma = +evt.gamma | 0;
  64064. this._dirty = true;
  64065. };
  64066. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  64067. if (this._dirty) {
  64068. this._dirty = false;
  64069. if (this._gamma < 0) {
  64070. this._gamma = 180 + this._gamma;
  64071. }
  64072. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  64073. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  64074. }
  64075. };
  64076. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  64077. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  64078. };
  64079. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  64080. return "ArcRotateCameraVRDeviceOrientationInput";
  64081. };
  64082. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  64083. return "VRDeviceOrientation";
  64084. };
  64085. return ArcRotateCameraVRDeviceOrientationInput;
  64086. }());
  64087. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  64088. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  64089. })(BABYLON || (BABYLON = {}));
  64090. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  64091. var BABYLON;
  64092. (function (BABYLON) {
  64093. var VRCameraMetrics = (function () {
  64094. function VRCameraMetrics() {
  64095. this.compensateDistortion = true;
  64096. }
  64097. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  64098. get: function () {
  64099. return this.hResolution / (2 * this.vResolution);
  64100. },
  64101. enumerable: true,
  64102. configurable: true
  64103. });
  64104. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  64105. get: function () {
  64106. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  64107. },
  64108. enumerable: true,
  64109. configurable: true
  64110. });
  64111. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  64112. get: function () {
  64113. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  64114. var h = (4 * meters) / this.hScreenSize;
  64115. return BABYLON.Matrix.Translation(h, 0, 0);
  64116. },
  64117. enumerable: true,
  64118. configurable: true
  64119. });
  64120. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  64121. get: function () {
  64122. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  64123. var h = (4 * meters) / this.hScreenSize;
  64124. return BABYLON.Matrix.Translation(-h, 0, 0);
  64125. },
  64126. enumerable: true,
  64127. configurable: true
  64128. });
  64129. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  64130. get: function () {
  64131. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  64132. },
  64133. enumerable: true,
  64134. configurable: true
  64135. });
  64136. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  64137. get: function () {
  64138. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  64139. },
  64140. enumerable: true,
  64141. configurable: true
  64142. });
  64143. VRCameraMetrics.GetDefault = function () {
  64144. var result = new VRCameraMetrics();
  64145. result.hResolution = 1280;
  64146. result.vResolution = 800;
  64147. result.hScreenSize = 0.149759993;
  64148. result.vScreenSize = 0.0935999975;
  64149. result.vScreenCenter = 0.0467999987;
  64150. result.eyeToScreenDistance = 0.0410000011;
  64151. result.lensSeparationDistance = 0.0635000020;
  64152. result.interpupillaryDistance = 0.0640000030;
  64153. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  64154. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  64155. result.postProcessScaleFactor = 1.714605507808412;
  64156. result.lensCenterOffset = 0.151976421;
  64157. return result;
  64158. };
  64159. return VRCameraMetrics;
  64160. }());
  64161. BABYLON.VRCameraMetrics = VRCameraMetrics;
  64162. })(BABYLON || (BABYLON = {}));
  64163. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  64164. var BABYLON;
  64165. (function (BABYLON) {
  64166. var WebVRFreeCamera = (function (_super) {
  64167. __extends(WebVRFreeCamera, _super);
  64168. function WebVRFreeCamera(name, position, scene, webVROptions) {
  64169. if (webVROptions === void 0) { webVROptions = {}; }
  64170. var _this = _super.call(this, name, position, scene) || this;
  64171. _this.webVROptions = webVROptions;
  64172. _this._vrDevice = null;
  64173. _this.rawPose = null;
  64174. _this._vrEnabled = false;
  64175. _this._specsVersion = 1.1;
  64176. _this._attached = false;
  64177. _this._positionOffset = BABYLON.Vector3.Zero();
  64178. _this._descendants = [];
  64179. _this.devicePosition = BABYLON.Vector3.Zero();
  64180. _this.deviceScaleFactor = 1;
  64181. _this.controllers = [];
  64182. _this.nonVRControllers = [];
  64183. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  64184. //legacy support - the compensation boolean was removed.
  64185. if (arguments.length === 5) {
  64186. _this.webVROptions = arguments[4];
  64187. }
  64188. // default webVR options
  64189. if (_this.webVROptions.trackPosition == undefined) {
  64190. _this.webVROptions.trackPosition = true;
  64191. }
  64192. if (_this.webVROptions.controllerMeshes == undefined) {
  64193. _this.webVROptions.controllerMeshes = true;
  64194. }
  64195. if (_this.webVROptions.defaultLightningOnControllers == undefined) {
  64196. _this.webVROptions.defaultLightningOnControllers = true;
  64197. }
  64198. _this.rotationQuaternion = new BABYLON.Quaternion();
  64199. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  64200. if (_this.webVROptions && _this.webVROptions.positionScale) {
  64201. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  64202. }
  64203. //enable VR
  64204. _this.getEngine().initWebVR();
  64205. //check specs version
  64206. if (!window.VRFrameData) {
  64207. _this._specsVersion = 1.0;
  64208. _this._frameData = {};
  64209. }
  64210. else {
  64211. _this._frameData = new VRFrameData();
  64212. }
  64213. _this.getEngine().getVRDevice(_this.webVROptions.displayName, function (device) {
  64214. if (!device) {
  64215. return;
  64216. }
  64217. _this._vrEnabled = true;
  64218. _this._vrDevice = device;
  64219. //reset the rig parameters.
  64220. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  64221. if (_this._attached) {
  64222. _this.getEngine().enableVR(_this._vrDevice);
  64223. }
  64224. });
  64225. // try to attach the controllers, if found.
  64226. _this.initControllers();
  64227. /**
  64228. * The idea behind the following lines:
  64229. * objects that have the camera as parent should actually have the rig cameras as a parent.
  64230. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  64231. * the second will not show it correctly.
  64232. *
  64233. * To solve this - each object that has the camera as parent will be added to a protected array.
  64234. * When the rig camera renders, it will take this array and set all of those to be its children.
  64235. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  64236. * Amazing!
  64237. */
  64238. scene.onBeforeCameraRenderObservable.add(function (camera) {
  64239. if (camera.parent === _this && _this.rigParenting) {
  64240. _this._descendants = _this.getDescendants(true, function (n) {
  64241. // don't take the cameras or the controllers!
  64242. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  64243. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  64244. return !isController && !isRigCamera;
  64245. });
  64246. _this._descendants.forEach(function (node) {
  64247. node.parent = camera;
  64248. });
  64249. }
  64250. });
  64251. scene.onAfterCameraRenderObservable.add(function (camera) {
  64252. if (camera.parent === _this && _this.rigParenting) {
  64253. _this._descendants.forEach(function (node) {
  64254. node.parent = _this;
  64255. });
  64256. }
  64257. });
  64258. return _this;
  64259. }
  64260. Object.defineProperty(WebVRFreeCamera.prototype, "onControllersAttached", {
  64261. set: function (callback) {
  64262. this._onControllersAttached = callback;
  64263. // after setting - if the controllers are already set, execute the callback.
  64264. if (this.controllers.length >= 2) {
  64265. callback(this.controllers);
  64266. }
  64267. },
  64268. enumerable: true,
  64269. configurable: true
  64270. });
  64271. Object.defineProperty(WebVRFreeCamera.prototype, "onNonVRControllerAttached", {
  64272. set: function (callback) {
  64273. this._onNonVRControllerAttached = callback;
  64274. this.nonVRControllers.forEach(function (controller) {
  64275. callback(controller);
  64276. });
  64277. },
  64278. enumerable: true,
  64279. configurable: true
  64280. });
  64281. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  64282. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  64283. var gp = _a[_i];
  64284. if (gp.hand === name) {
  64285. return gp;
  64286. }
  64287. }
  64288. return undefined;
  64289. };
  64290. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  64291. get: function () {
  64292. if (!this._leftController) {
  64293. this._leftController = this.getControllerByName("left");
  64294. }
  64295. return this._leftController;
  64296. },
  64297. enumerable: true,
  64298. configurable: true
  64299. });
  64300. ;
  64301. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  64302. get: function () {
  64303. if (!this._rightController) {
  64304. this._rightController = this.getControllerByName("right");
  64305. }
  64306. return this._rightController;
  64307. },
  64308. enumerable: true,
  64309. configurable: true
  64310. });
  64311. ;
  64312. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  64313. if (length === void 0) { length = 100; }
  64314. if (this.leftCamera) {
  64315. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera
  64316. }
  64317. else {
  64318. return _super.prototype.getForwardRay.call(this, length);
  64319. }
  64320. };
  64321. WebVRFreeCamera.prototype._checkInputs = function () {
  64322. if (this._vrEnabled) {
  64323. if (this._specsVersion === 1.1) {
  64324. this._vrDevice.getFrameData(this._frameData);
  64325. }
  64326. else {
  64327. //backwards comp
  64328. var pose = this._vrDevice.getPose();
  64329. this._frameData.pose = pose;
  64330. // calculate view and projection matrix
  64331. }
  64332. this.updateFromDevice(this._frameData.pose);
  64333. }
  64334. _super.prototype._checkInputs.call(this);
  64335. };
  64336. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  64337. if (poseData && poseData.orientation) {
  64338. this.rawPose = poseData;
  64339. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  64340. if (this.getScene().useRightHandedSystem) {
  64341. this.deviceRotationQuaternion.z *= -1;
  64342. this.deviceRotationQuaternion.w *= -1;
  64343. }
  64344. if (this.webVROptions.trackPosition && this.rawPose.position) {
  64345. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  64346. if (this.getScene().useRightHandedSystem) {
  64347. this.devicePosition.z *= -1;
  64348. }
  64349. }
  64350. }
  64351. };
  64352. /**
  64353. * WebVR's attach control will start broadcasting frames to the device.
  64354. * Note that in certain browsers (chrome for example) this function must be called
  64355. * within a user-interaction callback. Example:
  64356. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  64357. *
  64358. * @param {HTMLElement} element
  64359. * @param {boolean} [noPreventDefault]
  64360. *
  64361. * @memberOf WebVRFreeCamera
  64362. */
  64363. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  64364. _super.prototype.attachControl.call(this, element, noPreventDefault);
  64365. this._attached = true;
  64366. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  64367. if (this._vrEnabled) {
  64368. this.getEngine().enableVR(this._vrDevice);
  64369. }
  64370. };
  64371. WebVRFreeCamera.prototype.detachControl = function (element) {
  64372. _super.prototype.detachControl.call(this, element);
  64373. this._vrEnabled = false;
  64374. this._attached = false;
  64375. this.getEngine().disableVR();
  64376. };
  64377. WebVRFreeCamera.prototype.getClassName = function () {
  64378. return "WebVRFreeCamera";
  64379. };
  64380. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  64381. //uses the vrDisplay's "resetPose()".
  64382. //pitch and roll won't be affected.
  64383. this._vrDevice.resetPose();
  64384. };
  64385. WebVRFreeCamera.prototype._updateRigCameras = function () {
  64386. var camLeft = this._rigCameras[0];
  64387. var camRight = this._rigCameras[1];
  64388. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  64389. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  64390. camLeft.position.copyFrom(this.devicePosition);
  64391. camRight.position.copyFrom(this.devicePosition);
  64392. };
  64393. /**
  64394. * This function is called by the two RIG cameras.
  64395. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  64396. */
  64397. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  64398. var _this = this;
  64399. //WebVR 1.0
  64400. if (this._cameraRigParams["specs"] === 1.0) {
  64401. this._updateCameraRotationMatrix();
  64402. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  64403. // Computing target and final matrix
  64404. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  64405. if (this.getScene().useRightHandedSystem) {
  64406. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  64407. }
  64408. else {
  64409. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  64410. }
  64411. //now move the eye in the right direction
  64412. var eyeParams = this._cameraRigParams["eyeParameters"];
  64413. var offset = eyeParams.offset;
  64414. // it will actually always be 0, but just in case
  64415. if (this.getScene().useRightHandedSystem) {
  64416. offset[2] *= -1;
  64417. }
  64418. BABYLON.Matrix.TranslationToRef(-offset[0], offset[1], -offset[2], BABYLON.Tmp.Matrix[0]);
  64419. this._webvrViewMatrix.multiplyToRef(BABYLON.Tmp.Matrix[0], this._webvrViewMatrix);
  64420. }
  64421. else {
  64422. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  64423. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  64424. if (!this.getScene().useRightHandedSystem) {
  64425. [2, 6, 8, 9, 14].forEach(function (num) {
  64426. _this._webvrViewMatrix.m[num] *= -1;
  64427. });
  64428. }
  64429. // update the camera rotation matrix
  64430. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  64431. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  64432. // Computing target and final matrix
  64433. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  64434. }
  64435. var parentCamera = this._cameraRigParams["parentCamera"];
  64436. // should the view matrix be updated with scale and position offset?
  64437. if (parentCamera.deviceScaleFactor !== 1) {
  64438. this._webvrViewMatrix.invert();
  64439. // scale the position, if set
  64440. if (parentCamera.deviceScaleFactor) {
  64441. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  64442. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  64443. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  64444. }
  64445. this._webvrViewMatrix.invert();
  64446. }
  64447. return this._webvrViewMatrix;
  64448. };
  64449. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  64450. var _this = this;
  64451. if (this._cameraRigParams["specs"] === 1.0) {
  64452. var eyeParams = this._cameraRigParams["eyeParameters"];
  64453. // deprecated!!
  64454. BABYLON.Matrix.PerspectiveFovWebVRToRef(eyeParams.fieldOfView, 0.1, 1000, this._projectionMatrix, this.getScene().useRightHandedSystem);
  64455. }
  64456. else {
  64457. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  64458. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  64459. //babylon compatible matrix
  64460. if (!this.getScene().useRightHandedSystem) {
  64461. [8, 9, 10, 11].forEach(function (num) {
  64462. _this._projectionMatrix.m[num] *= -1;
  64463. });
  64464. }
  64465. }
  64466. return this._projectionMatrix;
  64467. };
  64468. WebVRFreeCamera.prototype.initControllers = function () {
  64469. var _this = this;
  64470. this.controllers = [];
  64471. new BABYLON.Gamepads(function (gp) {
  64472. if (gp.type === BABYLON.Gamepad.POSE_ENABLED) {
  64473. var webVrController = gp;
  64474. if (_this.webVROptions.controllerMeshes) {
  64475. webVrController.initControllerMesh(_this.getScene(), function (loadedMesh) {
  64476. if (_this.webVROptions.defaultLightningOnControllers) {
  64477. if (!_this._lightOnControllers) {
  64478. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  64479. }
  64480. loadedMesh.getChildren().forEach(function (mesh) {
  64481. _this._lightOnControllers.includedOnlyMeshes.push(mesh);
  64482. });
  64483. }
  64484. });
  64485. }
  64486. webVrController.attachToPoseControlledCamera(_this);
  64487. // since this is async - sanity check. Is the controller already stored?
  64488. if (_this.controllers.indexOf(webVrController) === -1) {
  64489. //add to the controllers array
  64490. _this.controllers.push(webVrController);
  64491. //did we find enough controllers? Great! let the developer know.
  64492. if (_this._onControllersAttached && _this.controllers.length >= 2) {
  64493. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  64494. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  64495. // So we're overriding setting left & right manually to be sure
  64496. var firstViveWandDetected = false;
  64497. for (var i = 0; i < _this.controllers.length; i++) {
  64498. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  64499. if (!firstViveWandDetected) {
  64500. firstViveWandDetected = true;
  64501. _this.controllers[i].hand = "left";
  64502. }
  64503. else {
  64504. _this.controllers[i].hand = "right";
  64505. }
  64506. }
  64507. }
  64508. _this._onControllersAttached(_this.controllers);
  64509. }
  64510. }
  64511. }
  64512. else {
  64513. _this.nonVRControllers.push(gp);
  64514. if (_this._onNonVRControllerAttached) {
  64515. _this._onNonVRControllerAttached(gp);
  64516. }
  64517. }
  64518. });
  64519. };
  64520. return WebVRFreeCamera;
  64521. }(BABYLON.FreeCamera));
  64522. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  64523. })(BABYLON || (BABYLON = {}));
  64524. //# sourceMappingURL=babylon.webVRCamera.js.map
  64525. /// <reference path="babylon.freeCamera.ts" />
  64526. var BABYLON;
  64527. (function (BABYLON) {
  64528. // We're mainly based on the logic defined into the FreeCamera code
  64529. var DeviceOrientationCamera = (function (_super) {
  64530. __extends(DeviceOrientationCamera, _super);
  64531. function DeviceOrientationCamera(name, position, scene) {
  64532. var _this = _super.call(this, name, position, scene) || this;
  64533. _this._quaternionCache = new BABYLON.Quaternion();
  64534. _this.inputs.addDeviceOrientation();
  64535. return _this;
  64536. }
  64537. DeviceOrientationCamera.prototype.getClassName = function () {
  64538. return "DeviceOrientationCamera";
  64539. };
  64540. DeviceOrientationCamera.prototype._checkInputs = function () {
  64541. _super.prototype._checkInputs.call(this);
  64542. this._quaternionCache.copyFrom(this.rotationQuaternion);
  64543. if (this._initialQuaternion) {
  64544. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  64545. }
  64546. };
  64547. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  64548. var _this = this;
  64549. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  64550. //can only work if this camera has a rotation quaternion already.
  64551. if (!this.rotationQuaternion)
  64552. return;
  64553. if (!this._initialQuaternion) {
  64554. this._initialQuaternion = new BABYLON.Quaternion();
  64555. }
  64556. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  64557. ['x', 'y', 'z'].forEach(function (axisName) {
  64558. if (!axis[axisName]) {
  64559. _this._initialQuaternion[axisName] = 0;
  64560. }
  64561. else {
  64562. _this._initialQuaternion[axisName] *= -1;
  64563. }
  64564. });
  64565. this._initialQuaternion.normalize();
  64566. //force rotation update
  64567. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  64568. };
  64569. return DeviceOrientationCamera;
  64570. }(BABYLON.FreeCamera));
  64571. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  64572. })(BABYLON || (BABYLON = {}));
  64573. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  64574. var BABYLON;
  64575. (function (BABYLON) {
  64576. var VRDeviceOrientationFreeCamera = (function (_super) {
  64577. __extends(VRDeviceOrientationFreeCamera, _super);
  64578. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  64579. if (compensateDistortion === void 0) { compensateDistortion = true; }
  64580. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  64581. var _this = _super.call(this, name, position, scene) || this;
  64582. vrCameraMetrics.compensateDistortion = compensateDistortion;
  64583. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  64584. return _this;
  64585. }
  64586. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  64587. return "VRDeviceOrientationFreeCamera";
  64588. };
  64589. return VRDeviceOrientationFreeCamera;
  64590. }(BABYLON.DeviceOrientationCamera));
  64591. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  64592. var VRDeviceOrientationGamepadCamera = (function (_super) {
  64593. __extends(VRDeviceOrientationGamepadCamera, _super);
  64594. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  64595. if (compensateDistortion === void 0) { compensateDistortion = true; }
  64596. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  64597. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  64598. _this.inputs.addGamepad();
  64599. return _this;
  64600. }
  64601. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  64602. return "VRDeviceOrientationGamepadCamera";
  64603. };
  64604. return VRDeviceOrientationGamepadCamera;
  64605. }(VRDeviceOrientationFreeCamera));
  64606. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  64607. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  64608. __extends(VRDeviceOrientationArcRotateCamera, _super);
  64609. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  64610. if (compensateDistortion === void 0) { compensateDistortion = true; }
  64611. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  64612. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  64613. vrCameraMetrics.compensateDistortion = compensateDistortion;
  64614. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  64615. _this.inputs.addVRDeviceOrientation();
  64616. return _this;
  64617. }
  64618. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  64619. return "VRDeviceOrientationArcRotateCamera";
  64620. };
  64621. return VRDeviceOrientationArcRotateCamera;
  64622. }(BABYLON.ArcRotateCamera));
  64623. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  64624. })(BABYLON || (BABYLON = {}));
  64625. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  64626. /// <reference path="babylon.freeCamera.ts" />
  64627. /// <reference path="babylon.arcRotateCamera.ts" />
  64628. /// <reference path="babylon.gamepadCamera.ts" />
  64629. /// <reference path="babylon.universalCamera.ts" />
  64630. var BABYLON;
  64631. (function (BABYLON) {
  64632. var AnaglyphFreeCamera = (function (_super) {
  64633. __extends(AnaglyphFreeCamera, _super);
  64634. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  64635. var _this = _super.call(this, name, position, scene) || this;
  64636. _this.interaxialDistance = interaxialDistance;
  64637. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  64638. return _this;
  64639. }
  64640. AnaglyphFreeCamera.prototype.getClassName = function () {
  64641. return "AnaglyphFreeCamera";
  64642. };
  64643. return AnaglyphFreeCamera;
  64644. }(BABYLON.FreeCamera));
  64645. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  64646. var AnaglyphArcRotateCamera = (function (_super) {
  64647. __extends(AnaglyphArcRotateCamera, _super);
  64648. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  64649. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  64650. _this.interaxialDistance = interaxialDistance;
  64651. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  64652. return _this;
  64653. }
  64654. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  64655. return "AnaglyphArcRotateCamera";
  64656. };
  64657. return AnaglyphArcRotateCamera;
  64658. }(BABYLON.ArcRotateCamera));
  64659. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  64660. var AnaglyphGamepadCamera = (function (_super) {
  64661. __extends(AnaglyphGamepadCamera, _super);
  64662. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  64663. var _this = _super.call(this, name, position, scene) || this;
  64664. _this.interaxialDistance = interaxialDistance;
  64665. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  64666. return _this;
  64667. }
  64668. AnaglyphGamepadCamera.prototype.getClassName = function () {
  64669. return "AnaglyphGamepadCamera";
  64670. };
  64671. return AnaglyphGamepadCamera;
  64672. }(BABYLON.GamepadCamera));
  64673. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  64674. var AnaglyphUniversalCamera = (function (_super) {
  64675. __extends(AnaglyphUniversalCamera, _super);
  64676. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  64677. var _this = _super.call(this, name, position, scene) || this;
  64678. _this.interaxialDistance = interaxialDistance;
  64679. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  64680. return _this;
  64681. }
  64682. AnaglyphUniversalCamera.prototype.getClassName = function () {
  64683. return "AnaglyphUniversalCamera";
  64684. };
  64685. return AnaglyphUniversalCamera;
  64686. }(BABYLON.UniversalCamera));
  64687. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  64688. var StereoscopicFreeCamera = (function (_super) {
  64689. __extends(StereoscopicFreeCamera, _super);
  64690. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  64691. var _this = _super.call(this, name, position, scene) || this;
  64692. _this.interaxialDistance = interaxialDistance;
  64693. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  64694. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  64695. return _this;
  64696. }
  64697. StereoscopicFreeCamera.prototype.getClassName = function () {
  64698. return "StereoscopicFreeCamera";
  64699. };
  64700. return StereoscopicFreeCamera;
  64701. }(BABYLON.FreeCamera));
  64702. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  64703. var StereoscopicArcRotateCamera = (function (_super) {
  64704. __extends(StereoscopicArcRotateCamera, _super);
  64705. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  64706. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  64707. _this.interaxialDistance = interaxialDistance;
  64708. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  64709. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  64710. return _this;
  64711. }
  64712. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  64713. return "StereoscopicArcRotateCamera";
  64714. };
  64715. return StereoscopicArcRotateCamera;
  64716. }(BABYLON.ArcRotateCamera));
  64717. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  64718. var StereoscopicGamepadCamera = (function (_super) {
  64719. __extends(StereoscopicGamepadCamera, _super);
  64720. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  64721. var _this = _super.call(this, name, position, scene) || this;
  64722. _this.interaxialDistance = interaxialDistance;
  64723. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  64724. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  64725. return _this;
  64726. }
  64727. StereoscopicGamepadCamera.prototype.getClassName = function () {
  64728. return "StereoscopicGamepadCamera";
  64729. };
  64730. return StereoscopicGamepadCamera;
  64731. }(BABYLON.GamepadCamera));
  64732. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  64733. var StereoscopicUniversalCamera = (function (_super) {
  64734. __extends(StereoscopicUniversalCamera, _super);
  64735. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  64736. var _this = _super.call(this, name, position, scene) || this;
  64737. _this.interaxialDistance = interaxialDistance;
  64738. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  64739. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  64740. return _this;
  64741. }
  64742. StereoscopicUniversalCamera.prototype.getClassName = function () {
  64743. return "StereoscopicUniversalCamera";
  64744. };
  64745. return StereoscopicUniversalCamera;
  64746. }(BABYLON.UniversalCamera));
  64747. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  64748. })(BABYLON || (BABYLON = {}));
  64749. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  64750. var BABYLON;
  64751. (function (BABYLON) {
  64752. var VRExperienceHelper = (function () {
  64753. function VRExperienceHelper(scene, webVROptions) {
  64754. if (webVROptions === void 0) { webVROptions = {}; }
  64755. var _this = this;
  64756. this.webVROptions = webVROptions;
  64757. this._webVRsupportedAndReady = false;
  64758. this._isInVRMode = false;
  64759. this._scene = scene;
  64760. if (!this._scene.activeCamera) {
  64761. this._scene.activeCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", new BABYLON.Vector3(0, 2, 0), scene);
  64762. }
  64763. else {
  64764. var newCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._scene.activeCamera.position, scene);
  64765. if (scene.activeCamera.rotation) {
  64766. newCamera.rotation = scene.activeCamera.rotation.clone();
  64767. }
  64768. this._scene.activeCamera = newCamera;
  64769. }
  64770. this._position = this._scene.activeCamera.position;
  64771. this._canvas = scene.getEngine().getRenderingCanvas();
  64772. this._scene.activeCamera.attachControl(this._canvas);
  64773. this._btnVR = document.createElement("BUTTON");
  64774. this._btnVR.className = "babylonVRicon";
  64775. this._btnVR.id = "babylonVRiconbtn";
  64776. this._btnVR.title = "Click to switch to VR";
  64777. 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) }";
  64778. var style = document.createElement('style');
  64779. style.appendChild(document.createTextNode(css));
  64780. document.getElementsByTagName('head')[0].appendChild(style);
  64781. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  64782. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  64783. window.addEventListener("resize", function () {
  64784. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  64785. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  64786. });
  64787. // Exiting VR mode using 'ESC' key on desktop
  64788. document.addEventListener("keydown", function (event) {
  64789. if (event.keyCode === 27 && _this._isInVRMode) {
  64790. _this.exitVR();
  64791. }
  64792. });
  64793. // Exiting VR mode double tapping the touch screen
  64794. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  64795. if (_this._isInVRMode) {
  64796. _this.exitVR();
  64797. }
  64798. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  64799. if (navigator.getVRDisplays) {
  64800. navigator.getVRDisplays().then(function (headsets) {
  64801. if (headsets.length > 0) {
  64802. scene.getEngine().initWebVR();
  64803. _this._webVRsupportedAndReady = true;
  64804. }
  64805. document.body.appendChild(_this._btnVR);
  64806. });
  64807. }
  64808. else {
  64809. document.body.appendChild(this._btnVR);
  64810. }
  64811. this._btnVR.addEventListener("click", function () {
  64812. _this.enterVR();
  64813. });
  64814. }
  64815. VRExperienceHelper.prototype.enterVR = function () {
  64816. this._scene.activeCamera.dispose();
  64817. // If WebVR is supported and a headset is connected
  64818. if (this._webVRsupportedAndReady) {
  64819. this._scene.activeCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene);
  64820. }
  64821. else {
  64822. this._scene.activeCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  64823. this._scene.getEngine().switchFullscreen(true);
  64824. }
  64825. this._scene.activeCamera.attachControl(this._canvas);
  64826. this._isInVRMode = true;
  64827. this._btnVR.style.display = "none";
  64828. };
  64829. VRExperienceHelper.prototype.exitVR = function () {
  64830. if (this._webVRsupportedAndReady) {
  64831. this._scene.getEngine().disableVR();
  64832. }
  64833. this._position = this._scene.activeCamera.position;
  64834. this._scene.activeCamera.dispose();
  64835. this._scene.activeCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position, this._scene);
  64836. this._scene.activeCamera.attachControl(this._canvas);
  64837. this._isInVRMode = false;
  64838. this._btnVR.style.display = "";
  64839. };
  64840. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  64841. get: function () {
  64842. return this._position;
  64843. },
  64844. set: function (value) {
  64845. this._position = value;
  64846. this._scene.activeCamera.position = value;
  64847. },
  64848. enumerable: true,
  64849. configurable: true
  64850. });
  64851. VRExperienceHelper.prototype.dispose = function () {
  64852. if (this._isInVRMode) {
  64853. this.exitVR();
  64854. }
  64855. document.body.removeChild(this._btnVR);
  64856. };
  64857. VRExperienceHelper.prototype.getClassName = function () {
  64858. return "VRExperienceHelper";
  64859. };
  64860. return VRExperienceHelper;
  64861. }());
  64862. BABYLON.VRExperienceHelper = VRExperienceHelper;
  64863. })(BABYLON || (BABYLON = {}));
  64864. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  64865. // Mainly based on these 2 articles :
  64866. // 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
  64867. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  64868. var BABYLON;
  64869. (function (BABYLON) {
  64870. var JoystickAxis;
  64871. (function (JoystickAxis) {
  64872. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  64873. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  64874. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  64875. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  64876. var VirtualJoystick = (function () {
  64877. function VirtualJoystick(leftJoystick) {
  64878. var _this = this;
  64879. if (leftJoystick) {
  64880. this._leftJoystick = true;
  64881. }
  64882. else {
  64883. this._leftJoystick = false;
  64884. }
  64885. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  64886. VirtualJoystick._globalJoystickIndex++;
  64887. // By default left & right arrow keys are moving the X
  64888. // and up & down keys are moving the Y
  64889. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  64890. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  64891. this.reverseLeftRight = false;
  64892. this.reverseUpDown = false;
  64893. // collections of pointers
  64894. this._touches = new BABYLON.StringDictionary();
  64895. this.deltaPosition = BABYLON.Vector3.Zero();
  64896. this._joystickSensibility = 25;
  64897. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  64898. this._rotationSpeed = 25;
  64899. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  64900. this._rotateOnAxisRelativeToMesh = false;
  64901. this._onResize = function (evt) {
  64902. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  64903. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  64904. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  64905. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  64906. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  64907. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  64908. };
  64909. // injecting a canvas element on top of the canvas 3D game
  64910. if (!VirtualJoystick.vjCanvas) {
  64911. window.addEventListener("resize", this._onResize, false);
  64912. VirtualJoystick.vjCanvas = document.createElement("canvas");
  64913. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  64914. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  64915. VirtualJoystick.vjCanvas.width = window.innerWidth;
  64916. VirtualJoystick.vjCanvas.height = window.innerHeight;
  64917. VirtualJoystick.vjCanvas.style.width = "100%";
  64918. VirtualJoystick.vjCanvas.style.height = "100%";
  64919. VirtualJoystick.vjCanvas.style.position = "absolute";
  64920. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  64921. VirtualJoystick.vjCanvas.style.top = "0px";
  64922. VirtualJoystick.vjCanvas.style.left = "0px";
  64923. VirtualJoystick.vjCanvas.style.zIndex = "5";
  64924. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  64925. // Support for jQuery PEP polyfill
  64926. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  64927. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  64928. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  64929. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  64930. document.body.appendChild(VirtualJoystick.vjCanvas);
  64931. }
  64932. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  64933. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  64934. this.pressed = false;
  64935. // default joystick color
  64936. this._joystickColor = "cyan";
  64937. this._joystickPointerID = -1;
  64938. // current joystick position
  64939. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  64940. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  64941. // origin joystick position
  64942. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  64943. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  64944. this._onPointerDownHandlerRef = function (evt) {
  64945. _this._onPointerDown(evt);
  64946. };
  64947. this._onPointerMoveHandlerRef = function (evt) {
  64948. _this._onPointerMove(evt);
  64949. };
  64950. this._onPointerOutHandlerRef = function (evt) {
  64951. _this._onPointerUp(evt);
  64952. };
  64953. this._onPointerUpHandlerRef = function (evt) {
  64954. _this._onPointerUp(evt);
  64955. };
  64956. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  64957. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  64958. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  64959. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  64960. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  64961. evt.preventDefault(); // Disables system menu
  64962. }, false);
  64963. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  64964. }
  64965. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  64966. this._joystickSensibility = newJoystickSensibility;
  64967. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  64968. };
  64969. VirtualJoystick.prototype._onPointerDown = function (e) {
  64970. var positionOnScreenCondition;
  64971. e.preventDefault();
  64972. if (this._leftJoystick === true) {
  64973. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  64974. }
  64975. else {
  64976. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  64977. }
  64978. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  64979. // First contact will be dedicated to the virtual joystick
  64980. this._joystickPointerID = e.pointerId;
  64981. this._joystickPointerStartPos.x = e.clientX;
  64982. this._joystickPointerStartPos.y = e.clientY;
  64983. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  64984. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  64985. this._deltaJoystickVector.x = 0;
  64986. this._deltaJoystickVector.y = 0;
  64987. this.pressed = true;
  64988. this._touches.add(e.pointerId.toString(), e);
  64989. }
  64990. else {
  64991. // You can only trigger the action buttons with a joystick declared
  64992. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  64993. this._action();
  64994. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  64995. }
  64996. }
  64997. };
  64998. VirtualJoystick.prototype._onPointerMove = function (e) {
  64999. // If the current pointer is the one associated to the joystick (first touch contact)
  65000. if (this._joystickPointerID == e.pointerId) {
  65001. this._joystickPointerPos.x = e.clientX;
  65002. this._joystickPointerPos.y = e.clientY;
  65003. this._deltaJoystickVector = this._joystickPointerPos.clone();
  65004. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  65005. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  65006. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  65007. switch (this._axisTargetedByLeftAndRight) {
  65008. case JoystickAxis.X:
  65009. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  65010. break;
  65011. case JoystickAxis.Y:
  65012. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  65013. break;
  65014. case JoystickAxis.Z:
  65015. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  65016. break;
  65017. }
  65018. var directionUpDown = this.reverseUpDown ? 1 : -1;
  65019. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  65020. switch (this._axisTargetedByUpAndDown) {
  65021. case JoystickAxis.X:
  65022. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  65023. break;
  65024. case JoystickAxis.Y:
  65025. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  65026. break;
  65027. case JoystickAxis.Z:
  65028. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  65029. break;
  65030. }
  65031. }
  65032. else {
  65033. var data = this._touches.get(e.pointerId.toString());
  65034. if (data) {
  65035. data.x = e.clientX;
  65036. data.y = e.clientY;
  65037. }
  65038. }
  65039. };
  65040. VirtualJoystick.prototype._onPointerUp = function (e) {
  65041. if (this._joystickPointerID == e.pointerId) {
  65042. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  65043. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  65044. this._joystickPointerID = -1;
  65045. this.pressed = false;
  65046. }
  65047. else {
  65048. var touch = this._touches.get(e.pointerId.toString());
  65049. if (touch) {
  65050. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  65051. }
  65052. }
  65053. this._deltaJoystickVector.x = 0;
  65054. this._deltaJoystickVector.y = 0;
  65055. this._touches.remove(e.pointerId.toString());
  65056. };
  65057. /**
  65058. * Change the color of the virtual joystick
  65059. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  65060. */
  65061. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  65062. this._joystickColor = newColor;
  65063. };
  65064. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  65065. this._action = action;
  65066. };
  65067. // Define which axis you'd like to control for left & right
  65068. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  65069. switch (axis) {
  65070. case JoystickAxis.X:
  65071. case JoystickAxis.Y:
  65072. case JoystickAxis.Z:
  65073. this._axisTargetedByLeftAndRight = axis;
  65074. break;
  65075. default:
  65076. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  65077. break;
  65078. }
  65079. };
  65080. // Define which axis you'd like to control for up & down
  65081. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  65082. switch (axis) {
  65083. case JoystickAxis.X:
  65084. case JoystickAxis.Y:
  65085. case JoystickAxis.Z:
  65086. this._axisTargetedByUpAndDown = axis;
  65087. break;
  65088. default:
  65089. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  65090. break;
  65091. }
  65092. };
  65093. VirtualJoystick.prototype._clearCanvas = function () {
  65094. if (this._leftJoystick) {
  65095. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  65096. }
  65097. else {
  65098. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  65099. }
  65100. };
  65101. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  65102. var _this = this;
  65103. if (this.pressed) {
  65104. this._touches.forEach(function (key, touch) {
  65105. if (touch.pointerId === _this._joystickPointerID) {
  65106. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  65107. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  65108. VirtualJoystick.vjCanvasContext.beginPath();
  65109. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  65110. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  65111. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  65112. VirtualJoystick.vjCanvasContext.stroke();
  65113. VirtualJoystick.vjCanvasContext.closePath();
  65114. VirtualJoystick.vjCanvasContext.beginPath();
  65115. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  65116. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  65117. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  65118. VirtualJoystick.vjCanvasContext.stroke();
  65119. VirtualJoystick.vjCanvasContext.closePath();
  65120. VirtualJoystick.vjCanvasContext.beginPath();
  65121. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  65122. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  65123. VirtualJoystick.vjCanvasContext.stroke();
  65124. VirtualJoystick.vjCanvasContext.closePath();
  65125. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  65126. }
  65127. else {
  65128. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  65129. VirtualJoystick.vjCanvasContext.beginPath();
  65130. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  65131. VirtualJoystick.vjCanvasContext.beginPath();
  65132. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  65133. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  65134. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  65135. VirtualJoystick.vjCanvasContext.stroke();
  65136. VirtualJoystick.vjCanvasContext.closePath();
  65137. touch.prevX = touch.x;
  65138. touch.prevY = touch.y;
  65139. }
  65140. ;
  65141. });
  65142. }
  65143. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  65144. };
  65145. VirtualJoystick.prototype.releaseCanvas = function () {
  65146. if (VirtualJoystick.vjCanvas) {
  65147. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  65148. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  65149. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  65150. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  65151. window.removeEventListener("resize", this._onResize);
  65152. document.body.removeChild(VirtualJoystick.vjCanvas);
  65153. VirtualJoystick.vjCanvas = null;
  65154. }
  65155. };
  65156. return VirtualJoystick;
  65157. }());
  65158. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  65159. VirtualJoystick._globalJoystickIndex = 0;
  65160. BABYLON.VirtualJoystick = VirtualJoystick;
  65161. })(BABYLON || (BABYLON = {}));
  65162. //# sourceMappingURL=babylon.virtualJoystick.js.map
  65163. var BABYLON;
  65164. (function (BABYLON) {
  65165. // We're mainly based on the logic defined into the FreeCamera code
  65166. var VirtualJoysticksCamera = (function (_super) {
  65167. __extends(VirtualJoysticksCamera, _super);
  65168. function VirtualJoysticksCamera(name, position, scene) {
  65169. var _this = _super.call(this, name, position, scene) || this;
  65170. _this.inputs.addVirtualJoystick();
  65171. return _this;
  65172. }
  65173. VirtualJoysticksCamera.prototype.getClassName = function () {
  65174. return "VirtualJoysticksCamera";
  65175. };
  65176. return VirtualJoysticksCamera;
  65177. }(BABYLON.FreeCamera));
  65178. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  65179. })(BABYLON || (BABYLON = {}));
  65180. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  65181. var BABYLON;
  65182. (function (BABYLON) {
  65183. var FreeCameraVirtualJoystickInput = (function () {
  65184. function FreeCameraVirtualJoystickInput() {
  65185. }
  65186. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  65187. return this._leftjoystick;
  65188. };
  65189. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  65190. return this._rightjoystick;
  65191. };
  65192. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  65193. if (this._leftjoystick) {
  65194. var camera = this.camera;
  65195. var speed = camera._computeLocalCameraSpeed() * 50;
  65196. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  65197. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  65198. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  65199. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  65200. if (!this._leftjoystick.pressed) {
  65201. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  65202. }
  65203. if (!this._rightjoystick.pressed) {
  65204. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  65205. }
  65206. }
  65207. };
  65208. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  65209. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  65210. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  65211. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  65212. this._leftjoystick.setJoystickSensibility(0.15);
  65213. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  65214. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  65215. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  65216. this._rightjoystick.reverseUpDown = true;
  65217. this._rightjoystick.setJoystickSensibility(0.05);
  65218. this._rightjoystick.setJoystickColor("yellow");
  65219. };
  65220. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  65221. this._leftjoystick.releaseCanvas();
  65222. this._rightjoystick.releaseCanvas();
  65223. };
  65224. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  65225. return "FreeCameraVirtualJoystickInput";
  65226. };
  65227. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  65228. return "virtualJoystick";
  65229. };
  65230. return FreeCameraVirtualJoystickInput;
  65231. }());
  65232. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  65233. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  65234. })(BABYLON || (BABYLON = {}));
  65235. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  65236. var BABYLON;
  65237. (function (BABYLON) {
  65238. var SimplificationSettings = (function () {
  65239. function SimplificationSettings(quality, distance, optimizeMesh) {
  65240. this.quality = quality;
  65241. this.distance = distance;
  65242. this.optimizeMesh = optimizeMesh;
  65243. }
  65244. return SimplificationSettings;
  65245. }());
  65246. BABYLON.SimplificationSettings = SimplificationSettings;
  65247. var SimplificationQueue = (function () {
  65248. function SimplificationQueue() {
  65249. this.running = false;
  65250. this._simplificationArray = [];
  65251. }
  65252. SimplificationQueue.prototype.addTask = function (task) {
  65253. this._simplificationArray.push(task);
  65254. };
  65255. SimplificationQueue.prototype.executeNext = function () {
  65256. var task = this._simplificationArray.pop();
  65257. if (task) {
  65258. this.running = true;
  65259. this.runSimplification(task);
  65260. }
  65261. else {
  65262. this.running = false;
  65263. }
  65264. };
  65265. SimplificationQueue.prototype.runSimplification = function (task) {
  65266. var _this = this;
  65267. if (task.parallelProcessing) {
  65268. //parallel simplifier
  65269. task.settings.forEach(function (setting) {
  65270. var simplifier = _this.getSimplifier(task);
  65271. simplifier.simplify(setting, function (newMesh) {
  65272. task.mesh.addLODLevel(setting.distance, newMesh);
  65273. newMesh.isVisible = true;
  65274. //check if it is the last
  65275. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  65276. //all done, run the success callback.
  65277. task.successCallback();
  65278. }
  65279. _this.executeNext();
  65280. });
  65281. });
  65282. }
  65283. else {
  65284. //single simplifier.
  65285. var simplifier = this.getSimplifier(task);
  65286. var runDecimation = function (setting, callback) {
  65287. simplifier.simplify(setting, function (newMesh) {
  65288. task.mesh.addLODLevel(setting.distance, newMesh);
  65289. newMesh.isVisible = true;
  65290. //run the next quality level
  65291. callback();
  65292. });
  65293. };
  65294. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  65295. runDecimation(task.settings[loop.index], function () {
  65296. loop.executeNext();
  65297. });
  65298. }, function () {
  65299. //execution ended, run the success callback.
  65300. if (task.successCallback) {
  65301. task.successCallback();
  65302. }
  65303. _this.executeNext();
  65304. });
  65305. }
  65306. };
  65307. SimplificationQueue.prototype.getSimplifier = function (task) {
  65308. switch (task.simplificationType) {
  65309. case SimplificationType.QUADRATIC:
  65310. default:
  65311. return new QuadraticErrorSimplification(task.mesh);
  65312. }
  65313. };
  65314. return SimplificationQueue;
  65315. }());
  65316. BABYLON.SimplificationQueue = SimplificationQueue;
  65317. /**
  65318. * The implemented types of simplification.
  65319. * At the moment only Quadratic Error Decimation is implemented.
  65320. */
  65321. var SimplificationType;
  65322. (function (SimplificationType) {
  65323. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  65324. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  65325. var DecimationTriangle = (function () {
  65326. function DecimationTriangle(vertices) {
  65327. this.vertices = vertices;
  65328. this.error = new Array(4);
  65329. this.deleted = false;
  65330. this.isDirty = false;
  65331. this.deletePending = false;
  65332. this.borderFactor = 0;
  65333. }
  65334. return DecimationTriangle;
  65335. }());
  65336. BABYLON.DecimationTriangle = DecimationTriangle;
  65337. var DecimationVertex = (function () {
  65338. function DecimationVertex(position, id) {
  65339. this.position = position;
  65340. this.id = id;
  65341. this.isBorder = true;
  65342. this.q = new QuadraticMatrix();
  65343. this.triangleCount = 0;
  65344. this.triangleStart = 0;
  65345. this.originalOffsets = [];
  65346. }
  65347. DecimationVertex.prototype.updatePosition = function (newPosition) {
  65348. this.position.copyFrom(newPosition);
  65349. };
  65350. return DecimationVertex;
  65351. }());
  65352. BABYLON.DecimationVertex = DecimationVertex;
  65353. var QuadraticMatrix = (function () {
  65354. function QuadraticMatrix(data) {
  65355. this.data = new Array(10);
  65356. for (var i = 0; i < 10; ++i) {
  65357. if (data && data[i]) {
  65358. this.data[i] = data[i];
  65359. }
  65360. else {
  65361. this.data[i] = 0;
  65362. }
  65363. }
  65364. }
  65365. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  65366. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  65367. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  65368. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  65369. return det;
  65370. };
  65371. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  65372. for (var i = 0; i < 10; ++i) {
  65373. this.data[i] += matrix.data[i];
  65374. }
  65375. };
  65376. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  65377. for (var i = 0; i < 10; ++i) {
  65378. this.data[i] += data[i];
  65379. }
  65380. };
  65381. QuadraticMatrix.prototype.add = function (matrix) {
  65382. var m = new QuadraticMatrix();
  65383. for (var i = 0; i < 10; ++i) {
  65384. m.data[i] = this.data[i] + matrix.data[i];
  65385. }
  65386. return m;
  65387. };
  65388. QuadraticMatrix.FromData = function (a, b, c, d) {
  65389. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  65390. };
  65391. //returning an array to avoid garbage collection
  65392. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  65393. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  65394. };
  65395. return QuadraticMatrix;
  65396. }());
  65397. BABYLON.QuadraticMatrix = QuadraticMatrix;
  65398. var Reference = (function () {
  65399. function Reference(vertexId, triangleId) {
  65400. this.vertexId = vertexId;
  65401. this.triangleId = triangleId;
  65402. }
  65403. return Reference;
  65404. }());
  65405. BABYLON.Reference = Reference;
  65406. /**
  65407. * An implementation of the Quadratic Error simplification algorithm.
  65408. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  65409. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  65410. * @author RaananW
  65411. */
  65412. var QuadraticErrorSimplification = (function () {
  65413. function QuadraticErrorSimplification(_mesh) {
  65414. this._mesh = _mesh;
  65415. this.initialized = false;
  65416. this.syncIterations = 5000;
  65417. this.aggressiveness = 7;
  65418. this.decimationIterations = 100;
  65419. this.boundingBoxEpsilon = BABYLON.Epsilon;
  65420. }
  65421. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  65422. var _this = this;
  65423. this.initDecimatedMesh();
  65424. //iterating through the submeshes array, one after the other.
  65425. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  65426. _this.initWithMesh(loop.index, function () {
  65427. _this.runDecimation(settings, loop.index, function () {
  65428. loop.executeNext();
  65429. });
  65430. }, settings.optimizeMesh);
  65431. }, function () {
  65432. setTimeout(function () {
  65433. successCallback(_this._reconstructedMesh);
  65434. }, 0);
  65435. });
  65436. };
  65437. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  65438. var _this = this;
  65439. var gCount = 0;
  65440. triangle.vertices.forEach(function (vertex) {
  65441. var count = 0;
  65442. var vPos = vertex.position;
  65443. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  65444. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  65445. ++count;
  65446. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  65447. ++count;
  65448. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  65449. ++count;
  65450. if (count > 1) {
  65451. ++gCount;
  65452. }
  65453. ;
  65454. });
  65455. if (gCount > 1) {
  65456. console.log(triangle, gCount);
  65457. }
  65458. return gCount > 1;
  65459. };
  65460. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  65461. var _this = this;
  65462. var targetCount = ~~(this.triangles.length * settings.quality);
  65463. var deletedTriangles = 0;
  65464. var triangleCount = this.triangles.length;
  65465. var iterationFunction = function (iteration, callback) {
  65466. setTimeout(function () {
  65467. if (iteration % 5 === 0) {
  65468. _this.updateMesh(iteration === 0);
  65469. }
  65470. for (var i = 0; i < _this.triangles.length; ++i) {
  65471. _this.triangles[i].isDirty = false;
  65472. }
  65473. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  65474. var trianglesIterator = function (i) {
  65475. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  65476. var t = _this.triangles[tIdx];
  65477. if (!t)
  65478. return;
  65479. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  65480. return;
  65481. }
  65482. for (var j = 0; j < 3; ++j) {
  65483. if (t.error[j] < threshold) {
  65484. var deleted0 = [];
  65485. var deleted1 = [];
  65486. var v0 = t.vertices[j];
  65487. var v1 = t.vertices[(j + 1) % 3];
  65488. if (v0.isBorder || v1.isBorder)
  65489. continue;
  65490. var p = BABYLON.Vector3.Zero();
  65491. var n = BABYLON.Vector3.Zero();
  65492. var uv = BABYLON.Vector2.Zero();
  65493. var color = new BABYLON.Color4(0, 0, 0, 1);
  65494. _this.calculateError(v0, v1, p, n, uv, color);
  65495. var delTr = [];
  65496. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  65497. continue;
  65498. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  65499. continue;
  65500. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  65501. continue;
  65502. var uniqueArray = [];
  65503. delTr.forEach(function (deletedT) {
  65504. if (uniqueArray.indexOf(deletedT) === -1) {
  65505. deletedT.deletePending = true;
  65506. uniqueArray.push(deletedT);
  65507. }
  65508. });
  65509. if (uniqueArray.length % 2 !== 0) {
  65510. continue;
  65511. }
  65512. v0.q = v1.q.add(v0.q);
  65513. v0.updatePosition(p);
  65514. var tStart = _this.references.length;
  65515. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  65516. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  65517. var tCount = _this.references.length - tStart;
  65518. if (tCount <= v0.triangleCount) {
  65519. if (tCount) {
  65520. for (var c = 0; c < tCount; c++) {
  65521. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  65522. }
  65523. }
  65524. }
  65525. else {
  65526. v0.triangleStart = tStart;
  65527. }
  65528. v0.triangleCount = tCount;
  65529. break;
  65530. }
  65531. }
  65532. };
  65533. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  65534. }, 0);
  65535. };
  65536. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  65537. if (triangleCount - deletedTriangles <= targetCount)
  65538. loop.breakLoop();
  65539. else {
  65540. iterationFunction(loop.index, function () {
  65541. loop.executeNext();
  65542. });
  65543. }
  65544. }, function () {
  65545. setTimeout(function () {
  65546. //reconstruct this part of the mesh
  65547. _this.reconstructMesh(submeshIndex);
  65548. successCallback();
  65549. }, 0);
  65550. });
  65551. };
  65552. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  65553. var _this = this;
  65554. this.vertices = [];
  65555. this.triangles = [];
  65556. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  65557. var indices = this._mesh.getIndices();
  65558. var submesh = this._mesh.subMeshes[submeshIndex];
  65559. var findInVertices = function (positionToSearch) {
  65560. if (optimizeMesh) {
  65561. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  65562. if (_this.vertices[ii].position.equals(positionToSearch)) {
  65563. return _this.vertices[ii];
  65564. }
  65565. }
  65566. }
  65567. return null;
  65568. };
  65569. var vertexReferences = [];
  65570. var vertexInit = function (i) {
  65571. var offset = i + submesh.verticesStart;
  65572. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  65573. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  65574. vertex.originalOffsets.push(offset);
  65575. if (vertex.id === _this.vertices.length) {
  65576. _this.vertices.push(vertex);
  65577. }
  65578. vertexReferences.push(vertex.id);
  65579. };
  65580. //var totalVertices = mesh.getTotalVertices();
  65581. var totalVertices = submesh.verticesCount;
  65582. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  65583. var indicesInit = function (i) {
  65584. var offset = (submesh.indexStart / 3) + i;
  65585. var pos = (offset * 3);
  65586. var i0 = indices[pos + 0];
  65587. var i1 = indices[pos + 1];
  65588. var i2 = indices[pos + 2];
  65589. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  65590. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  65591. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  65592. var triangle = new DecimationTriangle([v0, v1, v2]);
  65593. triangle.originalOffset = pos;
  65594. _this.triangles.push(triangle);
  65595. };
  65596. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  65597. _this.init(callback);
  65598. });
  65599. });
  65600. };
  65601. QuadraticErrorSimplification.prototype.init = function (callback) {
  65602. var _this = this;
  65603. var triangleInit1 = function (i) {
  65604. var t = _this.triangles[i];
  65605. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  65606. for (var j = 0; j < 3; j++) {
  65607. 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))));
  65608. }
  65609. };
  65610. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  65611. var triangleInit2 = function (i) {
  65612. var t = _this.triangles[i];
  65613. for (var j = 0; j < 3; ++j) {
  65614. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  65615. }
  65616. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  65617. };
  65618. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  65619. _this.initialized = true;
  65620. callback();
  65621. });
  65622. });
  65623. };
  65624. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  65625. var newTriangles = [];
  65626. var i;
  65627. for (i = 0; i < this.vertices.length; ++i) {
  65628. this.vertices[i].triangleCount = 0;
  65629. }
  65630. var t;
  65631. var j;
  65632. for (i = 0; i < this.triangles.length; ++i) {
  65633. if (!this.triangles[i].deleted) {
  65634. t = this.triangles[i];
  65635. for (j = 0; j < 3; ++j) {
  65636. t.vertices[j].triangleCount = 1;
  65637. }
  65638. newTriangles.push(t);
  65639. }
  65640. }
  65641. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  65642. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  65643. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  65644. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  65645. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  65646. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  65647. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  65648. var vertexCount = 0;
  65649. for (i = 0; i < this.vertices.length; ++i) {
  65650. var vertex = this.vertices[i];
  65651. vertex.id = vertexCount;
  65652. if (vertex.triangleCount) {
  65653. vertex.originalOffsets.forEach(function (originalOffset) {
  65654. newPositionData.push(vertex.position.x);
  65655. newPositionData.push(vertex.position.y);
  65656. newPositionData.push(vertex.position.z);
  65657. newNormalData.push(normalData[originalOffset * 3]);
  65658. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  65659. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  65660. if (uvs && uvs.length) {
  65661. newUVsData.push(uvs[(originalOffset * 2)]);
  65662. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  65663. }
  65664. else if (colorsData && colorsData.length) {
  65665. newColorsData.push(colorsData[(originalOffset * 4)]);
  65666. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  65667. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  65668. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  65669. }
  65670. ++vertexCount;
  65671. });
  65672. }
  65673. }
  65674. var startingIndex = this._reconstructedMesh.getTotalIndices();
  65675. var startingVertex = this._reconstructedMesh.getTotalVertices();
  65676. var submeshesArray = this._reconstructedMesh.subMeshes;
  65677. this._reconstructedMesh.subMeshes = [];
  65678. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  65679. var originalIndices = this._mesh.getIndices();
  65680. for (i = 0; i < newTriangles.length; ++i) {
  65681. t = newTriangles[i]; //now get the new referencing point for each vertex
  65682. [0, 1, 2].forEach(function (idx) {
  65683. var id = originalIndices[t.originalOffset + idx];
  65684. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  65685. if (offset < 0)
  65686. offset = 0;
  65687. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  65688. });
  65689. }
  65690. //overwriting the old vertex buffers and indices.
  65691. this._reconstructedMesh.setIndices(newIndicesArray);
  65692. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  65693. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  65694. if (newUVsData.length > 0)
  65695. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  65696. if (newColorsData.length > 0)
  65697. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  65698. //create submesh
  65699. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  65700. if (submeshIndex > 0) {
  65701. this._reconstructedMesh.subMeshes = [];
  65702. submeshesArray.forEach(function (submesh) {
  65703. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  65704. });
  65705. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  65706. }
  65707. };
  65708. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  65709. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  65710. this._reconstructedMesh.material = this._mesh.material;
  65711. this._reconstructedMesh.parent = this._mesh.parent;
  65712. this._reconstructedMesh.isVisible = false;
  65713. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  65714. };
  65715. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  65716. for (var i = 0; i < vertex1.triangleCount; ++i) {
  65717. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  65718. if (t.deleted)
  65719. continue;
  65720. var s = this.references[vertex1.triangleStart + i].vertexId;
  65721. var v1 = t.vertices[(s + 1) % 3];
  65722. var v2 = t.vertices[(s + 2) % 3];
  65723. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  65724. deletedArray[i] = true;
  65725. delTr.push(t);
  65726. continue;
  65727. }
  65728. var d1 = v1.position.subtract(point);
  65729. d1 = d1.normalize();
  65730. var d2 = v2.position.subtract(point);
  65731. d2 = d2.normalize();
  65732. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  65733. return true;
  65734. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  65735. deletedArray[i] = false;
  65736. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  65737. return true;
  65738. }
  65739. return false;
  65740. };
  65741. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  65742. var newDeleted = deletedTriangles;
  65743. for (var i = 0; i < vertex.triangleCount; ++i) {
  65744. var ref = this.references[vertex.triangleStart + i];
  65745. var t = this.triangles[ref.triangleId];
  65746. if (t.deleted)
  65747. continue;
  65748. if (deletedArray[i] && t.deletePending) {
  65749. t.deleted = true;
  65750. newDeleted++;
  65751. continue;
  65752. }
  65753. t.vertices[ref.vertexId] = origVertex;
  65754. t.isDirty = true;
  65755. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  65756. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  65757. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  65758. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  65759. this.references.push(ref);
  65760. }
  65761. return newDeleted;
  65762. };
  65763. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  65764. for (var i = 0; i < this.vertices.length; ++i) {
  65765. var vCount = [];
  65766. var vId = [];
  65767. var v = this.vertices[i];
  65768. var j;
  65769. for (j = 0; j < v.triangleCount; ++j) {
  65770. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  65771. for (var ii = 0; ii < 3; ii++) {
  65772. var ofs = 0;
  65773. var vv = triangle.vertices[ii];
  65774. while (ofs < vCount.length) {
  65775. if (vId[ofs] === vv.id)
  65776. break;
  65777. ++ofs;
  65778. }
  65779. if (ofs === vCount.length) {
  65780. vCount.push(1);
  65781. vId.push(vv.id);
  65782. }
  65783. else {
  65784. vCount[ofs]++;
  65785. }
  65786. }
  65787. }
  65788. for (j = 0; j < vCount.length; ++j) {
  65789. if (vCount[j] === 1) {
  65790. this.vertices[vId[j]].isBorder = true;
  65791. }
  65792. else {
  65793. this.vertices[vId[j]].isBorder = false;
  65794. }
  65795. }
  65796. }
  65797. };
  65798. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  65799. if (identifyBorders === void 0) { identifyBorders = false; }
  65800. var i;
  65801. if (!identifyBorders) {
  65802. var newTrianglesVector = [];
  65803. for (i = 0; i < this.triangles.length; ++i) {
  65804. if (!this.triangles[i].deleted) {
  65805. newTrianglesVector.push(this.triangles[i]);
  65806. }
  65807. }
  65808. this.triangles = newTrianglesVector;
  65809. }
  65810. for (i = 0; i < this.vertices.length; ++i) {
  65811. this.vertices[i].triangleCount = 0;
  65812. this.vertices[i].triangleStart = 0;
  65813. }
  65814. var t;
  65815. var j;
  65816. var v;
  65817. for (i = 0; i < this.triangles.length; ++i) {
  65818. t = this.triangles[i];
  65819. for (j = 0; j < 3; ++j) {
  65820. v = t.vertices[j];
  65821. v.triangleCount++;
  65822. }
  65823. }
  65824. var tStart = 0;
  65825. for (i = 0; i < this.vertices.length; ++i) {
  65826. this.vertices[i].triangleStart = tStart;
  65827. tStart += this.vertices[i].triangleCount;
  65828. this.vertices[i].triangleCount = 0;
  65829. }
  65830. var newReferences = new Array(this.triangles.length * 3);
  65831. for (i = 0; i < this.triangles.length; ++i) {
  65832. t = this.triangles[i];
  65833. for (j = 0; j < 3; ++j) {
  65834. v = t.vertices[j];
  65835. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  65836. v.triangleCount++;
  65837. }
  65838. }
  65839. this.references = newReferences;
  65840. if (identifyBorders) {
  65841. this.identifyBorder();
  65842. }
  65843. };
  65844. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  65845. var x = point.x;
  65846. var y = point.y;
  65847. var z = point.z;
  65848. 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
  65849. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  65850. };
  65851. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  65852. var q = vertex1.q.add(vertex2.q);
  65853. var border = vertex1.isBorder && vertex2.isBorder;
  65854. var error = 0;
  65855. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  65856. if (qDet !== 0 && !border) {
  65857. if (!pointResult) {
  65858. pointResult = BABYLON.Vector3.Zero();
  65859. }
  65860. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  65861. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  65862. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  65863. error = this.vertexError(q, pointResult);
  65864. }
  65865. else {
  65866. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  65867. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  65868. var error1 = this.vertexError(q, vertex1.position);
  65869. var error2 = this.vertexError(q, vertex2.position);
  65870. var error3 = this.vertexError(q, p3);
  65871. error = Math.min(error1, error2, error3);
  65872. if (error === error1) {
  65873. if (pointResult) {
  65874. pointResult.copyFrom(vertex1.position);
  65875. }
  65876. }
  65877. else if (error === error2) {
  65878. if (pointResult) {
  65879. pointResult.copyFrom(vertex2.position);
  65880. }
  65881. }
  65882. else {
  65883. if (pointResult) {
  65884. pointResult.copyFrom(p3);
  65885. }
  65886. }
  65887. }
  65888. return error;
  65889. };
  65890. return QuadraticErrorSimplification;
  65891. }());
  65892. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  65893. })(BABYLON || (BABYLON = {}));
  65894. //# sourceMappingURL=babylon.meshSimplification.js.map
  65895. var BABYLON;
  65896. (function (BABYLON) {
  65897. var Internals;
  65898. (function (Internals) {
  65899. var MeshLODLevel = (function () {
  65900. function MeshLODLevel(distance, mesh) {
  65901. this.distance = distance;
  65902. this.mesh = mesh;
  65903. }
  65904. return MeshLODLevel;
  65905. }());
  65906. Internals.MeshLODLevel = MeshLODLevel;
  65907. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  65908. })(BABYLON || (BABYLON = {}));
  65909. //# sourceMappingURL=babylon.meshLODLevel.js.map
  65910. var BABYLON;
  65911. (function (BABYLON) {
  65912. // Standard optimizations
  65913. var SceneOptimization = (function () {
  65914. function SceneOptimization(priority) {
  65915. if (priority === void 0) { priority = 0; }
  65916. this.priority = priority;
  65917. this.apply = function (scene) {
  65918. return true; // Return true if everything that can be done was applied
  65919. };
  65920. }
  65921. return SceneOptimization;
  65922. }());
  65923. BABYLON.SceneOptimization = SceneOptimization;
  65924. var TextureOptimization = (function (_super) {
  65925. __extends(TextureOptimization, _super);
  65926. function TextureOptimization(priority, maximumSize) {
  65927. if (priority === void 0) { priority = 0; }
  65928. if (maximumSize === void 0) { maximumSize = 1024; }
  65929. var _this = _super.call(this, priority) || this;
  65930. _this.priority = priority;
  65931. _this.maximumSize = maximumSize;
  65932. _this.apply = function (scene) {
  65933. var allDone = true;
  65934. for (var index = 0; index < scene.textures.length; index++) {
  65935. var texture = scene.textures[index];
  65936. if (!texture.canRescale || texture.getContext) {
  65937. continue;
  65938. }
  65939. var currentSize = texture.getSize();
  65940. var maxDimension = Math.max(currentSize.width, currentSize.height);
  65941. if (maxDimension > _this.maximumSize) {
  65942. texture.scale(0.5);
  65943. allDone = false;
  65944. }
  65945. }
  65946. return allDone;
  65947. };
  65948. return _this;
  65949. }
  65950. return TextureOptimization;
  65951. }(SceneOptimization));
  65952. BABYLON.TextureOptimization = TextureOptimization;
  65953. var HardwareScalingOptimization = (function (_super) {
  65954. __extends(HardwareScalingOptimization, _super);
  65955. function HardwareScalingOptimization(priority, maximumScale) {
  65956. if (priority === void 0) { priority = 0; }
  65957. if (maximumScale === void 0) { maximumScale = 2; }
  65958. var _this = _super.call(this, priority) || this;
  65959. _this.priority = priority;
  65960. _this.maximumScale = maximumScale;
  65961. _this._currentScale = 1;
  65962. _this.apply = function (scene) {
  65963. _this._currentScale++;
  65964. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  65965. return _this._currentScale >= _this.maximumScale;
  65966. };
  65967. return _this;
  65968. }
  65969. return HardwareScalingOptimization;
  65970. }(SceneOptimization));
  65971. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  65972. var ShadowsOptimization = (function (_super) {
  65973. __extends(ShadowsOptimization, _super);
  65974. function ShadowsOptimization() {
  65975. var _this = _super !== null && _super.apply(this, arguments) || this;
  65976. _this.apply = function (scene) {
  65977. scene.shadowsEnabled = false;
  65978. return true;
  65979. };
  65980. return _this;
  65981. }
  65982. return ShadowsOptimization;
  65983. }(SceneOptimization));
  65984. BABYLON.ShadowsOptimization = ShadowsOptimization;
  65985. var PostProcessesOptimization = (function (_super) {
  65986. __extends(PostProcessesOptimization, _super);
  65987. function PostProcessesOptimization() {
  65988. var _this = _super !== null && _super.apply(this, arguments) || this;
  65989. _this.apply = function (scene) {
  65990. scene.postProcessesEnabled = false;
  65991. return true;
  65992. };
  65993. return _this;
  65994. }
  65995. return PostProcessesOptimization;
  65996. }(SceneOptimization));
  65997. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  65998. var LensFlaresOptimization = (function (_super) {
  65999. __extends(LensFlaresOptimization, _super);
  66000. function LensFlaresOptimization() {
  66001. var _this = _super !== null && _super.apply(this, arguments) || this;
  66002. _this.apply = function (scene) {
  66003. scene.lensFlaresEnabled = false;
  66004. return true;
  66005. };
  66006. return _this;
  66007. }
  66008. return LensFlaresOptimization;
  66009. }(SceneOptimization));
  66010. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  66011. var ParticlesOptimization = (function (_super) {
  66012. __extends(ParticlesOptimization, _super);
  66013. function ParticlesOptimization() {
  66014. var _this = _super !== null && _super.apply(this, arguments) || this;
  66015. _this.apply = function (scene) {
  66016. scene.particlesEnabled = false;
  66017. return true;
  66018. };
  66019. return _this;
  66020. }
  66021. return ParticlesOptimization;
  66022. }(SceneOptimization));
  66023. BABYLON.ParticlesOptimization = ParticlesOptimization;
  66024. var RenderTargetsOptimization = (function (_super) {
  66025. __extends(RenderTargetsOptimization, _super);
  66026. function RenderTargetsOptimization() {
  66027. var _this = _super !== null && _super.apply(this, arguments) || this;
  66028. _this.apply = function (scene) {
  66029. scene.renderTargetsEnabled = false;
  66030. return true;
  66031. };
  66032. return _this;
  66033. }
  66034. return RenderTargetsOptimization;
  66035. }(SceneOptimization));
  66036. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  66037. var MergeMeshesOptimization = (function (_super) {
  66038. __extends(MergeMeshesOptimization, _super);
  66039. function MergeMeshesOptimization() {
  66040. var _this = _super !== null && _super.apply(this, arguments) || this;
  66041. _this._canBeMerged = function (abstractMesh) {
  66042. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  66043. return false;
  66044. }
  66045. var mesh = abstractMesh;
  66046. if (!mesh.isVisible || !mesh.isEnabled()) {
  66047. return false;
  66048. }
  66049. if (mesh.instances.length > 0) {
  66050. return false;
  66051. }
  66052. if (mesh.skeleton || mesh.hasLODLevels) {
  66053. return false;
  66054. }
  66055. if (mesh.parent) {
  66056. return false;
  66057. }
  66058. return true;
  66059. };
  66060. _this.apply = function (scene, updateSelectionTree) {
  66061. var globalPool = scene.meshes.slice(0);
  66062. var globalLength = globalPool.length;
  66063. for (var index = 0; index < globalLength; index++) {
  66064. var currentPool = new Array();
  66065. var current = globalPool[index];
  66066. // Checks
  66067. if (!_this._canBeMerged(current)) {
  66068. continue;
  66069. }
  66070. currentPool.push(current);
  66071. // Find compatible meshes
  66072. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  66073. var otherMesh = globalPool[subIndex];
  66074. if (!_this._canBeMerged(otherMesh)) {
  66075. continue;
  66076. }
  66077. if (otherMesh.material !== current.material) {
  66078. continue;
  66079. }
  66080. if (otherMesh.checkCollisions !== current.checkCollisions) {
  66081. continue;
  66082. }
  66083. currentPool.push(otherMesh);
  66084. globalLength--;
  66085. globalPool.splice(subIndex, 1);
  66086. subIndex--;
  66087. }
  66088. if (currentPool.length < 2) {
  66089. continue;
  66090. }
  66091. // Merge meshes
  66092. BABYLON.Mesh.MergeMeshes(currentPool);
  66093. }
  66094. if (updateSelectionTree != undefined) {
  66095. if (updateSelectionTree) {
  66096. scene.createOrUpdateSelectionOctree();
  66097. }
  66098. }
  66099. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  66100. scene.createOrUpdateSelectionOctree();
  66101. }
  66102. return true;
  66103. };
  66104. return _this;
  66105. }
  66106. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  66107. get: function () {
  66108. return MergeMeshesOptimization._UpdateSelectionTree;
  66109. },
  66110. set: function (value) {
  66111. MergeMeshesOptimization._UpdateSelectionTree = value;
  66112. },
  66113. enumerable: true,
  66114. configurable: true
  66115. });
  66116. return MergeMeshesOptimization;
  66117. }(SceneOptimization));
  66118. MergeMeshesOptimization._UpdateSelectionTree = false;
  66119. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  66120. // Options
  66121. var SceneOptimizerOptions = (function () {
  66122. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  66123. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  66124. if (trackerDuration === void 0) { trackerDuration = 2000; }
  66125. this.targetFrameRate = targetFrameRate;
  66126. this.trackerDuration = trackerDuration;
  66127. this.optimizations = new Array();
  66128. }
  66129. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  66130. var result = new SceneOptimizerOptions(targetFrameRate);
  66131. var priority = 0;
  66132. result.optimizations.push(new MergeMeshesOptimization(priority));
  66133. result.optimizations.push(new ShadowsOptimization(priority));
  66134. result.optimizations.push(new LensFlaresOptimization(priority));
  66135. // Next priority
  66136. priority++;
  66137. result.optimizations.push(new PostProcessesOptimization(priority));
  66138. result.optimizations.push(new ParticlesOptimization(priority));
  66139. // Next priority
  66140. priority++;
  66141. result.optimizations.push(new TextureOptimization(priority, 1024));
  66142. return result;
  66143. };
  66144. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  66145. var result = new SceneOptimizerOptions(targetFrameRate);
  66146. var priority = 0;
  66147. result.optimizations.push(new MergeMeshesOptimization(priority));
  66148. result.optimizations.push(new ShadowsOptimization(priority));
  66149. result.optimizations.push(new LensFlaresOptimization(priority));
  66150. // Next priority
  66151. priority++;
  66152. result.optimizations.push(new PostProcessesOptimization(priority));
  66153. result.optimizations.push(new ParticlesOptimization(priority));
  66154. // Next priority
  66155. priority++;
  66156. result.optimizations.push(new TextureOptimization(priority, 512));
  66157. // Next priority
  66158. priority++;
  66159. result.optimizations.push(new RenderTargetsOptimization(priority));
  66160. // Next priority
  66161. priority++;
  66162. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  66163. return result;
  66164. };
  66165. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  66166. var result = new SceneOptimizerOptions(targetFrameRate);
  66167. var priority = 0;
  66168. result.optimizations.push(new MergeMeshesOptimization(priority));
  66169. result.optimizations.push(new ShadowsOptimization(priority));
  66170. result.optimizations.push(new LensFlaresOptimization(priority));
  66171. // Next priority
  66172. priority++;
  66173. result.optimizations.push(new PostProcessesOptimization(priority));
  66174. result.optimizations.push(new ParticlesOptimization(priority));
  66175. // Next priority
  66176. priority++;
  66177. result.optimizations.push(new TextureOptimization(priority, 256));
  66178. // Next priority
  66179. priority++;
  66180. result.optimizations.push(new RenderTargetsOptimization(priority));
  66181. // Next priority
  66182. priority++;
  66183. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  66184. return result;
  66185. };
  66186. return SceneOptimizerOptions;
  66187. }());
  66188. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  66189. // Scene optimizer tool
  66190. var SceneOptimizer = (function () {
  66191. function SceneOptimizer() {
  66192. }
  66193. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  66194. // TODO: add an epsilon
  66195. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  66196. if (onSuccess) {
  66197. onSuccess();
  66198. }
  66199. return;
  66200. }
  66201. // Apply current level of optimizations
  66202. var allDone = true;
  66203. var noOptimizationApplied = true;
  66204. for (var index = 0; index < options.optimizations.length; index++) {
  66205. var optimization = options.optimizations[index];
  66206. if (optimization.priority === currentPriorityLevel) {
  66207. noOptimizationApplied = false;
  66208. allDone = allDone && optimization.apply(scene);
  66209. }
  66210. }
  66211. // If no optimization was applied, this is a failure :(
  66212. if (noOptimizationApplied) {
  66213. if (onFailure) {
  66214. onFailure();
  66215. }
  66216. return;
  66217. }
  66218. // If all optimizations were done, move to next level
  66219. if (allDone) {
  66220. currentPriorityLevel++;
  66221. }
  66222. // Let's the system running for a specific amount of time before checking FPS
  66223. scene.executeWhenReady(function () {
  66224. setTimeout(function () {
  66225. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  66226. }, options.trackerDuration);
  66227. });
  66228. };
  66229. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  66230. if (!options) {
  66231. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  66232. }
  66233. // Let's the system running for a specific amount of time before checking FPS
  66234. scene.executeWhenReady(function () {
  66235. setTimeout(function () {
  66236. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  66237. }, options.trackerDuration);
  66238. });
  66239. };
  66240. return SceneOptimizer;
  66241. }());
  66242. BABYLON.SceneOptimizer = SceneOptimizer;
  66243. })(BABYLON || (BABYLON = {}));
  66244. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  66245. var BABYLON;
  66246. (function (BABYLON) {
  66247. var OutlineRenderer = (function () {
  66248. function OutlineRenderer(scene) {
  66249. this.zOffset = 1;
  66250. this._scene = scene;
  66251. }
  66252. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  66253. var _this = this;
  66254. if (useOverlay === void 0) { useOverlay = false; }
  66255. var scene = this._scene;
  66256. var engine = this._scene.getEngine();
  66257. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66258. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  66259. return;
  66260. }
  66261. var mesh = subMesh.getRenderingMesh();
  66262. var material = subMesh.getMaterial();
  66263. engine.enableEffect(this._effect);
  66264. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  66265. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  66266. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  66267. // Bones
  66268. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66269. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  66270. }
  66271. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66272. // Alpha test
  66273. if (material && material.needAlphaTesting()) {
  66274. var alphaTexture = material.getAlphaTestTexture();
  66275. this._effect.setTexture("diffuseSampler", alphaTexture);
  66276. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  66277. }
  66278. engine.setZOffset(-this.zOffset);
  66279. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  66280. engine.setZOffset(0);
  66281. };
  66282. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  66283. var defines = [];
  66284. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  66285. var mesh = subMesh.getMesh();
  66286. var material = subMesh.getMaterial();
  66287. // Alpha test
  66288. if (material && material.needAlphaTesting()) {
  66289. defines.push("#define ALPHATEST");
  66290. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66291. attribs.push(BABYLON.VertexBuffer.UVKind);
  66292. defines.push("#define UV1");
  66293. }
  66294. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66295. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66296. defines.push("#define UV2");
  66297. }
  66298. }
  66299. // Bones
  66300. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66301. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66302. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66303. if (mesh.numBoneInfluencers > 4) {
  66304. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66305. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66306. }
  66307. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66308. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66309. }
  66310. else {
  66311. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66312. }
  66313. // Instances
  66314. if (useInstances) {
  66315. defines.push("#define INSTANCES");
  66316. attribs.push("world0");
  66317. attribs.push("world1");
  66318. attribs.push("world2");
  66319. attribs.push("world3");
  66320. }
  66321. // Get correct effect
  66322. var join = defines.join("\n");
  66323. if (this._cachedDefines !== join) {
  66324. this._cachedDefines = join;
  66325. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  66326. }
  66327. return this._effect.isReady();
  66328. };
  66329. return OutlineRenderer;
  66330. }());
  66331. BABYLON.OutlineRenderer = OutlineRenderer;
  66332. })(BABYLON || (BABYLON = {}));
  66333. //# sourceMappingURL=babylon.outlineRenderer.js.map
  66334. var BABYLON;
  66335. (function (BABYLON) {
  66336. var FaceAdjacencies = (function () {
  66337. function FaceAdjacencies() {
  66338. this.edges = new Array();
  66339. this.edgesConnectedCount = 0;
  66340. }
  66341. return FaceAdjacencies;
  66342. }());
  66343. var EdgesRenderer = (function () {
  66344. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  66345. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  66346. if (epsilon === void 0) { epsilon = 0.95; }
  66347. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  66348. this.edgesWidthScalerForOrthographic = 1000.0;
  66349. this.edgesWidthScalerForPerspective = 50.0;
  66350. this._linesPositions = new Array();
  66351. this._linesNormals = new Array();
  66352. this._linesIndices = new Array();
  66353. this._buffers = {};
  66354. this._checkVerticesInsteadOfIndices = false;
  66355. this._source = source;
  66356. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  66357. this._epsilon = epsilon;
  66358. this._prepareRessources();
  66359. this._generateEdgesLines();
  66360. }
  66361. EdgesRenderer.prototype._prepareRessources = function () {
  66362. if (this._lineShader) {
  66363. return;
  66364. }
  66365. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  66366. attributes: ["position", "normal"],
  66367. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  66368. });
  66369. this._lineShader.disableDepthWrite = true;
  66370. this._lineShader.backFaceCulling = false;
  66371. };
  66372. EdgesRenderer.prototype.dispose = function () {
  66373. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  66374. if (buffer) {
  66375. buffer.dispose();
  66376. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  66377. }
  66378. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  66379. if (buffer) {
  66380. buffer.dispose();
  66381. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  66382. }
  66383. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  66384. this._lineShader.dispose();
  66385. };
  66386. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  66387. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  66388. return 0;
  66389. }
  66390. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  66391. return 1;
  66392. }
  66393. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  66394. return 2;
  66395. }
  66396. return -1;
  66397. };
  66398. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  66399. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  66400. return 0;
  66401. }
  66402. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  66403. return 1;
  66404. }
  66405. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  66406. return 2;
  66407. }
  66408. return -1;
  66409. };
  66410. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  66411. var needToCreateLine;
  66412. if (edge === undefined) {
  66413. needToCreateLine = true;
  66414. }
  66415. else {
  66416. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  66417. needToCreateLine = dotProduct < this._epsilon;
  66418. }
  66419. if (needToCreateLine) {
  66420. var offset = this._linesPositions.length / 3;
  66421. var normal = p0.subtract(p1);
  66422. normal.normalize();
  66423. // Positions
  66424. this._linesPositions.push(p0.x);
  66425. this._linesPositions.push(p0.y);
  66426. this._linesPositions.push(p0.z);
  66427. this._linesPositions.push(p0.x);
  66428. this._linesPositions.push(p0.y);
  66429. this._linesPositions.push(p0.z);
  66430. this._linesPositions.push(p1.x);
  66431. this._linesPositions.push(p1.y);
  66432. this._linesPositions.push(p1.z);
  66433. this._linesPositions.push(p1.x);
  66434. this._linesPositions.push(p1.y);
  66435. this._linesPositions.push(p1.z);
  66436. // Normals
  66437. this._linesNormals.push(p1.x);
  66438. this._linesNormals.push(p1.y);
  66439. this._linesNormals.push(p1.z);
  66440. this._linesNormals.push(-1);
  66441. this._linesNormals.push(p1.x);
  66442. this._linesNormals.push(p1.y);
  66443. this._linesNormals.push(p1.z);
  66444. this._linesNormals.push(1);
  66445. this._linesNormals.push(p0.x);
  66446. this._linesNormals.push(p0.y);
  66447. this._linesNormals.push(p0.z);
  66448. this._linesNormals.push(-1);
  66449. this._linesNormals.push(p0.x);
  66450. this._linesNormals.push(p0.y);
  66451. this._linesNormals.push(p0.z);
  66452. this._linesNormals.push(1);
  66453. // Indices
  66454. this._linesIndices.push(offset);
  66455. this._linesIndices.push(offset + 1);
  66456. this._linesIndices.push(offset + 2);
  66457. this._linesIndices.push(offset);
  66458. this._linesIndices.push(offset + 2);
  66459. this._linesIndices.push(offset + 3);
  66460. }
  66461. };
  66462. EdgesRenderer.prototype._generateEdgesLines = function () {
  66463. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  66464. var indices = this._source.getIndices();
  66465. // First let's find adjacencies
  66466. var adjacencies = new Array();
  66467. var faceNormals = new Array();
  66468. var index;
  66469. var faceAdjacencies;
  66470. // Prepare faces
  66471. for (index = 0; index < indices.length; index += 3) {
  66472. faceAdjacencies = new FaceAdjacencies();
  66473. var p0Index = indices[index];
  66474. var p1Index = indices[index + 1];
  66475. var p2Index = indices[index + 2];
  66476. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  66477. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  66478. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  66479. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  66480. faceNormal.normalize();
  66481. faceNormals.push(faceNormal);
  66482. adjacencies.push(faceAdjacencies);
  66483. }
  66484. // Scan
  66485. for (index = 0; index < adjacencies.length; index++) {
  66486. faceAdjacencies = adjacencies[index];
  66487. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  66488. var otherFaceAdjacencies = adjacencies[otherIndex];
  66489. if (faceAdjacencies.edgesConnectedCount === 3) {
  66490. break;
  66491. }
  66492. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  66493. continue;
  66494. }
  66495. var otherP0 = indices[otherIndex * 3];
  66496. var otherP1 = indices[otherIndex * 3 + 1];
  66497. var otherP2 = indices[otherIndex * 3 + 2];
  66498. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  66499. var otherEdgeIndex;
  66500. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  66501. continue;
  66502. }
  66503. switch (edgeIndex) {
  66504. case 0:
  66505. if (this._checkVerticesInsteadOfIndices) {
  66506. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  66507. }
  66508. else {
  66509. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  66510. }
  66511. break;
  66512. case 1:
  66513. if (this._checkVerticesInsteadOfIndices) {
  66514. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  66515. }
  66516. else {
  66517. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  66518. }
  66519. break;
  66520. case 2:
  66521. if (this._checkVerticesInsteadOfIndices) {
  66522. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  66523. }
  66524. else {
  66525. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  66526. }
  66527. break;
  66528. }
  66529. if (otherEdgeIndex === -1) {
  66530. continue;
  66531. }
  66532. faceAdjacencies.edges[edgeIndex] = otherIndex;
  66533. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  66534. faceAdjacencies.edgesConnectedCount++;
  66535. otherFaceAdjacencies.edgesConnectedCount++;
  66536. if (faceAdjacencies.edgesConnectedCount === 3) {
  66537. break;
  66538. }
  66539. }
  66540. }
  66541. }
  66542. // Create lines
  66543. for (index = 0; index < adjacencies.length; index++) {
  66544. // 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
  66545. var current = adjacencies[index];
  66546. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  66547. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  66548. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  66549. }
  66550. // Merge into a single mesh
  66551. var engine = this._source.getScene().getEngine();
  66552. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  66553. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  66554. this._ib = engine.createIndexBuffer(this._linesIndices);
  66555. this._indicesCount = this._linesIndices.length;
  66556. };
  66557. EdgesRenderer.prototype.render = function () {
  66558. if (!this._lineShader.isReady()) {
  66559. return;
  66560. }
  66561. var scene = this._source.getScene();
  66562. var engine = scene.getEngine();
  66563. this._lineShader._preBind();
  66564. // VBOs
  66565. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  66566. scene.resetCachedMaterial();
  66567. this._lineShader.setColor4("color", this._source.edgesColor);
  66568. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  66569. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  66570. }
  66571. else {
  66572. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  66573. }
  66574. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  66575. this._lineShader.bind(this._source.getWorldMatrix());
  66576. // Draw order
  66577. engine.draw(true, 0, this._indicesCount);
  66578. this._lineShader.unbind();
  66579. engine.setDepthWrite(true);
  66580. };
  66581. return EdgesRenderer;
  66582. }());
  66583. BABYLON.EdgesRenderer = EdgesRenderer;
  66584. })(BABYLON || (BABYLON = {}));
  66585. //# sourceMappingURL=babylon.edgesRenderer.js.map
  66586. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  66587. /// <reference path="..\Math\babylon.math.ts" />
  66588. var BABYLON;
  66589. (function (BABYLON) {
  66590. /**
  66591. * Special Glow Blur post process only blurring the alpha channel
  66592. * It enforces keeping the most luminous color in the color channel.
  66593. */
  66594. var GlowBlurPostProcess = (function (_super) {
  66595. __extends(GlowBlurPostProcess, _super);
  66596. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  66597. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  66598. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  66599. _this.direction = direction;
  66600. _this.kernel = kernel;
  66601. _this.onApplyObservable.add(function (effect) {
  66602. effect.setFloat2("screenSize", _this.width, _this.height);
  66603. effect.setVector2("direction", _this.direction);
  66604. effect.setFloat("blurWidth", _this.kernel);
  66605. });
  66606. return _this;
  66607. }
  66608. return GlowBlurPostProcess;
  66609. }(BABYLON.PostProcess));
  66610. /**
  66611. * The highlight layer Helps adding a glow effect around a mesh.
  66612. *
  66613. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  66614. * glowy meshes to your scene.
  66615. *
  66616. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  66617. */
  66618. var HighlightLayer = (function () {
  66619. /**
  66620. * Instantiates a new highlight Layer and references it to the scene..
  66621. * @param name The name of the layer
  66622. * @param scene The scene to use the layer in
  66623. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  66624. */
  66625. function HighlightLayer(name, scene, options) {
  66626. this.name = name;
  66627. this._vertexBuffers = {};
  66628. this._mainTextureDesiredSize = { width: 0, height: 0 };
  66629. this._meshes = {};
  66630. this._maxSize = 0;
  66631. this._shouldRender = false;
  66632. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  66633. this._excludedMeshes = {};
  66634. /**
  66635. * Specifies whether or not the inner glow is ACTIVE in the layer.
  66636. */
  66637. this.innerGlow = true;
  66638. /**
  66639. * Specifies whether or not the outer glow is ACTIVE in the layer.
  66640. */
  66641. this.outerGlow = true;
  66642. /**
  66643. * Specifies wether the highlight layer is enabled or not.
  66644. */
  66645. this.isEnabled = true;
  66646. /**
  66647. * An event triggered when the highlight layer has been disposed.
  66648. * @type {BABYLON.Observable}
  66649. */
  66650. this.onDisposeObservable = new BABYLON.Observable();
  66651. /**
  66652. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  66653. * @type {BABYLON.Observable}
  66654. */
  66655. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  66656. /**
  66657. * An event triggered when the highlight layer is being blurred.
  66658. * @type {BABYLON.Observable}
  66659. */
  66660. this.onBeforeBlurObservable = new BABYLON.Observable();
  66661. /**
  66662. * An event triggered when the highlight layer has been blurred.
  66663. * @type {BABYLON.Observable}
  66664. */
  66665. this.onAfterBlurObservable = new BABYLON.Observable();
  66666. /**
  66667. * An event triggered when the glowing blurred texture is being merged in the scene.
  66668. * @type {BABYLON.Observable}
  66669. */
  66670. this.onBeforeComposeObservable = new BABYLON.Observable();
  66671. /**
  66672. * An event triggered when the glowing blurred texture has been merged in the scene.
  66673. * @type {BABYLON.Observable}
  66674. */
  66675. this.onAfterComposeObservable = new BABYLON.Observable();
  66676. /**
  66677. * An event triggered when the highlight layer changes its size.
  66678. * @type {BABYLON.Observable}
  66679. */
  66680. this.onSizeChangedObservable = new BABYLON.Observable();
  66681. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  66682. var engine = scene.getEngine();
  66683. this._engine = engine;
  66684. this._maxSize = this._engine.getCaps().maxTextureSize;
  66685. this._scene.highlightLayers.push(this);
  66686. // Warn on stencil.
  66687. if (!this._engine.isStencilEnable) {
  66688. 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 }");
  66689. }
  66690. // Adapt options
  66691. this._options = options || {
  66692. mainTextureRatio: 0.5,
  66693. blurTextureSizeRatio: 0.5,
  66694. blurHorizontalSize: 1.0,
  66695. blurVerticalSize: 1.0,
  66696. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  66697. };
  66698. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  66699. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  66700. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  66701. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  66702. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  66703. // VBO
  66704. var vertices = [];
  66705. vertices.push(1, 1);
  66706. vertices.push(-1, 1);
  66707. vertices.push(-1, -1);
  66708. vertices.push(1, -1);
  66709. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  66710. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  66711. // Indices
  66712. var indices = [];
  66713. indices.push(0);
  66714. indices.push(1);
  66715. indices.push(2);
  66716. indices.push(0);
  66717. indices.push(2);
  66718. indices.push(3);
  66719. this._indexBuffer = engine.createIndexBuffer(indices);
  66720. // Effect
  66721. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  66722. // Render target
  66723. this.setMainTextureSize();
  66724. // Create Textures and post processes
  66725. this.createTextureAndPostProcesses();
  66726. }
  66727. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  66728. /**
  66729. * Gets the horizontal size of the blur.
  66730. */
  66731. get: function () {
  66732. return this._horizontalBlurPostprocess.kernel;
  66733. },
  66734. /**
  66735. * Specifies the horizontal size of the blur.
  66736. */
  66737. set: function (value) {
  66738. this._horizontalBlurPostprocess.kernel = value;
  66739. },
  66740. enumerable: true,
  66741. configurable: true
  66742. });
  66743. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  66744. /**
  66745. * Gets the vertical size of the blur.
  66746. */
  66747. get: function () {
  66748. return this._verticalBlurPostprocess.kernel;
  66749. },
  66750. /**
  66751. * Specifies the vertical size of the blur.
  66752. */
  66753. set: function (value) {
  66754. this._verticalBlurPostprocess.kernel = value;
  66755. },
  66756. enumerable: true,
  66757. configurable: true
  66758. });
  66759. Object.defineProperty(HighlightLayer.prototype, "camera", {
  66760. /**
  66761. * Gets the camera attached to the layer.
  66762. */
  66763. get: function () {
  66764. return this._options.camera;
  66765. },
  66766. enumerable: true,
  66767. configurable: true
  66768. });
  66769. /**
  66770. * Creates the render target textures and post processes used in the highlight layer.
  66771. */
  66772. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  66773. var _this = this;
  66774. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  66775. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  66776. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  66777. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  66778. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  66779. width: this._mainTextureDesiredSize.width,
  66780. height: this._mainTextureDesiredSize.height
  66781. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  66782. this._mainTexture.activeCamera = this._options.camera;
  66783. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66784. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66785. this._mainTexture.anisotropicFilteringLevel = 1;
  66786. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66787. this._mainTexture.renderParticles = false;
  66788. this._mainTexture.renderList = null;
  66789. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  66790. width: blurTextureWidth,
  66791. height: blurTextureHeight
  66792. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  66793. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66794. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66795. this._blurTexture.anisotropicFilteringLevel = 16;
  66796. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  66797. this._blurTexture.renderParticles = false;
  66798. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  66799. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  66800. effect.setTexture("textureSampler", _this._mainTexture);
  66801. });
  66802. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  66803. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  66804. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  66805. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  66806. });
  66807. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  66808. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  66809. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  66810. });
  66811. }
  66812. else {
  66813. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  66814. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  66815. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  66816. });
  66817. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  66818. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  66819. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  66820. });
  66821. }
  66822. this._mainTexture.onAfterUnbindObservable.add(function () {
  66823. _this.onBeforeBlurObservable.notifyObservers(_this);
  66824. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  66825. _this.onAfterBlurObservable.notifyObservers(_this);
  66826. });
  66827. // Custom render function
  66828. var renderSubMesh = function (subMesh) {
  66829. var mesh = subMesh.getRenderingMesh();
  66830. var scene = _this._scene;
  66831. var engine = scene.getEngine();
  66832. // Culling
  66833. engine.setState(subMesh.getMaterial().backFaceCulling);
  66834. // Managing instances
  66835. var batch = mesh._getInstancesRenderList(subMesh._id);
  66836. if (batch.mustReturn) {
  66837. return;
  66838. }
  66839. // Excluded Mesh
  66840. if (_this._excludedMeshes[mesh.uniqueId]) {
  66841. return;
  66842. }
  66843. ;
  66844. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66845. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  66846. var material = subMesh.getMaterial();
  66847. var emissiveTexture = null;
  66848. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  66849. emissiveTexture = material.emissiveTexture;
  66850. }
  66851. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  66852. engine.enableEffect(_this._glowMapGenerationEffect);
  66853. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  66854. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  66855. if (highlightLayerMesh) {
  66856. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  66857. }
  66858. else {
  66859. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  66860. }
  66861. // Alpha test
  66862. if (material && material.needAlphaTesting()) {
  66863. var alphaTexture = material.getAlphaTestTexture();
  66864. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  66865. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  66866. }
  66867. // Glow emissive only
  66868. if (emissiveTexture) {
  66869. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  66870. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  66871. }
  66872. // Bones
  66873. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66874. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  66875. }
  66876. // Draw
  66877. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  66878. }
  66879. else {
  66880. // Need to reset refresh rate of the shadowMap
  66881. _this._mainTexture.resetRefreshCounter();
  66882. }
  66883. };
  66884. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  66885. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  66886. var index;
  66887. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66888. renderSubMesh(opaqueSubMeshes.data[index]);
  66889. }
  66890. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66891. renderSubMesh(alphaTestSubMeshes.data[index]);
  66892. }
  66893. for (index = 0; index < transparentSubMeshes.length; index++) {
  66894. renderSubMesh(transparentSubMeshes.data[index]);
  66895. }
  66896. };
  66897. this._mainTexture.onClearObservable.add(function (engine) {
  66898. engine.clear(HighlightLayer.neutralColor, true, true, true);
  66899. });
  66900. };
  66901. /**
  66902. * Checks for the readiness of the element composing the layer.
  66903. * @param subMesh the mesh to check for
  66904. * @param useInstances specify wether or not to use instances to render the mesh
  66905. * @param emissiveTexture the associated emissive texture used to generate the glow
  66906. * @return true if ready otherwise, false
  66907. */
  66908. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  66909. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  66910. return false;
  66911. }
  66912. var defines = [];
  66913. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66914. var mesh = subMesh.getMesh();
  66915. var material = subMesh.getMaterial();
  66916. var uv1 = false;
  66917. var uv2 = false;
  66918. // Alpha test
  66919. if (material && material.needAlphaTesting()) {
  66920. var alphaTexture = material.getAlphaTestTexture();
  66921. if (alphaTexture) {
  66922. defines.push("#define ALPHATEST");
  66923. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  66924. alphaTexture.coordinatesIndex === 1) {
  66925. defines.push("#define DIFFUSEUV2");
  66926. uv2 = true;
  66927. }
  66928. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66929. defines.push("#define DIFFUSEUV1");
  66930. uv1 = true;
  66931. }
  66932. }
  66933. }
  66934. // Emissive
  66935. if (emissiveTexture) {
  66936. defines.push("#define EMISSIVE");
  66937. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  66938. emissiveTexture.coordinatesIndex === 1) {
  66939. defines.push("#define EMISSIVEUV2");
  66940. uv2 = true;
  66941. }
  66942. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66943. defines.push("#define EMISSIVEUV1");
  66944. uv1 = true;
  66945. }
  66946. }
  66947. if (uv1) {
  66948. attribs.push(BABYLON.VertexBuffer.UVKind);
  66949. defines.push("#define UV1");
  66950. }
  66951. if (uv2) {
  66952. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66953. defines.push("#define UV2");
  66954. }
  66955. // Bones
  66956. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66957. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66958. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66959. if (mesh.numBoneInfluencers > 4) {
  66960. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66961. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66962. }
  66963. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66964. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66965. }
  66966. else {
  66967. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66968. }
  66969. // Instances
  66970. if (useInstances) {
  66971. defines.push("#define INSTANCES");
  66972. attribs.push("world0");
  66973. attribs.push("world1");
  66974. attribs.push("world2");
  66975. attribs.push("world3");
  66976. }
  66977. // Get correct effect
  66978. var join = defines.join("\n");
  66979. if (this._cachedDefines !== join) {
  66980. this._cachedDefines = join;
  66981. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  66982. }
  66983. return this._glowMapGenerationEffect.isReady();
  66984. };
  66985. /**
  66986. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  66987. */
  66988. HighlightLayer.prototype.render = function () {
  66989. var currentEffect = this._glowMapMergeEffect;
  66990. // Check
  66991. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  66992. return;
  66993. var engine = this._scene.getEngine();
  66994. this.onBeforeComposeObservable.notifyObservers(this);
  66995. // Render
  66996. engine.enableEffect(currentEffect);
  66997. engine.setState(false);
  66998. // Cache
  66999. var previousStencilBuffer = engine.getStencilBuffer();
  67000. var previousStencilFunction = engine.getStencilFunction();
  67001. var previousStencilMask = engine.getStencilMask();
  67002. var previousStencilOperationPass = engine.getStencilOperationPass();
  67003. var previousStencilOperationFail = engine.getStencilOperationFail();
  67004. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  67005. var previousAlphaMode = engine.getAlphaMode();
  67006. // Texture
  67007. currentEffect.setTexture("textureSampler", this._blurTexture);
  67008. // VBOs
  67009. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  67010. // Stencil operations
  67011. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  67012. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  67013. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  67014. // Draw order
  67015. engine.setAlphaMode(this._options.alphaBlendingMode);
  67016. engine.setStencilMask(0x00);
  67017. engine.setStencilBuffer(true);
  67018. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  67019. if (this.outerGlow) {
  67020. currentEffect.setFloat("offset", 0);
  67021. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  67022. engine.draw(true, 0, 6);
  67023. }
  67024. if (this.innerGlow) {
  67025. currentEffect.setFloat("offset", 1);
  67026. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  67027. engine.draw(true, 0, 6);
  67028. }
  67029. // Restore Cache
  67030. engine.setStencilFunction(previousStencilFunction);
  67031. engine.setStencilMask(previousStencilMask);
  67032. engine.setAlphaMode(previousAlphaMode);
  67033. engine.setStencilBuffer(previousStencilBuffer);
  67034. engine.setStencilOperationPass(previousStencilOperationPass);
  67035. engine.setStencilOperationFail(previousStencilOperationFail);
  67036. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  67037. engine._stencilState.reset();
  67038. this.onAfterComposeObservable.notifyObservers(this);
  67039. // Handle size changes.
  67040. var size = this._mainTexture.getSize();
  67041. this.setMainTextureSize();
  67042. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  67043. // Recreate RTT and post processes on size change.
  67044. this.onSizeChangedObservable.notifyObservers(this);
  67045. this.disposeTextureAndPostProcesses();
  67046. this.createTextureAndPostProcesses();
  67047. }
  67048. };
  67049. /**
  67050. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  67051. * @param mesh The mesh to exclude from the highlight layer
  67052. */
  67053. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  67054. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  67055. if (!meshExcluded) {
  67056. this._excludedMeshes[mesh.uniqueId] = {
  67057. mesh: mesh,
  67058. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  67059. mesh.getEngine().setStencilBuffer(false);
  67060. }),
  67061. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  67062. mesh.getEngine().setStencilBuffer(true);
  67063. }),
  67064. };
  67065. }
  67066. };
  67067. /**
  67068. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  67069. * @param mesh The mesh to highlight
  67070. */
  67071. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  67072. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  67073. if (meshExcluded) {
  67074. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  67075. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  67076. }
  67077. this._excludedMeshes[mesh.uniqueId] = undefined;
  67078. };
  67079. /**
  67080. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  67081. * @param mesh The mesh to highlight
  67082. * @param color The color of the highlight
  67083. * @param glowEmissiveOnly Extract the glow from the emissive texture
  67084. */
  67085. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  67086. var _this = this;
  67087. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  67088. var meshHighlight = this._meshes[mesh.uniqueId];
  67089. if (meshHighlight) {
  67090. meshHighlight.color = color;
  67091. }
  67092. else {
  67093. this._meshes[mesh.uniqueId] = {
  67094. mesh: mesh,
  67095. color: color,
  67096. // Lambda required for capture due to Observable this context
  67097. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  67098. if (_this._excludedMeshes[mesh.uniqueId]) {
  67099. _this.defaultStencilReference(mesh);
  67100. }
  67101. else {
  67102. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  67103. }
  67104. }),
  67105. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  67106. glowEmissiveOnly: glowEmissiveOnly
  67107. };
  67108. }
  67109. this._shouldRender = true;
  67110. };
  67111. /**
  67112. * Remove a mesh from the highlight layer in order to make it stop glowing.
  67113. * @param mesh The mesh to highlight
  67114. */
  67115. HighlightLayer.prototype.removeMesh = function (mesh) {
  67116. var meshHighlight = this._meshes[mesh.uniqueId];
  67117. if (meshHighlight) {
  67118. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  67119. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  67120. }
  67121. this._meshes[mesh.uniqueId] = undefined;
  67122. this._shouldRender = false;
  67123. for (var meshHighlightToCheck in this._meshes) {
  67124. if (meshHighlightToCheck) {
  67125. this._shouldRender = true;
  67126. break;
  67127. }
  67128. }
  67129. };
  67130. /**
  67131. * Returns true if the layer contains information to display, otherwise false.
  67132. */
  67133. HighlightLayer.prototype.shouldRender = function () {
  67134. return this.isEnabled && this._shouldRender;
  67135. };
  67136. /**
  67137. * Sets the main texture desired size which is the closest power of two
  67138. * of the engine canvas size.
  67139. */
  67140. HighlightLayer.prototype.setMainTextureSize = function () {
  67141. if (this._options.mainTextureFixedSize) {
  67142. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  67143. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  67144. }
  67145. else {
  67146. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  67147. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  67148. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  67149. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  67150. }
  67151. };
  67152. /**
  67153. * Force the stencil to the normal expected value for none glowing parts
  67154. */
  67155. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  67156. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  67157. };
  67158. /**
  67159. * Dispose only the render target textures and post process.
  67160. */
  67161. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  67162. this._blurTexture.dispose();
  67163. this._mainTexture.dispose();
  67164. this._downSamplePostprocess.dispose();
  67165. this._horizontalBlurPostprocess.dispose();
  67166. this._verticalBlurPostprocess.dispose();
  67167. };
  67168. /**
  67169. * Dispose the highlight layer and free resources.
  67170. */
  67171. HighlightLayer.prototype.dispose = function () {
  67172. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  67173. if (vertexBuffer) {
  67174. vertexBuffer.dispose();
  67175. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  67176. }
  67177. if (this._indexBuffer) {
  67178. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  67179. this._indexBuffer = null;
  67180. }
  67181. // Clean textures and post processes
  67182. this.disposeTextureAndPostProcesses();
  67183. // Clean mesh references
  67184. for (var id in this._meshes) {
  67185. var meshHighlight = this._meshes[id];
  67186. if (meshHighlight && meshHighlight.mesh) {
  67187. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  67188. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  67189. }
  67190. }
  67191. this._meshes = null;
  67192. for (var id in this._excludedMeshes) {
  67193. var meshHighlight = this._excludedMeshes[id];
  67194. if (meshHighlight) {
  67195. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  67196. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  67197. }
  67198. }
  67199. this._excludedMeshes = null;
  67200. // Remove from scene
  67201. var index = this._scene.highlightLayers.indexOf(this, 0);
  67202. if (index > -1) {
  67203. this._scene.highlightLayers.splice(index, 1);
  67204. }
  67205. // Callback
  67206. this.onDisposeObservable.notifyObservers(this);
  67207. this.onDisposeObservable.clear();
  67208. this.onBeforeRenderMainTextureObservable.clear();
  67209. this.onBeforeBlurObservable.clear();
  67210. this.onBeforeComposeObservable.clear();
  67211. this.onAfterComposeObservable.clear();
  67212. this.onSizeChangedObservable.clear();
  67213. };
  67214. return HighlightLayer;
  67215. }());
  67216. /**
  67217. * The neutral color used during the preparation of the glow effect.
  67218. * This is black by default as the blend operation is a blend operation.
  67219. */
  67220. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  67221. /**
  67222. * Stencil value used for glowing meshes.
  67223. */
  67224. HighlightLayer.glowingMeshStencilReference = 0x02;
  67225. /**
  67226. * Stencil value used for the other meshes in the scene.
  67227. */
  67228. HighlightLayer.normalMeshStencilReference = 0x01;
  67229. BABYLON.HighlightLayer = HighlightLayer;
  67230. })(BABYLON || (BABYLON = {}));
  67231. //# sourceMappingURL=babylon.highlightlayer.js.map
  67232. var BABYLON;
  67233. (function (BABYLON) {
  67234. var MeshAssetTask = (function () {
  67235. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  67236. this.name = name;
  67237. this.meshesNames = meshesNames;
  67238. this.rootUrl = rootUrl;
  67239. this.sceneFilename = sceneFilename;
  67240. this.isCompleted = false;
  67241. }
  67242. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  67243. var _this = this;
  67244. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  67245. _this.loadedMeshes = meshes;
  67246. _this.loadedParticleSystems = particleSystems;
  67247. _this.loadedSkeletons = skeletons;
  67248. _this.isCompleted = true;
  67249. if (_this.onSuccess) {
  67250. _this.onSuccess(_this);
  67251. }
  67252. onSuccess();
  67253. }, null, function () {
  67254. if (_this.onError) {
  67255. _this.onError(_this);
  67256. }
  67257. onError();
  67258. });
  67259. };
  67260. return MeshAssetTask;
  67261. }());
  67262. BABYLON.MeshAssetTask = MeshAssetTask;
  67263. var TextFileAssetTask = (function () {
  67264. function TextFileAssetTask(name, url) {
  67265. this.name = name;
  67266. this.url = url;
  67267. this.isCompleted = false;
  67268. }
  67269. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  67270. var _this = this;
  67271. BABYLON.Tools.LoadFile(this.url, function (data) {
  67272. _this.text = data;
  67273. _this.isCompleted = true;
  67274. if (_this.onSuccess) {
  67275. _this.onSuccess(_this);
  67276. }
  67277. onSuccess();
  67278. }, null, scene.database, false, function () {
  67279. if (_this.onError) {
  67280. _this.onError(_this);
  67281. }
  67282. onError();
  67283. });
  67284. };
  67285. return TextFileAssetTask;
  67286. }());
  67287. BABYLON.TextFileAssetTask = TextFileAssetTask;
  67288. var BinaryFileAssetTask = (function () {
  67289. function BinaryFileAssetTask(name, url) {
  67290. this.name = name;
  67291. this.url = url;
  67292. this.isCompleted = false;
  67293. }
  67294. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  67295. var _this = this;
  67296. BABYLON.Tools.LoadFile(this.url, function (data) {
  67297. _this.data = data;
  67298. _this.isCompleted = true;
  67299. if (_this.onSuccess) {
  67300. _this.onSuccess(_this);
  67301. }
  67302. onSuccess();
  67303. }, null, scene.database, true, function () {
  67304. if (_this.onError) {
  67305. _this.onError(_this);
  67306. }
  67307. onError();
  67308. });
  67309. };
  67310. return BinaryFileAssetTask;
  67311. }());
  67312. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  67313. var ImageAssetTask = (function () {
  67314. function ImageAssetTask(name, url) {
  67315. this.name = name;
  67316. this.url = url;
  67317. this.isCompleted = false;
  67318. }
  67319. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  67320. var _this = this;
  67321. var img = new Image();
  67322. BABYLON.Tools.SetCorsBehavior(this.url, img);
  67323. img.onload = function () {
  67324. _this.image = img;
  67325. _this.isCompleted = true;
  67326. if (_this.onSuccess) {
  67327. _this.onSuccess(_this);
  67328. }
  67329. onSuccess();
  67330. };
  67331. img.onerror = function () {
  67332. if (_this.onError) {
  67333. _this.onError(_this);
  67334. }
  67335. onError();
  67336. };
  67337. img.src = this.url;
  67338. };
  67339. return ImageAssetTask;
  67340. }());
  67341. BABYLON.ImageAssetTask = ImageAssetTask;
  67342. var TextureAssetTask = (function () {
  67343. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  67344. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67345. this.name = name;
  67346. this.url = url;
  67347. this.noMipmap = noMipmap;
  67348. this.invertY = invertY;
  67349. this.samplingMode = samplingMode;
  67350. this.isCompleted = false;
  67351. }
  67352. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  67353. var _this = this;
  67354. var onload = function () {
  67355. _this.isCompleted = true;
  67356. if (_this.onSuccess) {
  67357. _this.onSuccess(_this);
  67358. }
  67359. onSuccess();
  67360. };
  67361. var onerror = function () {
  67362. if (_this.onError) {
  67363. _this.onError(_this);
  67364. }
  67365. onError();
  67366. };
  67367. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  67368. };
  67369. return TextureAssetTask;
  67370. }());
  67371. BABYLON.TextureAssetTask = TextureAssetTask;
  67372. var CubeTextureAssetTask = (function () {
  67373. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  67374. this.name = name;
  67375. this.url = url;
  67376. this.extensions = extensions;
  67377. this.noMipmap = noMipmap;
  67378. this.files = files;
  67379. this.isCompleted = false;
  67380. }
  67381. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  67382. var _this = this;
  67383. var onload = function () {
  67384. _this.isCompleted = true;
  67385. if (_this.onSuccess) {
  67386. _this.onSuccess(_this);
  67387. }
  67388. onSuccess();
  67389. };
  67390. var onerror = function () {
  67391. if (_this.onError) {
  67392. _this.onError(_this);
  67393. }
  67394. onError();
  67395. };
  67396. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  67397. };
  67398. return CubeTextureAssetTask;
  67399. }());
  67400. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  67401. var HDRCubeTextureAssetTask = (function () {
  67402. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  67403. if (noMipmap === void 0) { noMipmap = false; }
  67404. if (generateHarmonics === void 0) { generateHarmonics = true; }
  67405. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  67406. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  67407. this.name = name;
  67408. this.url = url;
  67409. this.size = size;
  67410. this.noMipmap = noMipmap;
  67411. this.generateHarmonics = generateHarmonics;
  67412. this.useInGammaSpace = useInGammaSpace;
  67413. this.usePMREMGenerator = usePMREMGenerator;
  67414. this.isCompleted = false;
  67415. }
  67416. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  67417. var _this = this;
  67418. var onload = function () {
  67419. _this.isCompleted = true;
  67420. if (_this.onSuccess) {
  67421. _this.onSuccess(_this);
  67422. }
  67423. onSuccess();
  67424. };
  67425. var onerror = function () {
  67426. if (_this.onError) {
  67427. _this.onError(_this);
  67428. }
  67429. onError();
  67430. };
  67431. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  67432. };
  67433. return HDRCubeTextureAssetTask;
  67434. }());
  67435. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  67436. var AssetsManager = (function () {
  67437. function AssetsManager(scene) {
  67438. this.tasks = new Array();
  67439. this.waitingTasksCount = 0;
  67440. this.useDefaultLoadingScreen = true;
  67441. this._scene = scene;
  67442. }
  67443. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  67444. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  67445. this.tasks.push(task);
  67446. return task;
  67447. };
  67448. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  67449. var task = new TextFileAssetTask(taskName, url);
  67450. this.tasks.push(task);
  67451. return task;
  67452. };
  67453. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  67454. var task = new BinaryFileAssetTask(taskName, url);
  67455. this.tasks.push(task);
  67456. return task;
  67457. };
  67458. AssetsManager.prototype.addImageTask = function (taskName, url) {
  67459. var task = new ImageAssetTask(taskName, url);
  67460. this.tasks.push(task);
  67461. return task;
  67462. };
  67463. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  67464. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67465. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  67466. this.tasks.push(task);
  67467. return task;
  67468. };
  67469. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  67470. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  67471. this.tasks.push(task);
  67472. return task;
  67473. };
  67474. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  67475. if (noMipmap === void 0) { noMipmap = false; }
  67476. if (generateHarmonics === void 0) { generateHarmonics = true; }
  67477. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  67478. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  67479. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  67480. this.tasks.push(task);
  67481. return task;
  67482. };
  67483. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  67484. this.waitingTasksCount--;
  67485. if (this.waitingTasksCount === 0) {
  67486. if (this.onFinish) {
  67487. this.onFinish(this.tasks);
  67488. }
  67489. this._scene.getEngine().hideLoadingUI();
  67490. }
  67491. };
  67492. AssetsManager.prototype._runTask = function (task) {
  67493. var _this = this;
  67494. task.run(this._scene, function () {
  67495. if (_this.onTaskSuccess) {
  67496. _this.onTaskSuccess(task);
  67497. }
  67498. _this._decreaseWaitingTasksCount();
  67499. }, function () {
  67500. if (_this.onTaskError) {
  67501. _this.onTaskError(task);
  67502. }
  67503. _this._decreaseWaitingTasksCount();
  67504. });
  67505. };
  67506. AssetsManager.prototype.reset = function () {
  67507. this.tasks = new Array();
  67508. return this;
  67509. };
  67510. AssetsManager.prototype.load = function () {
  67511. this.waitingTasksCount = this.tasks.length;
  67512. if (this.waitingTasksCount === 0) {
  67513. if (this.onFinish) {
  67514. this.onFinish(this.tasks);
  67515. }
  67516. return this;
  67517. }
  67518. if (this.useDefaultLoadingScreen) {
  67519. this._scene.getEngine().displayLoadingUI();
  67520. }
  67521. for (var index = 0; index < this.tasks.length; index++) {
  67522. var task = this.tasks[index];
  67523. this._runTask(task);
  67524. }
  67525. return this;
  67526. };
  67527. return AssetsManager;
  67528. }());
  67529. BABYLON.AssetsManager = AssetsManager;
  67530. })(BABYLON || (BABYLON = {}));
  67531. //# sourceMappingURL=babylon.assetsManager.js.map
  67532. var BABYLON;
  67533. (function (BABYLON) {
  67534. var MapTexture = (function (_super) {
  67535. __extends(MapTexture, _super);
  67536. function MapTexture(name, scene, size, samplingMode, useMipMap, margin) {
  67537. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67538. if (useMipMap === void 0) { useMipMap = false; }
  67539. if (margin === void 0) { margin = 0; }
  67540. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  67541. _this.name = name;
  67542. _this._size = size;
  67543. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67544. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67545. // Create the rectPackMap that will allocate portion of the texture
  67546. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height), margin);
  67547. // Create the texture that will store the content
  67548. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  67549. return _this;
  67550. }
  67551. /**
  67552. * Allocate a rectangle of a given size in the texture map
  67553. * @param size the size of the rectangle to allocation
  67554. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  67555. */
  67556. MapTexture.prototype.allocateRect = function (size) {
  67557. return this._rectPackingMap.addRect(size);
  67558. };
  67559. /**
  67560. * Free a given rectangle from the texture map
  67561. * @param rectInfo the instance corresponding to the rect to free.
  67562. */
  67563. MapTexture.prototype.freeRect = function (rectInfo) {
  67564. if (rectInfo) {
  67565. rectInfo.freeContent();
  67566. }
  67567. };
  67568. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  67569. /**
  67570. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  67571. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  67572. * @returns {}
  67573. */
  67574. get: function () {
  67575. return this._rectPackingMap.freeSpace;
  67576. },
  67577. enumerable: true,
  67578. configurable: true
  67579. });
  67580. /**
  67581. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  67582. * 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.
  67583. * Don't forget to call unbindTexture when you're done rendering
  67584. * @param rect the zone to render to
  67585. * @param clear true to clear the portion's color/depth data
  67586. */
  67587. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  67588. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  67589. };
  67590. /**
  67591. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  67592. * 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.
  67593. * Don't forget to call unbindTexture when you're done rendering
  67594. * @param pos the position into the texture
  67595. * @param size the portion to fit the clip space to
  67596. * @param clear true to clear the portion's color/depth data
  67597. */
  67598. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  67599. var engine = this.getScene().getEngine();
  67600. engine.bindFramebuffer(this._texture);
  67601. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  67602. if (clear) {
  67603. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  67604. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  67605. }
  67606. };
  67607. /**
  67608. * Unbind the texture map from the rendering engine.
  67609. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  67610. * @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.
  67611. */
  67612. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  67613. // Dump ?
  67614. if (dumpForDebug) {
  67615. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  67616. }
  67617. var engine = this.getScene().getEngine();
  67618. if (this._replacedViewport) {
  67619. engine.setViewport(this._replacedViewport);
  67620. this._replacedViewport = null;
  67621. }
  67622. engine.unBindFramebuffer(this._texture);
  67623. };
  67624. Object.defineProperty(MapTexture.prototype, "canRescale", {
  67625. get: function () {
  67626. return false;
  67627. },
  67628. enumerable: true,
  67629. configurable: true
  67630. });
  67631. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  67632. // Anyway, there's not much point to use this method for this kind of texture I guess
  67633. MapTexture.prototype.clone = function () {
  67634. return null;
  67635. };
  67636. return MapTexture;
  67637. }(BABYLON.Texture));
  67638. BABYLON.MapTexture = MapTexture;
  67639. })(BABYLON || (BABYLON = {}));
  67640. //# sourceMappingURL=babylon.mapTexture.js.map
  67641. var BABYLON;
  67642. (function (BABYLON) {
  67643. /**
  67644. * This class describe a rectangle that were added to the map.
  67645. * You have access to its coordinates either in pixel or normalized (UV)
  67646. */
  67647. var PackedRect = (function () {
  67648. function PackedRect(root, parent, pos, size) {
  67649. this._pos = pos;
  67650. this._size = size;
  67651. this._root = root;
  67652. this._parent = parent;
  67653. this._contentSize = null;
  67654. this._bottomNode = null;
  67655. this._leftNode = null;
  67656. this._initialSize = null;
  67657. this._rightNode = null;
  67658. }
  67659. Object.defineProperty(PackedRect.prototype, "pos", {
  67660. /**
  67661. * @returns the position of this node into the map
  67662. */
  67663. get: function () {
  67664. return this._pos;
  67665. },
  67666. enumerable: true,
  67667. configurable: true
  67668. });
  67669. Object.defineProperty(PackedRect.prototype, "contentSize", {
  67670. /**
  67671. * @returns the size of the rectangle this node handles
  67672. */
  67673. get: function () {
  67674. return this._contentSize;
  67675. },
  67676. enumerable: true,
  67677. configurable: true
  67678. });
  67679. /**
  67680. * Retrieve the inner position (considering the margin) and stores it into the res object
  67681. * @param res must be a valid Vector2 that will contain the inner position after this call
  67682. */
  67683. PackedRect.prototype.getInnerPosToRef = function (res) {
  67684. var m = this._root._margin;
  67685. res.x = this._pos.x + m;
  67686. res.y = this._pos.y + m;
  67687. };
  67688. /**
  67689. * Retrieve the inner size (considering the margin) and stores it into the res object
  67690. * @param res must be a valid Size that will contain the inner size after this call
  67691. */
  67692. PackedRect.prototype.getInnerSizeToRef = function (res) {
  67693. var m = this._root._margin;
  67694. res.width = this._contentSize.width - (m * 2);
  67695. res.height = this._contentSize.height - (m * 2);
  67696. };
  67697. Object.defineProperty(PackedRect.prototype, "UVs", {
  67698. /**
  67699. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  67700. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  67701. */
  67702. get: function () {
  67703. if (!this._contentSize) {
  67704. throw new Error("Can't compute UVs for this object because it's nor allocated");
  67705. }
  67706. return this.getUVsForCustomSize(this._contentSize);
  67707. },
  67708. enumerable: true,
  67709. configurable: true
  67710. });
  67711. /**
  67712. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations)
  67713. * and then using only a part of the PackRect.
  67714. * This method will return the UVs for this part by given the custom size of what you really use
  67715. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  67716. */
  67717. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  67718. var mainWidth = this._root._size.width;
  67719. var mainHeight = this._root._size.height;
  67720. var margin = this._root._margin;
  67721. var topLeft = new BABYLON.Vector2((this._pos.x + margin) / mainWidth, (this._pos.y + margin) / mainHeight);
  67722. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width + margin - 1) / mainWidth, (this._pos.y + customSize.height + margin - 1) / mainHeight);
  67723. var uvs = new Array();
  67724. uvs.push(topLeft);
  67725. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  67726. uvs.push(rightBottom);
  67727. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  67728. return uvs;
  67729. };
  67730. /**
  67731. * Free this rectangle from the map.
  67732. * Call this method when you no longer need the rectangle to be in the map.
  67733. */
  67734. PackedRect.prototype.freeContent = function () {
  67735. if (!this.contentSize) {
  67736. return;
  67737. }
  67738. this._contentSize = null;
  67739. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  67740. this.attemptDefrag();
  67741. };
  67742. Object.defineProperty(PackedRect.prototype, "isUsed", {
  67743. get: function () {
  67744. return this._contentSize != null || this._leftNode != null;
  67745. },
  67746. enumerable: true,
  67747. configurable: true
  67748. });
  67749. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  67750. var node = this.findNode(contentSize);
  67751. // Not enough space...
  67752. if (!node) {
  67753. return null;
  67754. }
  67755. node.splitNode(contentSize);
  67756. return node;
  67757. };
  67758. PackedRect.prototype.findNode = function (size) {
  67759. var resNode = null;
  67760. var margin = this._root._margin * 2;
  67761. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  67762. if (this.isUsed) {
  67763. if (this._leftNode) {
  67764. resNode = this._leftNode.findNode(size);
  67765. }
  67766. if (!resNode && this._rightNode) {
  67767. resNode = this._rightNode.findNode(size);
  67768. }
  67769. if (!resNode && this._bottomNode) {
  67770. resNode = this._bottomNode.findNode(size);
  67771. }
  67772. }
  67773. else if (this._initialSize) {
  67774. if (((size.width + margin) <= this._initialSize.width) && ((size.height + margin) <= this._initialSize.height)) {
  67775. resNode = this;
  67776. }
  67777. else {
  67778. return null;
  67779. }
  67780. }
  67781. else if (((size.width + margin) <= this._size.width) && ((size.height + margin) <= this._size.height)) {
  67782. resNode = this;
  67783. }
  67784. return resNode;
  67785. };
  67786. PackedRect.prototype.splitNode = function (contentSize) {
  67787. var cs = PackedRect.TpsSize;
  67788. var margin = this._root._margin * 2;
  67789. cs.copyFrom(contentSize);
  67790. cs.width += margin;
  67791. cs.height += margin;
  67792. // 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)
  67793. if (!this._contentSize && this._initialSize) {
  67794. this._contentSize = cs.clone();
  67795. 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));
  67796. return this._leftNode.splitNode(contentSize);
  67797. }
  67798. else {
  67799. this._contentSize = cs.clone();
  67800. this._initialSize = cs.clone();
  67801. if (cs.width !== this._size.width) {
  67802. 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));
  67803. }
  67804. if (cs.height !== this._size.height) {
  67805. 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));
  67806. }
  67807. return this;
  67808. }
  67809. };
  67810. PackedRect.prototype.attemptDefrag = function () {
  67811. if (!this.isUsed && this.isRecursiveFree) {
  67812. this.clearNode();
  67813. if (this._parent) {
  67814. this._parent.attemptDefrag();
  67815. }
  67816. }
  67817. };
  67818. PackedRect.prototype.clearNode = function () {
  67819. this._initialSize = null;
  67820. this._rightNode = null;
  67821. this._bottomNode = null;
  67822. };
  67823. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  67824. get: function () {
  67825. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  67826. },
  67827. enumerable: true,
  67828. configurable: true
  67829. });
  67830. PackedRect.prototype.evalFreeSize = function (size) {
  67831. var levelSize = 0;
  67832. if (!this.isUsed) {
  67833. var margin = this._root._margin;
  67834. var is = this._initialSize;
  67835. if (is) {
  67836. levelSize = is.surface - (is.width * margin) - (is.height * margin);
  67837. }
  67838. else {
  67839. var size_1 = this._size;
  67840. levelSize = size_1.surface - (size_1.width * margin) - (size_1.height * margin);
  67841. }
  67842. }
  67843. if (this._rightNode) {
  67844. levelSize += this._rightNode.evalFreeSize(0);
  67845. }
  67846. if (this._bottomNode) {
  67847. levelSize += this._bottomNode.evalFreeSize(0);
  67848. }
  67849. return levelSize + size;
  67850. };
  67851. return PackedRect;
  67852. }());
  67853. PackedRect.TpsSize = BABYLON.Size.Zero();
  67854. BABYLON.PackedRect = PackedRect;
  67855. /**
  67856. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  67857. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  67858. * 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.
  67859. * In case you need a margin around the allocated rect, specify the amount in the margin argument during construction.
  67860. * In such case you will have to rely on innerPositionToRef and innerSizeToRef calls to get the proper size
  67861. */
  67862. var RectPackingMap = (function (_super) {
  67863. __extends(RectPackingMap, _super);
  67864. /**
  67865. * Create an instance of the object with a dimension using the given size
  67866. * @param size The dimension of the rectangle that will contain all the sub ones.
  67867. * @param margin The margin (empty space) created (in pixels) around the allocated Rectangles
  67868. */
  67869. function RectPackingMap(size, margin) {
  67870. if (margin === void 0) { margin = 0; }
  67871. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  67872. _this._margin = margin;
  67873. _this._root = _this;
  67874. return _this;
  67875. }
  67876. /**
  67877. * Add a rectangle, finding the best location to store it into the map
  67878. * @param size the dimension of the rectangle to store
  67879. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  67880. */
  67881. RectPackingMap.prototype.addRect = function (size) {
  67882. var node = this.findAndSplitNode(size);
  67883. return node;
  67884. };
  67885. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  67886. /**
  67887. * Return the current space free normalized between [0;1]
  67888. * @returns {}
  67889. */
  67890. get: function () {
  67891. var freeSize = 0;
  67892. freeSize = this.evalFreeSize(freeSize);
  67893. return freeSize / (this._size.width * this._size.height);
  67894. },
  67895. enumerable: true,
  67896. configurable: true
  67897. });
  67898. return RectPackingMap;
  67899. }(PackedRect));
  67900. BABYLON.RectPackingMap = RectPackingMap;
  67901. })(BABYLON || (BABYLON = {}));
  67902. //# sourceMappingURL=babylon.rectPackingMap.js.map
  67903. var BABYLON;
  67904. (function (BABYLON) {
  67905. /**
  67906. * This groups together the common properties used for image processing either in direct forward pass
  67907. * or through post processing effect depending on the use of the image processing pipeline in your scene
  67908. * or not.
  67909. */
  67910. var ImageProcessingConfiguration = (function () {
  67911. function ImageProcessingConfiguration() {
  67912. /**
  67913. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  67914. */
  67915. this.colorCurves = new BABYLON.ColorCurves();
  67916. this._colorCurvesEnabled = false;
  67917. this._colorGradingEnabled = false;
  67918. this._colorGradingWithGreenDepth = false;
  67919. this._colorGradingBGR = false;
  67920. this._exposure = 1.0;
  67921. this._toneMappingEnabled = false;
  67922. this._contrast = 1.0;
  67923. /**
  67924. * Vignette stretch size.
  67925. */
  67926. this.vignetteStretch = 0;
  67927. /**
  67928. * Vignette centre X Offset.
  67929. */
  67930. this.vignetteCentreX = 0;
  67931. /**
  67932. * Vignette centre Y Offset.
  67933. */
  67934. this.vignetteCentreY = 0;
  67935. /**
  67936. * Vignette weight or intensity of the vignette effect.
  67937. */
  67938. this.vignetteWeight = 1.5;
  67939. /**
  67940. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  67941. * if vignetteEnabled is set to true.
  67942. */
  67943. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  67944. /**
  67945. * Camera field of view used by the Vignette effect.
  67946. */
  67947. this.vignetteCameraFov = 0.5;
  67948. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  67949. this._vignetteEnabled = false;
  67950. this._applyByPostProcess = false;
  67951. /**
  67952. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  67953. * @type {BABYLON.Observable}
  67954. */
  67955. this.onUpdateParameters = new BABYLON.Observable();
  67956. }
  67957. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  67958. /**
  67959. * Gets wether the color curves effect is enabled.
  67960. */
  67961. get: function () {
  67962. return this._colorCurvesEnabled;
  67963. },
  67964. /**
  67965. * Sets wether the color curves effect is enabled.
  67966. */
  67967. set: function (value) {
  67968. if (this._colorCurvesEnabled === value) {
  67969. return;
  67970. }
  67971. this._colorCurvesEnabled = value;
  67972. this._updateParameters();
  67973. },
  67974. enumerable: true,
  67975. configurable: true
  67976. });
  67977. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  67978. /**
  67979. * Gets wether the color grading effect is enabled.
  67980. */
  67981. get: function () {
  67982. return this._colorGradingEnabled;
  67983. },
  67984. /**
  67985. * Sets wether the color grading effect is enabled.
  67986. */
  67987. set: function (value) {
  67988. if (this._colorGradingEnabled === value) {
  67989. return;
  67990. }
  67991. this._colorGradingEnabled = value;
  67992. this._updateParameters();
  67993. },
  67994. enumerable: true,
  67995. configurable: true
  67996. });
  67997. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  67998. /**
  67999. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  68000. */
  68001. get: function () {
  68002. return this._colorGradingWithGreenDepth;
  68003. },
  68004. /**
  68005. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  68006. */
  68007. set: function (value) {
  68008. if (this._colorGradingWithGreenDepth === value) {
  68009. return;
  68010. }
  68011. this._colorGradingWithGreenDepth = value;
  68012. this._updateParameters();
  68013. },
  68014. enumerable: true,
  68015. configurable: true
  68016. });
  68017. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  68018. /**
  68019. * Gets wether the color grading texture contains BGR values.
  68020. */
  68021. get: function () {
  68022. return this._colorGradingBGR;
  68023. },
  68024. /**
  68025. * Sets wether the color grading texture contains BGR values.
  68026. */
  68027. set: function (value) {
  68028. if (this._colorGradingBGR === value) {
  68029. return;
  68030. }
  68031. this._colorGradingBGR = value;
  68032. this._updateParameters();
  68033. },
  68034. enumerable: true,
  68035. configurable: true
  68036. });
  68037. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  68038. /**
  68039. * Gets the Exposure used in the effect.
  68040. */
  68041. get: function () {
  68042. return this._exposure;
  68043. },
  68044. /**
  68045. * Sets the Exposure used in the effect.
  68046. */
  68047. set: function (value) {
  68048. if (this._exposure === value) {
  68049. return;
  68050. }
  68051. this._exposure = value;
  68052. this._updateParameters();
  68053. },
  68054. enumerable: true,
  68055. configurable: true
  68056. });
  68057. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  68058. /**
  68059. * Gets wether the tone mapping effect is enabled.
  68060. */
  68061. get: function () {
  68062. return this._toneMappingEnabled;
  68063. },
  68064. /**
  68065. * Sets wether the tone mapping effect is enabled.
  68066. */
  68067. set: function (value) {
  68068. if (this._toneMappingEnabled === value) {
  68069. return;
  68070. }
  68071. this._toneMappingEnabled = value;
  68072. this._updateParameters();
  68073. },
  68074. enumerable: true,
  68075. configurable: true
  68076. });
  68077. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  68078. /**
  68079. * Gets the contrast used in the effect.
  68080. */
  68081. get: function () {
  68082. return this._contrast;
  68083. },
  68084. /**
  68085. * Sets the contrast used in the effect.
  68086. */
  68087. set: function (value) {
  68088. if (this._contrast === value) {
  68089. return;
  68090. }
  68091. this._contrast = value;
  68092. this._updateParameters();
  68093. },
  68094. enumerable: true,
  68095. configurable: true
  68096. });
  68097. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  68098. /**
  68099. * Gets the vignette blend mode allowing different kind of effect.
  68100. */
  68101. get: function () {
  68102. return this._vignetteBlendMode;
  68103. },
  68104. /**
  68105. * Sets the vignette blend mode allowing different kind of effect.
  68106. */
  68107. set: function (value) {
  68108. if (this._vignetteBlendMode === value) {
  68109. return;
  68110. }
  68111. this._vignetteBlendMode = value;
  68112. this._updateParameters();
  68113. },
  68114. enumerable: true,
  68115. configurable: true
  68116. });
  68117. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  68118. /**
  68119. * Gets wether the vignette effect is enabled.
  68120. */
  68121. get: function () {
  68122. return this._vignetteEnabled;
  68123. },
  68124. /**
  68125. * Sets wether the vignette effect is enabled.
  68126. */
  68127. set: function (value) {
  68128. if (this._vignetteEnabled === value) {
  68129. return;
  68130. }
  68131. this._vignetteEnabled = value;
  68132. this._updateParameters();
  68133. },
  68134. enumerable: true,
  68135. configurable: true
  68136. });
  68137. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  68138. /**
  68139. * Gets wether the image processing is applied through a post process or not.
  68140. */
  68141. get: function () {
  68142. return this._applyByPostProcess;
  68143. },
  68144. /**
  68145. * Sets wether the image processing is applied through a post process or not.
  68146. */
  68147. set: function (value) {
  68148. if (this._applyByPostProcess === value) {
  68149. return;
  68150. }
  68151. this._applyByPostProcess = value;
  68152. this._updateParameters();
  68153. },
  68154. enumerable: true,
  68155. configurable: true
  68156. });
  68157. /**
  68158. * Method called each time the image processing information changes requires to recompile the effect.
  68159. */
  68160. ImageProcessingConfiguration.prototype._updateParameters = function () {
  68161. this.onUpdateParameters.notifyObservers(this);
  68162. };
  68163. ImageProcessingConfiguration.prototype.getClassName = function () {
  68164. return "ImageProcessingConfiguration";
  68165. };
  68166. /**
  68167. * Prepare the list of uniforms associated with the Image Processing effects.
  68168. * @param uniformsList The list of uniforms used in the effect
  68169. * @param defines the list of defines currently in use
  68170. */
  68171. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  68172. if (defines.EXPOSURE) {
  68173. uniforms.push("exposureLinear");
  68174. }
  68175. if (defines.CONTRAST) {
  68176. uniforms.push("contrast");
  68177. }
  68178. if (defines.COLORGRADING) {
  68179. uniforms.push("colorTransformSettings");
  68180. }
  68181. if (defines.VIGNETTE) {
  68182. uniforms.push("vInverseScreenSize");
  68183. uniforms.push("vignetteSettings1");
  68184. uniforms.push("vignetteSettings2");
  68185. }
  68186. if (defines.COLORCURVES) {
  68187. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  68188. }
  68189. };
  68190. /**
  68191. * Prepare the list of samplers associated with the Image Processing effects.
  68192. * @param uniformsList The list of uniforms used in the effect
  68193. * @param defines the list of defines currently in use
  68194. */
  68195. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  68196. if (defines.COLORGRADING) {
  68197. samplersList.push("txColorTransform");
  68198. }
  68199. };
  68200. /**
  68201. * Prepare the list of defines associated to the shader.
  68202. * @param defines the list of defines to complete
  68203. */
  68204. ImageProcessingConfiguration.prototype.prepareDefines = function (defines) {
  68205. defines.VIGNETTE = this.vignetteEnabled;
  68206. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  68207. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  68208. defines.TONEMAPPING = this.toneMappingEnabled;
  68209. defines.CONTRAST = (this.contrast !== 1.0);
  68210. defines.EXPOSURE = (this.exposure !== 1.0);
  68211. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  68212. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  68213. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  68214. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  68215. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  68216. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  68217. };
  68218. /**
  68219. * Returns true if all the image processing information are ready.
  68220. */
  68221. ImageProcessingConfiguration.prototype.isReady = function () {
  68222. // Color Grading texure can not be none blocking.
  68223. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  68224. };
  68225. /**
  68226. * Binds the image processing to the shader.
  68227. * @param effect The effect to bind to
  68228. */
  68229. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  68230. if (aspectRatio === void 0) { aspectRatio = 1; }
  68231. // Color Curves
  68232. if (this._colorCurvesEnabled) {
  68233. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  68234. }
  68235. // Vignette
  68236. if (this._vignetteEnabled) {
  68237. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  68238. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  68239. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  68240. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  68241. var vignetteScaleX = vignetteScaleY * aspectRatio;
  68242. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  68243. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  68244. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  68245. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  68246. var vignettePower = -2.0 * this.vignetteWeight;
  68247. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  68248. }
  68249. // Exposure
  68250. effect.setFloat("exposureLinear", this.exposure);
  68251. // Contrast
  68252. effect.setFloat("contrast", this.contrast);
  68253. // Color transform settings
  68254. if (this.colorGradingTexture) {
  68255. effect.setTexture("txColorTransform", this.colorGradingTexture);
  68256. var textureSize = this.colorGradingTexture.getSize().height;
  68257. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  68258. 0.5 / textureSize, // textureOffset
  68259. textureSize, // textureSize
  68260. this.colorGradingTexture.level // weight
  68261. );
  68262. }
  68263. };
  68264. /**
  68265. * Clones the current image processing instance.
  68266. * @return The cloned image processing
  68267. */
  68268. ImageProcessingConfiguration.prototype.clone = function () {
  68269. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  68270. };
  68271. /**
  68272. * Serializes the current image processing instance to a json representation.
  68273. * @return a JSON representation
  68274. */
  68275. ImageProcessingConfiguration.prototype.serialize = function () {
  68276. return BABYLON.SerializationHelper.Serialize(this);
  68277. };
  68278. /**
  68279. * Parses the image processing from a json representation.
  68280. * @param source the JSON source to parse
  68281. * @return The parsed image processing
  68282. */
  68283. ImageProcessingConfiguration.Parse = function (source) {
  68284. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  68285. };
  68286. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  68287. /**
  68288. * Used to apply the vignette as a mix with the pixel color.
  68289. */
  68290. get: function () {
  68291. return this._VIGNETTEMODE_MULTIPLY;
  68292. },
  68293. enumerable: true,
  68294. configurable: true
  68295. });
  68296. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  68297. /**
  68298. * Used to apply the vignette as a replacement of the pixel color.
  68299. */
  68300. get: function () {
  68301. return this._VIGNETTEMODE_OPAQUE;
  68302. },
  68303. enumerable: true,
  68304. configurable: true
  68305. });
  68306. return ImageProcessingConfiguration;
  68307. }());
  68308. // Static constants associated to the image processing.
  68309. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  68310. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  68311. __decorate([
  68312. BABYLON.serializeAsColorCurves()
  68313. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  68314. __decorate([
  68315. BABYLON.serialize()
  68316. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  68317. __decorate([
  68318. BABYLON.serializeAsTexture()
  68319. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  68320. __decorate([
  68321. BABYLON.serialize()
  68322. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  68323. __decorate([
  68324. BABYLON.serialize()
  68325. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  68326. __decorate([
  68327. BABYLON.serialize()
  68328. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  68329. __decorate([
  68330. BABYLON.serialize()
  68331. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  68332. __decorate([
  68333. BABYLON.serialize()
  68334. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  68335. __decorate([
  68336. BABYLON.serialize()
  68337. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  68338. __decorate([
  68339. BABYLON.serialize()
  68340. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  68341. __decorate([
  68342. BABYLON.serialize()
  68343. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  68344. __decorate([
  68345. BABYLON.serialize()
  68346. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  68347. __decorate([
  68348. BABYLON.serialize()
  68349. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  68350. __decorate([
  68351. BABYLON.serializeAsColor4()
  68352. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  68353. __decorate([
  68354. BABYLON.serialize()
  68355. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  68356. __decorate([
  68357. BABYLON.serialize()
  68358. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  68359. __decorate([
  68360. BABYLON.serialize()
  68361. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  68362. __decorate([
  68363. BABYLON.serialize()
  68364. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  68365. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  68366. })(BABYLON || (BABYLON = {}));
  68367. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  68368. var BABYLON;
  68369. (function (BABYLON) {
  68370. var serializedGeometries = [];
  68371. var serializeGeometry = function (geometry, serializationGeometries) {
  68372. if (serializedGeometries[geometry.id]) {
  68373. return;
  68374. }
  68375. if (geometry.doNotSerialize) {
  68376. return;
  68377. }
  68378. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  68379. serializationGeometries.boxes.push(geometry.serialize());
  68380. }
  68381. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  68382. serializationGeometries.spheres.push(geometry.serialize());
  68383. }
  68384. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  68385. serializationGeometries.cylinders.push(geometry.serialize());
  68386. }
  68387. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  68388. serializationGeometries.toruses.push(geometry.serialize());
  68389. }
  68390. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  68391. serializationGeometries.grounds.push(geometry.serialize());
  68392. }
  68393. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  68394. serializationGeometries.planes.push(geometry.serialize());
  68395. }
  68396. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  68397. serializationGeometries.torusKnots.push(geometry.serialize());
  68398. }
  68399. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  68400. throw new Error("Unknown primitive type");
  68401. }
  68402. else {
  68403. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  68404. }
  68405. serializedGeometries[geometry.id] = true;
  68406. };
  68407. var serializeMesh = function (mesh, serializationScene) {
  68408. var serializationObject = {};
  68409. // Geometry
  68410. var geometry = mesh._geometry;
  68411. if (geometry) {
  68412. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  68413. // 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
  68414. serializeGeometry(geometry, serializationScene.geometries);
  68415. }
  68416. }
  68417. // Custom
  68418. if (mesh.serialize) {
  68419. mesh.serialize(serializationObject);
  68420. }
  68421. return serializationObject;
  68422. };
  68423. var finalizeSingleMesh = function (mesh, serializationObject) {
  68424. //only works if the mesh is already loaded
  68425. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  68426. //serialize material
  68427. if (mesh.material) {
  68428. if (mesh.material instanceof BABYLON.StandardMaterial) {
  68429. serializationObject.materials = serializationObject.materials || [];
  68430. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  68431. serializationObject.materials.push(mesh.material.serialize());
  68432. }
  68433. }
  68434. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  68435. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  68436. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  68437. serializationObject.multiMaterials.push(mesh.material.serialize());
  68438. }
  68439. }
  68440. }
  68441. //serialize geometry
  68442. var geometry = mesh._geometry;
  68443. if (geometry) {
  68444. if (!serializationObject.geometries) {
  68445. serializationObject.geometries = {};
  68446. serializationObject.geometries.boxes = [];
  68447. serializationObject.geometries.spheres = [];
  68448. serializationObject.geometries.cylinders = [];
  68449. serializationObject.geometries.toruses = [];
  68450. serializationObject.geometries.grounds = [];
  68451. serializationObject.geometries.planes = [];
  68452. serializationObject.geometries.torusKnots = [];
  68453. serializationObject.geometries.vertexData = [];
  68454. }
  68455. serializeGeometry(geometry, serializationObject.geometries);
  68456. }
  68457. // Skeletons
  68458. if (mesh.skeleton) {
  68459. serializationObject.skeletons = serializationObject.skeletons || [];
  68460. serializationObject.skeletons.push(mesh.skeleton.serialize());
  68461. }
  68462. //serialize the actual mesh
  68463. serializationObject.meshes = serializationObject.meshes || [];
  68464. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  68465. }
  68466. };
  68467. var SceneSerializer = (function () {
  68468. function SceneSerializer() {
  68469. }
  68470. SceneSerializer.ClearCache = function () {
  68471. serializedGeometries = [];
  68472. };
  68473. SceneSerializer.Serialize = function (scene) {
  68474. var serializationObject = {};
  68475. SceneSerializer.ClearCache();
  68476. // Scene
  68477. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  68478. serializationObject.autoClear = scene.autoClear;
  68479. serializationObject.clearColor = scene.clearColor.asArray();
  68480. serializationObject.ambientColor = scene.ambientColor.asArray();
  68481. serializationObject.gravity = scene.gravity.asArray();
  68482. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  68483. serializationObject.workerCollisions = scene.workerCollisions;
  68484. // Fog
  68485. if (scene.fogMode && scene.fogMode !== 0) {
  68486. serializationObject.fogMode = scene.fogMode;
  68487. serializationObject.fogColor = scene.fogColor.asArray();
  68488. serializationObject.fogStart = scene.fogStart;
  68489. serializationObject.fogEnd = scene.fogEnd;
  68490. serializationObject.fogDensity = scene.fogDensity;
  68491. }
  68492. //Physics
  68493. if (scene.isPhysicsEnabled()) {
  68494. serializationObject.physicsEnabled = true;
  68495. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  68496. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  68497. }
  68498. // Metadata
  68499. if (scene.metadata) {
  68500. serializationObject.metadata = scene.metadata;
  68501. }
  68502. // Morph targets
  68503. serializationObject.morphTargetManagers = [];
  68504. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  68505. var abstractMesh = _a[_i];
  68506. var manager = abstractMesh.morphTargetManager;
  68507. if (manager) {
  68508. serializationObject.morphTargetManagers.push(manager.serialize());
  68509. }
  68510. }
  68511. // Lights
  68512. serializationObject.lights = [];
  68513. var index;
  68514. var light;
  68515. for (index = 0; index < scene.lights.length; index++) {
  68516. light = scene.lights[index];
  68517. if (!light.doNotSerialize) {
  68518. serializationObject.lights.push(light.serialize());
  68519. }
  68520. }
  68521. // Cameras
  68522. serializationObject.cameras = [];
  68523. for (index = 0; index < scene.cameras.length; index++) {
  68524. var camera = scene.cameras[index];
  68525. if (!camera.doNotSerialize) {
  68526. serializationObject.cameras.push(camera.serialize());
  68527. }
  68528. }
  68529. if (scene.activeCamera) {
  68530. serializationObject.activeCameraID = scene.activeCamera.id;
  68531. }
  68532. // Animations
  68533. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  68534. // Materials
  68535. serializationObject.materials = [];
  68536. serializationObject.multiMaterials = [];
  68537. var material;
  68538. for (index = 0; index < scene.materials.length; index++) {
  68539. material = scene.materials[index];
  68540. if (!material.doNotSerialize) {
  68541. serializationObject.materials.push(material.serialize());
  68542. }
  68543. }
  68544. // MultiMaterials
  68545. serializationObject.multiMaterials = [];
  68546. for (index = 0; index < scene.multiMaterials.length; index++) {
  68547. var multiMaterial = scene.multiMaterials[index];
  68548. serializationObject.multiMaterials.push(multiMaterial.serialize());
  68549. }
  68550. // Skeletons
  68551. serializationObject.skeletons = [];
  68552. for (index = 0; index < scene.skeletons.length; index++) {
  68553. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  68554. }
  68555. // Geometries
  68556. serializationObject.geometries = {};
  68557. serializationObject.geometries.boxes = [];
  68558. serializationObject.geometries.spheres = [];
  68559. serializationObject.geometries.cylinders = [];
  68560. serializationObject.geometries.toruses = [];
  68561. serializationObject.geometries.grounds = [];
  68562. serializationObject.geometries.planes = [];
  68563. serializationObject.geometries.torusKnots = [];
  68564. serializationObject.geometries.vertexData = [];
  68565. serializedGeometries = [];
  68566. var geometries = scene.getGeometries();
  68567. for (index = 0; index < geometries.length; index++) {
  68568. var geometry = geometries[index];
  68569. if (geometry.isReady()) {
  68570. serializeGeometry(geometry, serializationObject.geometries);
  68571. }
  68572. }
  68573. // Meshes
  68574. serializationObject.meshes = [];
  68575. for (index = 0; index < scene.meshes.length; index++) {
  68576. var abstractMesh = scene.meshes[index];
  68577. if (abstractMesh instanceof BABYLON.Mesh) {
  68578. var mesh = abstractMesh;
  68579. if (!mesh.doNotSerialize) {
  68580. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  68581. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  68582. }
  68583. }
  68584. }
  68585. }
  68586. // Particles Systems
  68587. serializationObject.particleSystems = [];
  68588. for (index = 0; index < scene.particleSystems.length; index++) {
  68589. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  68590. }
  68591. // Lens flares
  68592. serializationObject.lensFlareSystems = [];
  68593. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  68594. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  68595. }
  68596. // Shadows
  68597. serializationObject.shadowGenerators = [];
  68598. for (index = 0; index < scene.lights.length; index++) {
  68599. light = scene.lights[index];
  68600. var shadowGenerator = light.getShadowGenerator();
  68601. if (shadowGenerator) {
  68602. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  68603. }
  68604. }
  68605. // Action Manager
  68606. if (scene.actionManager) {
  68607. serializationObject.actions = scene.actionManager.serialize("scene");
  68608. }
  68609. // Audio
  68610. serializationObject.sounds = [];
  68611. for (index = 0; index < scene.soundTracks.length; index++) {
  68612. var soundtrack = scene.soundTracks[index];
  68613. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  68614. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  68615. }
  68616. }
  68617. return serializationObject;
  68618. };
  68619. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  68620. if (withParents === void 0) { withParents = false; }
  68621. if (withChildren === void 0) { withChildren = false; }
  68622. var serializationObject = {};
  68623. SceneSerializer.ClearCache();
  68624. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  68625. if (withParents || withChildren) {
  68626. //deliberate for loop! not for each, appended should be processed as well.
  68627. for (var i = 0; i < toSerialize.length; ++i) {
  68628. if (withChildren) {
  68629. toSerialize[i].getDescendants().forEach(function (node) {
  68630. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  68631. toSerialize.push(node);
  68632. }
  68633. });
  68634. }
  68635. //make sure the array doesn't contain the object already
  68636. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  68637. toSerialize.push(toSerialize[i].parent);
  68638. }
  68639. }
  68640. }
  68641. toSerialize.forEach(function (mesh) {
  68642. finalizeSingleMesh(mesh, serializationObject);
  68643. });
  68644. return serializationObject;
  68645. };
  68646. return SceneSerializer;
  68647. }());
  68648. BABYLON.SceneSerializer = SceneSerializer;
  68649. })(BABYLON || (BABYLON = {}));
  68650. //# sourceMappingURL=babylon.sceneSerializer.js.map
  68651. var BABYLON;
  68652. (function (BABYLON) {
  68653. var ReflectionProbe = (function () {
  68654. function ReflectionProbe(name, size, scene, generateMipMaps) {
  68655. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68656. var _this = this;
  68657. this.name = name;
  68658. this._viewMatrix = BABYLON.Matrix.Identity();
  68659. this._target = BABYLON.Vector3.Zero();
  68660. this._add = BABYLON.Vector3.Zero();
  68661. this.invertYAxis = false;
  68662. this.position = BABYLON.Vector3.Zero();
  68663. this._scene = scene;
  68664. this._scene.reflectionProbes.push(this);
  68665. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  68666. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  68667. switch (faceIndex) {
  68668. case 0:
  68669. _this._add.copyFromFloats(1, 0, 0);
  68670. break;
  68671. case 1:
  68672. _this._add.copyFromFloats(-1, 0, 0);
  68673. break;
  68674. case 2:
  68675. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  68676. break;
  68677. case 3:
  68678. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  68679. break;
  68680. case 4:
  68681. _this._add.copyFromFloats(0, 0, 1);
  68682. break;
  68683. case 5:
  68684. _this._add.copyFromFloats(0, 0, -1);
  68685. break;
  68686. }
  68687. if (_this._attachedMesh) {
  68688. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  68689. }
  68690. _this.position.addToRef(_this._add, _this._target);
  68691. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  68692. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  68693. });
  68694. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  68695. scene.updateTransformMatrix(true);
  68696. });
  68697. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  68698. }
  68699. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  68700. get: function () {
  68701. return this._renderTargetTexture.samples;
  68702. },
  68703. set: function (value) {
  68704. this._renderTargetTexture.samples = value;
  68705. },
  68706. enumerable: true,
  68707. configurable: true
  68708. });
  68709. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  68710. get: function () {
  68711. return this._renderTargetTexture.refreshRate;
  68712. },
  68713. set: function (value) {
  68714. this._renderTargetTexture.refreshRate = value;
  68715. },
  68716. enumerable: true,
  68717. configurable: true
  68718. });
  68719. ReflectionProbe.prototype.getScene = function () {
  68720. return this._scene;
  68721. };
  68722. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  68723. get: function () {
  68724. return this._renderTargetTexture;
  68725. },
  68726. enumerable: true,
  68727. configurable: true
  68728. });
  68729. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  68730. get: function () {
  68731. return this._renderTargetTexture.renderList;
  68732. },
  68733. enumerable: true,
  68734. configurable: true
  68735. });
  68736. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  68737. this._attachedMesh = mesh;
  68738. };
  68739. /**
  68740. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  68741. *
  68742. * @param renderingGroupId The rendering group id corresponding to its index
  68743. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  68744. */
  68745. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  68746. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  68747. };
  68748. ReflectionProbe.prototype.dispose = function () {
  68749. var index = this._scene.reflectionProbes.indexOf(this);
  68750. if (index !== -1) {
  68751. // Remove from the scene if found
  68752. this._scene.reflectionProbes.splice(index, 1);
  68753. }
  68754. if (this._renderTargetTexture) {
  68755. this._renderTargetTexture.dispose();
  68756. this._renderTargetTexture = null;
  68757. }
  68758. };
  68759. return ReflectionProbe;
  68760. }());
  68761. BABYLON.ReflectionProbe = ReflectionProbe;
  68762. })(BABYLON || (BABYLON = {}));
  68763. //# sourceMappingURL=babylon.reflectionProbe.js.map
  68764. var BABYLON;
  68765. (function (BABYLON) {
  68766. var Layer = (function () {
  68767. function Layer(name, imgUrl, scene, isBackground, color) {
  68768. this.name = name;
  68769. this.scale = new BABYLON.Vector2(1, 1);
  68770. this.offset = new BABYLON.Vector2(0, 0);
  68771. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  68772. this.layerMask = 0x0FFFFFFF;
  68773. this._vertexBuffers = {};
  68774. // Events
  68775. /**
  68776. * An event triggered when the layer is disposed.
  68777. * @type {BABYLON.Observable}
  68778. */
  68779. this.onDisposeObservable = new BABYLON.Observable();
  68780. /**
  68781. * An event triggered before rendering the scene
  68782. * @type {BABYLON.Observable}
  68783. */
  68784. this.onBeforeRenderObservable = new BABYLON.Observable();
  68785. /**
  68786. * An event triggered after rendering the scene
  68787. * @type {BABYLON.Observable}
  68788. */
  68789. this.onAfterRenderObservable = new BABYLON.Observable();
  68790. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  68791. this.isBackground = isBackground === undefined ? true : isBackground;
  68792. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  68793. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  68794. this._scene.layers.push(this);
  68795. var engine = this._scene.getEngine();
  68796. // VBO
  68797. var vertices = [];
  68798. vertices.push(1, 1);
  68799. vertices.push(-1, 1);
  68800. vertices.push(-1, -1);
  68801. vertices.push(1, -1);
  68802. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  68803. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  68804. // Indices
  68805. var indices = [];
  68806. indices.push(0);
  68807. indices.push(1);
  68808. indices.push(2);
  68809. indices.push(0);
  68810. indices.push(2);
  68811. indices.push(3);
  68812. this._indexBuffer = engine.createIndexBuffer(indices);
  68813. // Effects
  68814. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  68815. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  68816. }
  68817. Object.defineProperty(Layer.prototype, "onDispose", {
  68818. set: function (callback) {
  68819. if (this._onDisposeObserver) {
  68820. this.onDisposeObservable.remove(this._onDisposeObserver);
  68821. }
  68822. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  68823. },
  68824. enumerable: true,
  68825. configurable: true
  68826. });
  68827. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  68828. set: function (callback) {
  68829. if (this._onBeforeRenderObserver) {
  68830. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  68831. }
  68832. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  68833. },
  68834. enumerable: true,
  68835. configurable: true
  68836. });
  68837. Object.defineProperty(Layer.prototype, "onAfterRender", {
  68838. set: function (callback) {
  68839. if (this._onAfterRenderObserver) {
  68840. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  68841. }
  68842. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  68843. },
  68844. enumerable: true,
  68845. configurable: true
  68846. });
  68847. Layer.prototype.render = function () {
  68848. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  68849. // Check
  68850. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  68851. return;
  68852. var engine = this._scene.getEngine();
  68853. this.onBeforeRenderObservable.notifyObservers(this);
  68854. // Render
  68855. engine.enableEffect(currentEffect);
  68856. engine.setState(false);
  68857. // Texture
  68858. currentEffect.setTexture("textureSampler", this.texture);
  68859. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  68860. // Color
  68861. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  68862. // Scale / offset
  68863. currentEffect.setVector2("offset", this.offset);
  68864. currentEffect.setVector2("scale", this.scale);
  68865. // VBOs
  68866. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  68867. // Draw order
  68868. if (!this.alphaTest) {
  68869. engine.setAlphaMode(this.alphaBlendingMode);
  68870. engine.draw(true, 0, 6);
  68871. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  68872. }
  68873. else {
  68874. engine.draw(true, 0, 6);
  68875. }
  68876. this.onAfterRenderObservable.notifyObservers(this);
  68877. };
  68878. Layer.prototype.dispose = function () {
  68879. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68880. if (vertexBuffer) {
  68881. vertexBuffer.dispose();
  68882. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  68883. }
  68884. if (this._indexBuffer) {
  68885. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  68886. this._indexBuffer = null;
  68887. }
  68888. if (this.texture) {
  68889. this.texture.dispose();
  68890. this.texture = null;
  68891. }
  68892. // Remove from scene
  68893. var index = this._scene.layers.indexOf(this);
  68894. this._scene.layers.splice(index, 1);
  68895. // Callback
  68896. this.onDisposeObservable.notifyObservers(this);
  68897. this.onDisposeObservable.clear();
  68898. this.onAfterRenderObservable.clear();
  68899. this.onBeforeRenderObservable.clear();
  68900. };
  68901. return Layer;
  68902. }());
  68903. BABYLON.Layer = Layer;
  68904. })(BABYLON || (BABYLON = {}));
  68905. //# sourceMappingURL=babylon.layer.js.map
  68906. var BABYLON;
  68907. (function (BABYLON) {
  68908. var TextureTools = (function () {
  68909. function TextureTools() {
  68910. }
  68911. /**
  68912. * Uses the GPU to create a copy texture rescaled at a given size
  68913. * @param texture Texture to copy from
  68914. * @param width Desired width
  68915. * @param height Desired height
  68916. * @return Generated texture
  68917. */
  68918. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  68919. if (useBilinearMode === void 0) { useBilinearMode = true; }
  68920. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  68921. var scene = texture.getScene();
  68922. var engine = scene.getEngine();
  68923. rtt.wrapU = texture.wrapU;
  68924. rtt.wrapV = texture.wrapV;
  68925. rtt.uOffset = texture.uOffset;
  68926. rtt.vOffset = texture.vOffset;
  68927. rtt.uScale = texture.uScale;
  68928. rtt.vScale = texture.vScale;
  68929. rtt.uAng = texture.uAng;
  68930. rtt.vAng = texture.vAng;
  68931. rtt.wAng = texture.wAng;
  68932. rtt.coordinatesIndex = texture.coordinatesIndex;
  68933. rtt.level = texture.level;
  68934. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  68935. rtt._texture.isReady = false;
  68936. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68937. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68938. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  68939. passPostProcess.getEffect().executeWhenCompiled(function () {
  68940. passPostProcess.onApply = function (effect) {
  68941. effect.setTexture("textureSampler", texture);
  68942. };
  68943. scene.postProcessManager.directRender([passPostProcess], rtt.getInternalTexture());
  68944. engine.unBindFramebuffer(rtt.getInternalTexture());
  68945. rtt.disposeFramebufferObjects();
  68946. passPostProcess.dispose();
  68947. rtt._texture.isReady = true;
  68948. });
  68949. return rtt;
  68950. };
  68951. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  68952. if (!scene._environmentBRDFTexture) {
  68953. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68954. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68955. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68956. scene._environmentBRDFTexture = texture;
  68957. }
  68958. return scene._environmentBRDFTexture;
  68959. };
  68960. return TextureTools;
  68961. }());
  68962. 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=";
  68963. BABYLON.TextureTools = TextureTools;
  68964. })(BABYLON || (BABYLON = {}));
  68965. //# sourceMappingURL=babylon.textureTools.js.map
  68966. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#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#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(texture(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(texture(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":"#version 300 es\nprecision highp float;\nprecision highp int;\n#include<bones300Declaration>\n#include<instances300Declaration>\nin vec3 position;\nin vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nout vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nin vec2 uv;\n#endif\n#ifdef UV2\nin vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nout vec3 vNormalV;\nout vec4 vViewPos;\n#ifdef POSITION\nout 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":"#version 300 es\nprecision highp float;\nprecision highp int;\nin vec3 vNormalV;\nin vec4 vViewPos;\n#ifdef POSITION\nin vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nin vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nlayout(location=0) out vec4 color0;\nlayout(location=1) out vec4 color1;\n#ifdef POSITION\nlayout(location=2) out vec4 color2;\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ncolor0=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\ncolor1=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ncolor2=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\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}\n","outlinePixelShader":"uniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\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}"};
  68967. BABYLON.Effect.IncludesShadersStore={"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}","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};"};
  68968. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  68969. module.exports = BABYLON;
  68970. };