babylon.max.js 3.4 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365
  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. Matrix._tempQuaternion = new Quaternion();
  3833. Matrix._xAxis = Vector3.Zero();
  3834. Matrix._yAxis = Vector3.Zero();
  3835. Matrix._zAxis = Vector3.Zero();
  3836. Matrix._updateFlagSeed = 0;
  3837. return Matrix;
  3838. }());
  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.getRenderWidth) {
  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. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4084. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4085. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4086. return Axis;
  4087. }());
  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. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4644. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4645. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4646. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4647. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4648. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4649. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4650. Matrix.Zero(), Matrix.Zero(),
  4651. Matrix.Zero(), Matrix.Zero(),
  4652. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4653. return Tmp;
  4654. }());
  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. MathTmp.Vector3 = [Vector3.Zero()];
  4661. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4662. MathTmp.Quaternion = [Quaternion.Zero()];
  4663. return MathTmp;
  4664. }());
  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:// Mesh reference
  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:// Color Curves
  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:// Value
  5049. serializationObject[targetPropertyName] = sourceProperty;
  5050. break;
  5051. case 1:// Texture
  5052. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5053. break;
  5054. case 2:// Color3
  5055. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5056. break;
  5057. case 3:// FresnelParameters
  5058. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5059. break;
  5060. case 4:// Vector2
  5061. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5062. break;
  5063. case 5:// Vector3
  5064. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5065. break;
  5066. case 6:// Mesh reference
  5067. serializationObject[targetPropertyName] = sourceProperty.id;
  5068. break;
  5069. case 7:// Color Curves
  5070. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5071. break;
  5072. case 8:// Color 4
  5073. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5074. break;
  5075. case 9:// Image Processing
  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:// Value
  5098. destination[property] = sourceProperty;
  5099. break;
  5100. case 1:// Texture
  5101. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  5102. break;
  5103. case 2:// Color3
  5104. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  5105. break;
  5106. case 3:// FresnelParameters
  5107. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  5108. break;
  5109. case 4:// Vector2
  5110. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  5111. break;
  5112. case 5:// Vector3
  5113. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  5114. break;
  5115. case 6:// Mesh reference
  5116. destination[property] = scene.getLastMeshByID(sourceProperty);
  5117. break;
  5118. case 7:// Color Curves
  5119. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  5120. break;
  5121. case 8:// Color 4
  5122. destination[property] = BABYLON.Color4.FromArray(sourceProperty);
  5123. break;
  5124. case 9:// Image Processing
  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. // Statics
  5375. SmartArray._GlobalId = 0;
  5376. return SmartArray;
  5377. }());
  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. url = Tools.PreprocessUrl(url);
  5709. var img = new Image();
  5710. if (url.substr(0, 5) !== "data:") {
  5711. Tools.SetCorsBehavior(url, img);
  5712. }
  5713. img.onload = function () {
  5714. onload(img);
  5715. };
  5716. img.onerror = function (err) {
  5717. Tools.Error("Error while trying to load image: " + url);
  5718. if (Tools.UseFallbackTexture) {
  5719. img.src = Tools.fallbackTexture;
  5720. onload(img);
  5721. }
  5722. else {
  5723. onerror();
  5724. }
  5725. };
  5726. var noIndexedDB = function () {
  5727. img.src = url;
  5728. };
  5729. var loadFromIndexedDB = function () {
  5730. database.loadImageFromDB(url, img);
  5731. };
  5732. //ANY database to do!
  5733. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  5734. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5735. }
  5736. else {
  5737. if (url.indexOf("file:") !== 0) {
  5738. noIndexedDB();
  5739. }
  5740. else {
  5741. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  5742. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  5743. try {
  5744. var blobURL;
  5745. try {
  5746. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  5747. }
  5748. catch (ex) {
  5749. // Chrome doesn't support oneTimeOnly parameter
  5750. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  5751. }
  5752. img.src = blobURL;
  5753. }
  5754. catch (e) {
  5755. img.src = null;
  5756. }
  5757. }
  5758. else {
  5759. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  5760. img.src = Tools.fallbackTexture;
  5761. }
  5762. }
  5763. }
  5764. return img;
  5765. };
  5766. //ANY
  5767. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  5768. url = Tools.CleanUrl(url);
  5769. url = Tools.PreprocessUrl(url);
  5770. var noIndexedDB = function () {
  5771. var request = new XMLHttpRequest();
  5772. var loadUrl = Tools.BaseUrl + url;
  5773. request.open('GET', loadUrl, true);
  5774. if (useArrayBuffer) {
  5775. request.responseType = "arraybuffer";
  5776. }
  5777. request.onprogress = progressCallBack;
  5778. request.onreadystatechange = function () {
  5779. // In case of undefined state in some browsers.
  5780. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  5781. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  5782. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  5783. callback(!useArrayBuffer ? request.responseText : request.response);
  5784. }
  5785. else {
  5786. if (onError) {
  5787. onError(request);
  5788. }
  5789. else {
  5790. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  5791. }
  5792. }
  5793. }
  5794. };
  5795. request.send(null);
  5796. };
  5797. var loadFromIndexedDB = function () {
  5798. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5799. };
  5800. if (url.indexOf("file:") !== -1) {
  5801. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  5802. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  5803. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5804. }
  5805. else {
  5806. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  5807. }
  5808. }
  5809. else {
  5810. // Caching all files
  5811. if (database && database.enableSceneOffline) {
  5812. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5813. }
  5814. else {
  5815. noIndexedDB();
  5816. }
  5817. }
  5818. };
  5819. /**
  5820. * Load a script (identified by an url). When the url returns, the
  5821. * content of this file is added into a new script element, attached to the DOM (body element)
  5822. */
  5823. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5824. var head = document.getElementsByTagName('head')[0];
  5825. var script = document.createElement('script');
  5826. script.type = 'text/javascript';
  5827. script.src = scriptUrl;
  5828. var self = this;
  5829. script.onload = function () {
  5830. if (onSuccess) {
  5831. onSuccess();
  5832. }
  5833. };
  5834. script.onerror = function () {
  5835. if (onError) {
  5836. onError();
  5837. }
  5838. };
  5839. head.appendChild(script);
  5840. };
  5841. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5842. var reader = new FileReader();
  5843. reader.onload = function (e) {
  5844. //target doesn't have result from ts 1.3
  5845. callback(e.target['result']);
  5846. };
  5847. reader.onprogress = progressCallback;
  5848. reader.readAsDataURL(fileToLoad);
  5849. };
  5850. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  5851. var reader = new FileReader();
  5852. reader.onerror = function (e) {
  5853. Tools.Log("Error while reading file: " + fileToLoad.name);
  5854. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  5855. };
  5856. reader.onload = function (e) {
  5857. //target doesn't have result from ts 1.3
  5858. callback(e.target['result']);
  5859. };
  5860. reader.onprogress = progressCallBack;
  5861. if (!useArrayBuffer) {
  5862. // Asynchronous read
  5863. reader.readAsText(fileToLoad);
  5864. }
  5865. else {
  5866. reader.readAsArrayBuffer(fileToLoad);
  5867. }
  5868. };
  5869. //returns a downloadable url to a file content.
  5870. Tools.FileAsURL = function (content) {
  5871. var fileBlob = new Blob([content]);
  5872. var url = window.URL || window.webkitURL;
  5873. var link = url.createObjectURL(fileBlob);
  5874. return link;
  5875. };
  5876. // Misc.
  5877. Tools.Format = function (value, decimals) {
  5878. if (decimals === void 0) { decimals = 2; }
  5879. return value.toFixed(decimals);
  5880. };
  5881. Tools.CheckExtends = function (v, min, max) {
  5882. if (v.x < min.x)
  5883. min.x = v.x;
  5884. if (v.y < min.y)
  5885. min.y = v.y;
  5886. if (v.z < min.z)
  5887. min.z = v.z;
  5888. if (v.x > max.x)
  5889. max.x = v.x;
  5890. if (v.y > max.y)
  5891. max.y = v.y;
  5892. if (v.z > max.z)
  5893. max.z = v.z;
  5894. };
  5895. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5896. for (var prop in source) {
  5897. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5898. continue;
  5899. }
  5900. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5901. continue;
  5902. }
  5903. var sourceValue = source[prop];
  5904. var typeOfSourceValue = typeof sourceValue;
  5905. if (typeOfSourceValue === "function") {
  5906. continue;
  5907. }
  5908. if (typeOfSourceValue === "object") {
  5909. if (sourceValue instanceof Array) {
  5910. destination[prop] = [];
  5911. if (sourceValue.length > 0) {
  5912. if (typeof sourceValue[0] == "object") {
  5913. for (var index = 0; index < sourceValue.length; index++) {
  5914. var clonedValue = cloneValue(sourceValue[index], destination);
  5915. if (destination[prop].indexOf(clonedValue) === -1) {
  5916. destination[prop].push(clonedValue);
  5917. }
  5918. }
  5919. }
  5920. else {
  5921. destination[prop] = sourceValue.slice(0);
  5922. }
  5923. }
  5924. }
  5925. else {
  5926. destination[prop] = cloneValue(sourceValue, destination);
  5927. }
  5928. }
  5929. else {
  5930. destination[prop] = sourceValue;
  5931. }
  5932. }
  5933. };
  5934. Tools.IsEmpty = function (obj) {
  5935. for (var i in obj) {
  5936. return false;
  5937. }
  5938. return true;
  5939. };
  5940. Tools.RegisterTopRootEvents = function (events) {
  5941. for (var index = 0; index < events.length; index++) {
  5942. var event = events[index];
  5943. window.addEventListener(event.name, event.handler, false);
  5944. try {
  5945. if (window.parent) {
  5946. window.parent.addEventListener(event.name, event.handler, false);
  5947. }
  5948. }
  5949. catch (e) {
  5950. // Silently fails...
  5951. }
  5952. }
  5953. };
  5954. Tools.UnregisterTopRootEvents = function (events) {
  5955. for (var index = 0; index < events.length; index++) {
  5956. var event = events[index];
  5957. window.removeEventListener(event.name, event.handler);
  5958. try {
  5959. if (window.parent) {
  5960. window.parent.removeEventListener(event.name, event.handler);
  5961. }
  5962. }
  5963. catch (e) {
  5964. // Silently fails...
  5965. }
  5966. }
  5967. };
  5968. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5969. if (mimeType === void 0) { mimeType = "image/png"; }
  5970. // Read the contents of the framebuffer
  5971. var numberOfChannelsByLine = width * 4;
  5972. var halfHeight = height / 2;
  5973. //Reading datas from WebGL
  5974. var data = engine.readPixels(0, 0, width, height);
  5975. //To flip image on Y axis.
  5976. for (var i = 0; i < halfHeight; i++) {
  5977. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5978. var currentCell = j + i * numberOfChannelsByLine;
  5979. var targetLine = height - i - 1;
  5980. var targetCell = j + targetLine * numberOfChannelsByLine;
  5981. var temp = data[currentCell];
  5982. data[currentCell] = data[targetCell];
  5983. data[targetCell] = temp;
  5984. }
  5985. }
  5986. // Create a 2D canvas to store the result
  5987. if (!screenshotCanvas) {
  5988. screenshotCanvas = document.createElement('canvas');
  5989. }
  5990. screenshotCanvas.width = width;
  5991. screenshotCanvas.height = height;
  5992. var context = screenshotCanvas.getContext('2d');
  5993. // Copy the pixels to a 2D canvas
  5994. var imageData = context.createImageData(width, height);
  5995. var castData = (imageData.data);
  5996. castData.set(data);
  5997. context.putImageData(imageData, 0, 0);
  5998. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5999. };
  6000. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  6001. if (mimeType === void 0) { mimeType = "image/png"; }
  6002. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6003. if (successCallback) {
  6004. successCallback(base64Image);
  6005. }
  6006. else {
  6007. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6008. if (("download" in document.createElement("a"))) {
  6009. var a = window.document.createElement("a");
  6010. a.href = base64Image;
  6011. var date = new Date();
  6012. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6013. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6014. window.document.body.appendChild(a);
  6015. a.addEventListener("click", function () {
  6016. a.parentElement.removeChild(a);
  6017. });
  6018. a.click();
  6019. //Or opening a new tab with the image if it is not possible to automatically start download.
  6020. }
  6021. else {
  6022. var newWindow = window.open("");
  6023. var img = newWindow.document.createElement("img");
  6024. img.src = base64Image;
  6025. newWindow.document.body.appendChild(img);
  6026. }
  6027. }
  6028. };
  6029. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6030. if (mimeType === void 0) { mimeType = "image/png"; }
  6031. var width;
  6032. var height;
  6033. // If a precision value is specified
  6034. if (size.precision) {
  6035. width = Math.round(engine.getRenderWidth() * size.precision);
  6036. height = Math.round(width / engine.getAspectRatio(camera));
  6037. }
  6038. else if (size.width && size.height) {
  6039. width = size.width;
  6040. height = size.height;
  6041. }
  6042. else if (size.width && !size.height) {
  6043. width = size.width;
  6044. height = Math.round(width / engine.getAspectRatio(camera));
  6045. }
  6046. else if (size.height && !size.width) {
  6047. height = size.height;
  6048. width = Math.round(height * engine.getAspectRatio(camera));
  6049. }
  6050. else if (!isNaN(size)) {
  6051. height = size;
  6052. width = size;
  6053. }
  6054. else {
  6055. Tools.Error("Invalid 'size' parameter !");
  6056. return;
  6057. }
  6058. if (!screenshotCanvas) {
  6059. screenshotCanvas = document.createElement('canvas');
  6060. }
  6061. screenshotCanvas.width = width;
  6062. screenshotCanvas.height = height;
  6063. var renderContext = screenshotCanvas.getContext("2d");
  6064. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6065. var newWidth = width;
  6066. var newHeight = newWidth / ratio;
  6067. if (newHeight > height) {
  6068. newHeight = height;
  6069. newWidth = newHeight * ratio;
  6070. }
  6071. var offsetX = Math.max(0, width - newWidth) / 2;
  6072. var offsetY = Math.max(0, height - newHeight) / 2;
  6073. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  6074. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6075. };
  6076. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  6077. if (mimeType === void 0) { mimeType = "image/png"; }
  6078. if (samples === void 0) { samples = 1; }
  6079. var width;
  6080. var height;
  6081. //If a precision value is specified
  6082. if (size.precision) {
  6083. width = Math.round(engine.getRenderWidth() * size.precision);
  6084. height = Math.round(width / engine.getAspectRatio(camera));
  6085. size = { width: width, height: height };
  6086. }
  6087. else if (size.width && size.height) {
  6088. width = size.width;
  6089. height = size.height;
  6090. }
  6091. else if (size.width && !size.height) {
  6092. width = size.width;
  6093. height = Math.round(width / engine.getAspectRatio(camera));
  6094. size = { width: width, height: height };
  6095. }
  6096. else if (size.height && !size.width) {
  6097. height = size.height;
  6098. width = Math.round(height * engine.getAspectRatio(camera));
  6099. size = { width: width, height: height };
  6100. }
  6101. else if (!isNaN(size)) {
  6102. height = size;
  6103. width = size;
  6104. }
  6105. else {
  6106. Tools.Error("Invalid 'size' parameter !");
  6107. return;
  6108. }
  6109. var scene = camera.getScene();
  6110. var previousCamera = null;
  6111. if (scene.activeCamera !== camera) {
  6112. previousCamera = scene.activeCamera;
  6113. scene.activeCamera = camera;
  6114. }
  6115. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6116. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6117. texture.renderList = null;
  6118. texture.samples = samples;
  6119. texture.onAfterRenderObservable.add(function () {
  6120. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6121. });
  6122. scene.incrementRenderId();
  6123. scene.resetCachedMaterial();
  6124. texture.render(true);
  6125. texture.dispose();
  6126. if (previousCamera) {
  6127. scene.activeCamera = previousCamera;
  6128. }
  6129. camera.getProjectionMatrix(true); // Force cache refresh;
  6130. };
  6131. // XHR response validator for local file scenario
  6132. Tools.ValidateXHRData = function (xhr, dataType) {
  6133. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6134. if (dataType === void 0) { dataType = 7; }
  6135. try {
  6136. if (dataType & 1) {
  6137. if (xhr.responseText && xhr.responseText.length > 0) {
  6138. return true;
  6139. }
  6140. else if (dataType === 1) {
  6141. return false;
  6142. }
  6143. }
  6144. if (dataType & 2) {
  6145. // Check header width and height since there is no "TGA" magic number
  6146. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6147. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6148. return true;
  6149. }
  6150. else if (dataType === 2) {
  6151. return false;
  6152. }
  6153. }
  6154. if (dataType & 4) {
  6155. // Check for the "DDS" magic number
  6156. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6157. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6158. return true;
  6159. }
  6160. else {
  6161. return false;
  6162. }
  6163. }
  6164. }
  6165. catch (e) {
  6166. // Global protection
  6167. }
  6168. return false;
  6169. };
  6170. /**
  6171. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6172. * Be aware Math.random() could cause collisions, but:
  6173. * "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"
  6174. */
  6175. Tools.RandomId = function () {
  6176. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6177. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6178. return v.toString(16);
  6179. });
  6180. };
  6181. Object.defineProperty(Tools, "NoneLogLevel", {
  6182. get: function () {
  6183. return Tools._NoneLogLevel;
  6184. },
  6185. enumerable: true,
  6186. configurable: true
  6187. });
  6188. Object.defineProperty(Tools, "MessageLogLevel", {
  6189. get: function () {
  6190. return Tools._MessageLogLevel;
  6191. },
  6192. enumerable: true,
  6193. configurable: true
  6194. });
  6195. Object.defineProperty(Tools, "WarningLogLevel", {
  6196. get: function () {
  6197. return Tools._WarningLogLevel;
  6198. },
  6199. enumerable: true,
  6200. configurable: true
  6201. });
  6202. Object.defineProperty(Tools, "ErrorLogLevel", {
  6203. get: function () {
  6204. return Tools._ErrorLogLevel;
  6205. },
  6206. enumerable: true,
  6207. configurable: true
  6208. });
  6209. Object.defineProperty(Tools, "AllLogLevel", {
  6210. get: function () {
  6211. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6212. },
  6213. enumerable: true,
  6214. configurable: true
  6215. });
  6216. Tools._AddLogEntry = function (entry) {
  6217. Tools._LogCache = entry + Tools._LogCache;
  6218. if (Tools.OnNewCacheEntry) {
  6219. Tools.OnNewCacheEntry(entry);
  6220. }
  6221. };
  6222. Tools._FormatMessage = function (message) {
  6223. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6224. var date = new Date();
  6225. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6226. };
  6227. Tools._LogDisabled = function (message) {
  6228. // nothing to do
  6229. };
  6230. Tools._LogEnabled = function (message) {
  6231. var formattedMessage = Tools._FormatMessage(message);
  6232. console.log("BJS - " + formattedMessage);
  6233. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6234. Tools._AddLogEntry(entry);
  6235. };
  6236. Tools._WarnDisabled = function (message) {
  6237. // nothing to do
  6238. };
  6239. Tools._WarnEnabled = function (message) {
  6240. var formattedMessage = Tools._FormatMessage(message);
  6241. console.warn("BJS - " + formattedMessage);
  6242. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6243. Tools._AddLogEntry(entry);
  6244. };
  6245. Tools._ErrorDisabled = function (message) {
  6246. // nothing to do
  6247. };
  6248. Tools._ErrorEnabled = function (message) {
  6249. Tools.errorsCount++;
  6250. var formattedMessage = Tools._FormatMessage(message);
  6251. console.error("BJS - " + formattedMessage);
  6252. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6253. Tools._AddLogEntry(entry);
  6254. };
  6255. Object.defineProperty(Tools, "LogCache", {
  6256. get: function () {
  6257. return Tools._LogCache;
  6258. },
  6259. enumerable: true,
  6260. configurable: true
  6261. });
  6262. Tools.ClearLogCache = function () {
  6263. Tools._LogCache = "";
  6264. Tools.errorsCount = 0;
  6265. };
  6266. Object.defineProperty(Tools, "LogLevels", {
  6267. set: function (level) {
  6268. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6269. Tools.Log = Tools._LogEnabled;
  6270. }
  6271. else {
  6272. Tools.Log = Tools._LogDisabled;
  6273. }
  6274. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6275. Tools.Warn = Tools._WarnEnabled;
  6276. }
  6277. else {
  6278. Tools.Warn = Tools._WarnDisabled;
  6279. }
  6280. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6281. Tools.Error = Tools._ErrorEnabled;
  6282. }
  6283. else {
  6284. Tools.Error = Tools._ErrorDisabled;
  6285. }
  6286. },
  6287. enumerable: true,
  6288. configurable: true
  6289. });
  6290. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6291. get: function () {
  6292. return Tools._PerformanceNoneLogLevel;
  6293. },
  6294. enumerable: true,
  6295. configurable: true
  6296. });
  6297. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6298. get: function () {
  6299. return Tools._PerformanceUserMarkLogLevel;
  6300. },
  6301. enumerable: true,
  6302. configurable: true
  6303. });
  6304. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6305. get: function () {
  6306. return Tools._PerformanceConsoleLogLevel;
  6307. },
  6308. enumerable: true,
  6309. configurable: true
  6310. });
  6311. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6312. set: function (level) {
  6313. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6314. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6315. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6316. return;
  6317. }
  6318. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6319. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6320. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6321. return;
  6322. }
  6323. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6324. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6325. },
  6326. enumerable: true,
  6327. configurable: true
  6328. });
  6329. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6330. };
  6331. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6332. };
  6333. Tools._StartUserMark = function (counterName, condition) {
  6334. if (condition === void 0) { condition = true; }
  6335. if (!condition || !Tools._performance.mark) {
  6336. return;
  6337. }
  6338. Tools._performance.mark(counterName + "-Begin");
  6339. };
  6340. Tools._EndUserMark = function (counterName, condition) {
  6341. if (condition === void 0) { condition = true; }
  6342. if (!condition || !Tools._performance.mark) {
  6343. return;
  6344. }
  6345. Tools._performance.mark(counterName + "-End");
  6346. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6347. };
  6348. Tools._StartPerformanceConsole = function (counterName, condition) {
  6349. if (condition === void 0) { condition = true; }
  6350. if (!condition) {
  6351. return;
  6352. }
  6353. Tools._StartUserMark(counterName, condition);
  6354. if (console.time) {
  6355. console.time(counterName);
  6356. }
  6357. };
  6358. Tools._EndPerformanceConsole = function (counterName, condition) {
  6359. if (condition === void 0) { condition = true; }
  6360. if (!condition) {
  6361. return;
  6362. }
  6363. Tools._EndUserMark(counterName, condition);
  6364. if (console.time) {
  6365. console.timeEnd(counterName);
  6366. }
  6367. };
  6368. Object.defineProperty(Tools, "Now", {
  6369. get: function () {
  6370. if (window.performance && window.performance.now) {
  6371. return window.performance.now();
  6372. }
  6373. return new Date().getTime();
  6374. },
  6375. enumerable: true,
  6376. configurable: true
  6377. });
  6378. /**
  6379. * This method will return the name of the class used to create the instance of the given object.
  6380. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6381. * @param object the object to get the class name from
  6382. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6383. */
  6384. Tools.GetClassName = function (object, isType) {
  6385. if (isType === void 0) { isType = false; }
  6386. var name = null;
  6387. if (!isType && object.getClassName) {
  6388. name = object.getClassName();
  6389. }
  6390. else {
  6391. if (object instanceof Object) {
  6392. var classObj = isType ? object : Object.getPrototypeOf(object);
  6393. name = classObj.constructor["__bjsclassName__"];
  6394. }
  6395. if (!name) {
  6396. name = typeof object;
  6397. }
  6398. }
  6399. return name;
  6400. };
  6401. Tools.first = function (array, predicate) {
  6402. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6403. var el = array_1[_i];
  6404. if (predicate(el)) {
  6405. return el;
  6406. }
  6407. }
  6408. };
  6409. /**
  6410. * This method will return the name of the full name of the class, including its owning module (if any).
  6411. * 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).
  6412. * @param object the object to get the class name from
  6413. * @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.
  6414. */
  6415. Tools.getFullClassName = function (object, isType) {
  6416. if (isType === void 0) { isType = false; }
  6417. var className = null;
  6418. var moduleName = null;
  6419. if (!isType && object.getClassName) {
  6420. className = object.getClassName();
  6421. }
  6422. else {
  6423. if (object instanceof Object) {
  6424. var classObj = isType ? object : Object.getPrototypeOf(object);
  6425. className = classObj.constructor["__bjsclassName__"];
  6426. moduleName = classObj.constructor["__bjsmoduleName__"];
  6427. }
  6428. if (!className) {
  6429. className = typeof object;
  6430. }
  6431. }
  6432. if (!className) {
  6433. return null;
  6434. }
  6435. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6436. };
  6437. /**
  6438. * 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.
  6439. * @param array
  6440. */
  6441. Tools.arrayOrStringFeeder = function (array) {
  6442. return function (index) {
  6443. if (index >= array.length) {
  6444. return null;
  6445. }
  6446. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6447. if (val && val.getHashCode) {
  6448. val = val.getHashCode();
  6449. }
  6450. if (typeof val === "string") {
  6451. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6452. }
  6453. return val;
  6454. };
  6455. };
  6456. /**
  6457. * Compute the hashCode of a stream of number
  6458. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6459. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6460. * @return the hash code computed
  6461. */
  6462. Tools.hashCodeFromStream = function (feeder) {
  6463. // Based from here: http://stackoverflow.com/a/7616484/802124
  6464. var hash = 0;
  6465. var index = 0;
  6466. var chr = feeder(index++);
  6467. while (chr != null) {
  6468. hash = ((hash << 5) - hash) + chr;
  6469. hash |= 0; // Convert to 32bit integer
  6470. chr = feeder(index++);
  6471. }
  6472. return hash;
  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. Tools.PreprocessUrl = function (url) {
  6480. return url;
  6481. };
  6482. // Logs
  6483. Tools._NoneLogLevel = 0;
  6484. Tools._MessageLogLevel = 1;
  6485. Tools._WarningLogLevel = 2;
  6486. Tools._ErrorLogLevel = 4;
  6487. Tools._LogCache = "";
  6488. Tools.errorsCount = 0;
  6489. Tools.Log = Tools._LogEnabled;
  6490. Tools.Warn = Tools._WarnEnabled;
  6491. Tools.Error = Tools._ErrorEnabled;
  6492. // Performances
  6493. Tools._PerformanceNoneLogLevel = 0;
  6494. Tools._PerformanceUserMarkLogLevel = 1;
  6495. Tools._PerformanceConsoleLogLevel = 2;
  6496. Tools._performance = window.performance;
  6497. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6498. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6499. return Tools;
  6500. }());
  6501. BABYLON.Tools = Tools;
  6502. /**
  6503. * This class is used to track a performance counter which is number based.
  6504. * The user has access to many properties which give statistics of different nature
  6505. *
  6506. * The implementer can track two kinds of Performance Counter: time and count
  6507. * 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.
  6508. * 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.
  6509. */
  6510. var PerfCounter = (function () {
  6511. function PerfCounter() {
  6512. this._startMonitoringTime = 0;
  6513. this._min = 0;
  6514. this._max = 0;
  6515. this._average = 0;
  6516. this._lastSecAverage = 0;
  6517. this._current = 0;
  6518. this._totalValueCount = 0;
  6519. this._totalAccumulated = 0;
  6520. this._lastSecAccumulated = 0;
  6521. this._lastSecTime = 0;
  6522. this._lastSecValueCount = 0;
  6523. }
  6524. Object.defineProperty(PerfCounter.prototype, "min", {
  6525. /**
  6526. * Returns the smallest value ever
  6527. */
  6528. get: function () {
  6529. return this._min;
  6530. },
  6531. enumerable: true,
  6532. configurable: true
  6533. });
  6534. Object.defineProperty(PerfCounter.prototype, "max", {
  6535. /**
  6536. * Returns the biggest value ever
  6537. */
  6538. get: function () {
  6539. return this._max;
  6540. },
  6541. enumerable: true,
  6542. configurable: true
  6543. });
  6544. Object.defineProperty(PerfCounter.prototype, "average", {
  6545. /**
  6546. * Returns the average value since the performance counter is running
  6547. */
  6548. get: function () {
  6549. return this._average;
  6550. },
  6551. enumerable: true,
  6552. configurable: true
  6553. });
  6554. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6555. /**
  6556. * Returns the average value of the last second the counter was monitored
  6557. */
  6558. get: function () {
  6559. return this._lastSecAverage;
  6560. },
  6561. enumerable: true,
  6562. configurable: true
  6563. });
  6564. Object.defineProperty(PerfCounter.prototype, "current", {
  6565. /**
  6566. * Returns the current value
  6567. */
  6568. get: function () {
  6569. return this._current;
  6570. },
  6571. enumerable: true,
  6572. configurable: true
  6573. });
  6574. Object.defineProperty(PerfCounter.prototype, "total", {
  6575. get: function () {
  6576. return this._totalAccumulated;
  6577. },
  6578. enumerable: true,
  6579. configurable: true
  6580. });
  6581. /**
  6582. * Call this method to start monitoring a new frame.
  6583. * 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.
  6584. */
  6585. PerfCounter.prototype.fetchNewFrame = function () {
  6586. this._totalValueCount++;
  6587. this._current = 0;
  6588. this._lastSecValueCount++;
  6589. };
  6590. /**
  6591. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6592. * @param newCount the count value to add to the monitored count
  6593. * @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.
  6594. */
  6595. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6596. if (!PerfCounter.Enabled) {
  6597. return;
  6598. }
  6599. this._current += newCount;
  6600. if (fetchResult) {
  6601. this._fetchResult();
  6602. }
  6603. };
  6604. /**
  6605. * Start monitoring this performance counter
  6606. */
  6607. PerfCounter.prototype.beginMonitoring = function () {
  6608. if (!PerfCounter.Enabled) {
  6609. return;
  6610. }
  6611. this._startMonitoringTime = Tools.Now;
  6612. };
  6613. /**
  6614. * Compute the time lapsed since the previous beginMonitoring() call.
  6615. * @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
  6616. */
  6617. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6618. if (newFrame === void 0) { newFrame = true; }
  6619. if (!PerfCounter.Enabled) {
  6620. return;
  6621. }
  6622. if (newFrame) {
  6623. this.fetchNewFrame();
  6624. }
  6625. var currentTime = Tools.Now;
  6626. this._current = currentTime - this._startMonitoringTime;
  6627. if (newFrame) {
  6628. this._fetchResult();
  6629. }
  6630. };
  6631. PerfCounter.prototype._fetchResult = function () {
  6632. this._totalAccumulated += this._current;
  6633. this._lastSecAccumulated += this._current;
  6634. // Min/Max update
  6635. this._min = Math.min(this._min, this._current);
  6636. this._max = Math.max(this._max, this._current);
  6637. this._average = this._totalAccumulated / this._totalValueCount;
  6638. // Reset last sec?
  6639. var now = Tools.Now;
  6640. if ((now - this._lastSecTime) > 1000) {
  6641. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6642. this._lastSecTime = now;
  6643. this._lastSecAccumulated = 0;
  6644. this._lastSecValueCount = 0;
  6645. }
  6646. };
  6647. PerfCounter.Enabled = true;
  6648. return PerfCounter;
  6649. }());
  6650. BABYLON.PerfCounter = PerfCounter;
  6651. /**
  6652. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6653. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6654. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6655. * @param name The name of the class, case should be preserved
  6656. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6657. */
  6658. function className(name, module) {
  6659. return function (target) {
  6660. target["__bjsclassName__"] = name;
  6661. target["__bjsmoduleName__"] = (module != null) ? module : null;
  6662. };
  6663. }
  6664. BABYLON.className = className;
  6665. /**
  6666. * An implementation of a loop for asynchronous functions.
  6667. */
  6668. var AsyncLoop = (function () {
  6669. /**
  6670. * Constroctor.
  6671. * @param iterations the number of iterations.
  6672. * @param _fn the function to run each iteration
  6673. * @param _successCallback the callback that will be called upon succesful execution
  6674. * @param offset starting offset.
  6675. */
  6676. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  6677. if (offset === void 0) { offset = 0; }
  6678. this.iterations = iterations;
  6679. this._fn = _fn;
  6680. this._successCallback = _successCallback;
  6681. this.index = offset - 1;
  6682. this._done = false;
  6683. }
  6684. /**
  6685. * Execute the next iteration. Must be called after the last iteration was finished.
  6686. */
  6687. AsyncLoop.prototype.executeNext = function () {
  6688. if (!this._done) {
  6689. if (this.index + 1 < this.iterations) {
  6690. ++this.index;
  6691. this._fn(this);
  6692. }
  6693. else {
  6694. this.breakLoop();
  6695. }
  6696. }
  6697. };
  6698. /**
  6699. * Break the loop and run the success callback.
  6700. */
  6701. AsyncLoop.prototype.breakLoop = function () {
  6702. this._done = true;
  6703. this._successCallback();
  6704. };
  6705. /**
  6706. * Helper function
  6707. */
  6708. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  6709. if (offset === void 0) { offset = 0; }
  6710. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  6711. loop.executeNext();
  6712. return loop;
  6713. };
  6714. /**
  6715. * A for-loop that will run a given number of iterations synchronous and the rest async.
  6716. * @param iterations total number of iterations
  6717. * @param syncedIterations number of synchronous iterations in each async iteration.
  6718. * @param fn the function to call each iteration.
  6719. * @param callback a success call back that will be called when iterating stops.
  6720. * @param breakFunction a break condition (optional)
  6721. * @param timeout timeout settings for the setTimeout function. default - 0.
  6722. * @constructor
  6723. */
  6724. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  6725. if (timeout === void 0) { timeout = 0; }
  6726. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  6727. if (breakFunction && breakFunction())
  6728. loop.breakLoop();
  6729. else {
  6730. setTimeout(function () {
  6731. for (var i = 0; i < syncedIterations; ++i) {
  6732. var iteration = (loop.index * syncedIterations) + i;
  6733. if (iteration >= iterations)
  6734. break;
  6735. fn(iteration);
  6736. if (breakFunction && breakFunction()) {
  6737. loop.breakLoop();
  6738. break;
  6739. }
  6740. }
  6741. loop.executeNext();
  6742. }, timeout);
  6743. }
  6744. }, callback);
  6745. };
  6746. return AsyncLoop;
  6747. }());
  6748. BABYLON.AsyncLoop = AsyncLoop;
  6749. })(BABYLON || (BABYLON = {}));
  6750. //# sourceMappingURL=babylon.tools.js.map
  6751. var BABYLON;
  6752. (function (BABYLON) {
  6753. var Internals;
  6754. (function (Internals) {
  6755. var _AlphaState = (function () {
  6756. /**
  6757. * Initializes the state.
  6758. */
  6759. function _AlphaState() {
  6760. this._isAlphaBlendDirty = false;
  6761. this._isBlendFunctionParametersDirty = false;
  6762. this._isBlendEquationParametersDirty = false;
  6763. this._isBlendConstantsDirty = false;
  6764. this._alphaBlend = false;
  6765. this._blendFunctionParameters = new Array(4);
  6766. this._blendEquationParameters = new Array(2);
  6767. this._blendConstants = new Array(4);
  6768. this.reset();
  6769. }
  6770. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  6771. get: function () {
  6772. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  6773. },
  6774. enumerable: true,
  6775. configurable: true
  6776. });
  6777. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  6778. get: function () {
  6779. return this._alphaBlend;
  6780. },
  6781. set: function (value) {
  6782. if (this._alphaBlend === value) {
  6783. return;
  6784. }
  6785. this._alphaBlend = value;
  6786. this._isAlphaBlendDirty = true;
  6787. },
  6788. enumerable: true,
  6789. configurable: true
  6790. });
  6791. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  6792. if (this._blendConstants[0] === r &&
  6793. this._blendConstants[1] === g &&
  6794. this._blendConstants[2] === b &&
  6795. this._blendConstants[3] === a) {
  6796. return;
  6797. }
  6798. this._blendConstants[0] = r;
  6799. this._blendConstants[1] = g;
  6800. this._blendConstants[2] = b;
  6801. this._blendConstants[3] = a;
  6802. this._isBlendConstantsDirty = true;
  6803. };
  6804. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  6805. if (this._blendFunctionParameters[0] === value0 &&
  6806. this._blendFunctionParameters[1] === value1 &&
  6807. this._blendFunctionParameters[2] === value2 &&
  6808. this._blendFunctionParameters[3] === value3) {
  6809. return;
  6810. }
  6811. this._blendFunctionParameters[0] = value0;
  6812. this._blendFunctionParameters[1] = value1;
  6813. this._blendFunctionParameters[2] = value2;
  6814. this._blendFunctionParameters[3] = value3;
  6815. this._isBlendFunctionParametersDirty = true;
  6816. };
  6817. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  6818. if (this._blendEquationParameters[0] === rgb &&
  6819. this._blendEquationParameters[1] === alpha) {
  6820. return;
  6821. }
  6822. this._blendEquationParameters[0] = rgb;
  6823. this._blendEquationParameters[1] = alpha;
  6824. this._isBlendEquationParametersDirty = true;
  6825. };
  6826. _AlphaState.prototype.reset = function () {
  6827. this._alphaBlend = false;
  6828. this._blendFunctionParameters[0] = null;
  6829. this._blendFunctionParameters[1] = null;
  6830. this._blendFunctionParameters[2] = null;
  6831. this._blendFunctionParameters[3] = null;
  6832. this._blendEquationParameters[0] = null;
  6833. this._blendEquationParameters[1] = null;
  6834. this._blendConstants[0] = null;
  6835. this._blendConstants[1] = null;
  6836. this._blendConstants[2] = null;
  6837. this._blendConstants[3] = null;
  6838. this._isAlphaBlendDirty = true;
  6839. this._isBlendFunctionParametersDirty = false;
  6840. this._isBlendEquationParametersDirty = false;
  6841. this._isBlendConstantsDirty = false;
  6842. };
  6843. _AlphaState.prototype.apply = function (gl) {
  6844. if (!this.isDirty) {
  6845. return;
  6846. }
  6847. // Alpha blend
  6848. if (this._isAlphaBlendDirty) {
  6849. if (this._alphaBlend) {
  6850. gl.enable(gl.BLEND);
  6851. }
  6852. else {
  6853. gl.disable(gl.BLEND);
  6854. }
  6855. this._isAlphaBlendDirty = false;
  6856. }
  6857. // Alpha function
  6858. if (this._isBlendFunctionParametersDirty) {
  6859. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  6860. this._isBlendFunctionParametersDirty = false;
  6861. }
  6862. // Alpha equation
  6863. if (this._isBlendEquationParametersDirty) {
  6864. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  6865. this._isBlendEquationParametersDirty = false;
  6866. }
  6867. // Constants
  6868. if (this._isBlendConstantsDirty) {
  6869. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  6870. this._isBlendConstantsDirty = false;
  6871. }
  6872. };
  6873. return _AlphaState;
  6874. }());
  6875. Internals._AlphaState = _AlphaState;
  6876. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6877. })(BABYLON || (BABYLON = {}));
  6878. //# sourceMappingURL=babylon.alphaCullingState.js.map
  6879. var BABYLON;
  6880. (function (BABYLON) {
  6881. var Internals;
  6882. (function (Internals) {
  6883. var _DepthCullingState = (function () {
  6884. /**
  6885. * Initializes the state.
  6886. */
  6887. function _DepthCullingState() {
  6888. this._isDepthTestDirty = false;
  6889. this._isDepthMaskDirty = false;
  6890. this._isDepthFuncDirty = false;
  6891. this._isCullFaceDirty = false;
  6892. this._isCullDirty = false;
  6893. this._isZOffsetDirty = false;
  6894. this.reset();
  6895. }
  6896. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  6897. get: function () {
  6898. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  6899. },
  6900. enumerable: true,
  6901. configurable: true
  6902. });
  6903. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  6904. get: function () {
  6905. return this._zOffset;
  6906. },
  6907. set: function (value) {
  6908. if (this._zOffset === value) {
  6909. return;
  6910. }
  6911. this._zOffset = value;
  6912. this._isZOffsetDirty = true;
  6913. },
  6914. enumerable: true,
  6915. configurable: true
  6916. });
  6917. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  6918. get: function () {
  6919. return this._cullFace;
  6920. },
  6921. set: function (value) {
  6922. if (this._cullFace === value) {
  6923. return;
  6924. }
  6925. this._cullFace = value;
  6926. this._isCullFaceDirty = true;
  6927. },
  6928. enumerable: true,
  6929. configurable: true
  6930. });
  6931. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6932. get: function () {
  6933. return this._cull;
  6934. },
  6935. set: function (value) {
  6936. if (this._cull === value) {
  6937. return;
  6938. }
  6939. this._cull = value;
  6940. this._isCullDirty = true;
  6941. },
  6942. enumerable: true,
  6943. configurable: true
  6944. });
  6945. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6946. get: function () {
  6947. return this._depthFunc;
  6948. },
  6949. set: function (value) {
  6950. if (this._depthFunc === value) {
  6951. return;
  6952. }
  6953. this._depthFunc = value;
  6954. this._isDepthFuncDirty = true;
  6955. },
  6956. enumerable: true,
  6957. configurable: true
  6958. });
  6959. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6960. get: function () {
  6961. return this._depthMask;
  6962. },
  6963. set: function (value) {
  6964. if (this._depthMask === value) {
  6965. return;
  6966. }
  6967. this._depthMask = value;
  6968. this._isDepthMaskDirty = true;
  6969. },
  6970. enumerable: true,
  6971. configurable: true
  6972. });
  6973. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6974. get: function () {
  6975. return this._depthTest;
  6976. },
  6977. set: function (value) {
  6978. if (this._depthTest === value) {
  6979. return;
  6980. }
  6981. this._depthTest = value;
  6982. this._isDepthTestDirty = true;
  6983. },
  6984. enumerable: true,
  6985. configurable: true
  6986. });
  6987. _DepthCullingState.prototype.reset = function () {
  6988. this._depthMask = true;
  6989. this._depthTest = true;
  6990. this._depthFunc = null;
  6991. this._cullFace = null;
  6992. this._cull = null;
  6993. this._zOffset = 0;
  6994. this._isDepthTestDirty = true;
  6995. this._isDepthMaskDirty = true;
  6996. this._isDepthFuncDirty = false;
  6997. this._isCullFaceDirty = false;
  6998. this._isCullDirty = false;
  6999. this._isZOffsetDirty = false;
  7000. };
  7001. _DepthCullingState.prototype.apply = function (gl) {
  7002. if (!this.isDirty) {
  7003. return;
  7004. }
  7005. // Cull
  7006. if (this._isCullDirty) {
  7007. if (this.cull) {
  7008. gl.enable(gl.CULL_FACE);
  7009. }
  7010. else {
  7011. gl.disable(gl.CULL_FACE);
  7012. }
  7013. this._isCullDirty = false;
  7014. }
  7015. // Cull face
  7016. if (this._isCullFaceDirty) {
  7017. gl.cullFace(this.cullFace);
  7018. this._isCullFaceDirty = false;
  7019. }
  7020. // Depth mask
  7021. if (this._isDepthMaskDirty) {
  7022. gl.depthMask(this.depthMask);
  7023. this._isDepthMaskDirty = false;
  7024. }
  7025. // Depth test
  7026. if (this._isDepthTestDirty) {
  7027. if (this.depthTest) {
  7028. gl.enable(gl.DEPTH_TEST);
  7029. }
  7030. else {
  7031. gl.disable(gl.DEPTH_TEST);
  7032. }
  7033. this._isDepthTestDirty = false;
  7034. }
  7035. // Depth func
  7036. if (this._isDepthFuncDirty) {
  7037. gl.depthFunc(this.depthFunc);
  7038. this._isDepthFuncDirty = false;
  7039. }
  7040. // zOffset
  7041. if (this._isZOffsetDirty) {
  7042. if (this.zOffset) {
  7043. gl.enable(gl.POLYGON_OFFSET_FILL);
  7044. gl.polygonOffset(this.zOffset, 0);
  7045. }
  7046. else {
  7047. gl.disable(gl.POLYGON_OFFSET_FILL);
  7048. }
  7049. this._isZOffsetDirty = false;
  7050. }
  7051. };
  7052. return _DepthCullingState;
  7053. }());
  7054. Internals._DepthCullingState = _DepthCullingState;
  7055. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7056. })(BABYLON || (BABYLON = {}));
  7057. //# sourceMappingURL=babylon.depthCullingState.js.map
  7058. var BABYLON;
  7059. (function (BABYLON) {
  7060. var Internals;
  7061. (function (Internals) {
  7062. var _StencilState = (function () {
  7063. function _StencilState() {
  7064. this._isStencilTestDirty = false;
  7065. this._isStencilMaskDirty = false;
  7066. this._isStencilFuncDirty = false;
  7067. this._isStencilOpDirty = false;
  7068. this.reset();
  7069. }
  7070. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7071. get: function () {
  7072. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7073. },
  7074. enumerable: true,
  7075. configurable: true
  7076. });
  7077. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7078. get: function () {
  7079. return this._stencilFunc;
  7080. },
  7081. set: function (value) {
  7082. if (this._stencilFunc === value) {
  7083. return;
  7084. }
  7085. this._stencilFunc = value;
  7086. this._isStencilFuncDirty = true;
  7087. },
  7088. enumerable: true,
  7089. configurable: true
  7090. });
  7091. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7092. get: function () {
  7093. return this._stencilFuncRef;
  7094. },
  7095. set: function (value) {
  7096. if (this._stencilFuncRef === value) {
  7097. return;
  7098. }
  7099. this._stencilFuncRef = value;
  7100. this._isStencilFuncDirty = true;
  7101. },
  7102. enumerable: true,
  7103. configurable: true
  7104. });
  7105. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7106. get: function () {
  7107. return this._stencilFuncMask;
  7108. },
  7109. set: function (value) {
  7110. if (this._stencilFuncMask === value) {
  7111. return;
  7112. }
  7113. this._stencilFuncMask = value;
  7114. this._isStencilFuncDirty = true;
  7115. },
  7116. enumerable: true,
  7117. configurable: true
  7118. });
  7119. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7120. get: function () {
  7121. return this._stencilOpStencilFail;
  7122. },
  7123. set: function (value) {
  7124. if (this._stencilOpStencilFail === value) {
  7125. return;
  7126. }
  7127. this._stencilOpStencilFail = value;
  7128. this._isStencilOpDirty = true;
  7129. },
  7130. enumerable: true,
  7131. configurable: true
  7132. });
  7133. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7134. get: function () {
  7135. return this._stencilOpDepthFail;
  7136. },
  7137. set: function (value) {
  7138. if (this._stencilOpDepthFail === value) {
  7139. return;
  7140. }
  7141. this._stencilOpDepthFail = value;
  7142. this._isStencilOpDirty = true;
  7143. },
  7144. enumerable: true,
  7145. configurable: true
  7146. });
  7147. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7148. get: function () {
  7149. return this._stencilOpStencilDepthPass;
  7150. },
  7151. set: function (value) {
  7152. if (this._stencilOpStencilDepthPass === value) {
  7153. return;
  7154. }
  7155. this._stencilOpStencilDepthPass = value;
  7156. this._isStencilOpDirty = true;
  7157. },
  7158. enumerable: true,
  7159. configurable: true
  7160. });
  7161. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7162. get: function () {
  7163. return this._stencilMask;
  7164. },
  7165. set: function (value) {
  7166. if (this._stencilMask === value) {
  7167. return;
  7168. }
  7169. this._stencilMask = value;
  7170. this._isStencilMaskDirty = true;
  7171. },
  7172. enumerable: true,
  7173. configurable: true
  7174. });
  7175. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7176. get: function () {
  7177. return this._stencilTest;
  7178. },
  7179. set: function (value) {
  7180. if (this._stencilTest === value) {
  7181. return;
  7182. }
  7183. this._stencilTest = value;
  7184. this._isStencilTestDirty = true;
  7185. },
  7186. enumerable: true,
  7187. configurable: true
  7188. });
  7189. _StencilState.prototype.reset = function () {
  7190. this._stencilTest = false;
  7191. this._stencilMask = 0xFF;
  7192. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7193. this._stencilFuncRef = 1;
  7194. this._stencilFuncMask = 0xFF;
  7195. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7196. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7197. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7198. this._isStencilTestDirty = true;
  7199. this._isStencilMaskDirty = true;
  7200. this._isStencilFuncDirty = true;
  7201. this._isStencilOpDirty = true;
  7202. };
  7203. _StencilState.prototype.apply = function (gl) {
  7204. if (!this.isDirty) {
  7205. return;
  7206. }
  7207. // Stencil test
  7208. if (this._isStencilTestDirty) {
  7209. if (this.stencilTest) {
  7210. gl.enable(gl.STENCIL_TEST);
  7211. }
  7212. else {
  7213. gl.disable(gl.STENCIL_TEST);
  7214. }
  7215. this._isStencilTestDirty = false;
  7216. }
  7217. // Stencil mask
  7218. if (this._isStencilMaskDirty) {
  7219. gl.stencilMask(this.stencilMask);
  7220. this._isStencilMaskDirty = false;
  7221. }
  7222. // Stencil func
  7223. if (this._isStencilFuncDirty) {
  7224. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7225. this._isStencilFuncDirty = false;
  7226. }
  7227. // Stencil op
  7228. if (this._isStencilOpDirty) {
  7229. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7230. this._isStencilOpDirty = false;
  7231. }
  7232. };
  7233. return _StencilState;
  7234. }());
  7235. Internals._StencilState = _StencilState;
  7236. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7237. })(BABYLON || (BABYLON = {}));
  7238. //# sourceMappingURL=babylon.stencilState.js.map
  7239. var BABYLON;
  7240. (function (BABYLON) {
  7241. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7242. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7243. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7244. gl.compileShader(shader);
  7245. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7246. throw new Error(gl.getShaderInfoLog(shader));
  7247. }
  7248. return shader;
  7249. };
  7250. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7251. var magFilter = gl.NEAREST;
  7252. var minFilter = gl.NEAREST;
  7253. switch (samplingMode) {
  7254. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7255. magFilter = gl.LINEAR;
  7256. if (generateMipMaps) {
  7257. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7258. }
  7259. else {
  7260. minFilter = gl.LINEAR;
  7261. }
  7262. break;
  7263. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7264. magFilter = gl.LINEAR;
  7265. if (generateMipMaps) {
  7266. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7267. }
  7268. else {
  7269. minFilter = gl.LINEAR;
  7270. }
  7271. break;
  7272. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7273. magFilter = gl.NEAREST;
  7274. if (generateMipMaps) {
  7275. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7276. }
  7277. else {
  7278. minFilter = gl.NEAREST;
  7279. }
  7280. break;
  7281. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7282. magFilter = gl.NEAREST;
  7283. if (generateMipMaps) {
  7284. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7285. }
  7286. else {
  7287. minFilter = gl.NEAREST;
  7288. }
  7289. break;
  7290. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7291. magFilter = gl.NEAREST;
  7292. if (generateMipMaps) {
  7293. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7294. }
  7295. else {
  7296. minFilter = gl.LINEAR;
  7297. }
  7298. break;
  7299. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7300. magFilter = gl.NEAREST;
  7301. if (generateMipMaps) {
  7302. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7303. }
  7304. else {
  7305. minFilter = gl.LINEAR;
  7306. }
  7307. break;
  7308. case BABYLON.Texture.NEAREST_LINEAR:
  7309. magFilter = gl.NEAREST;
  7310. minFilter = gl.LINEAR;
  7311. break;
  7312. case BABYLON.Texture.NEAREST_NEAREST:
  7313. magFilter = gl.NEAREST;
  7314. minFilter = gl.NEAREST;
  7315. break;
  7316. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7317. magFilter = gl.LINEAR;
  7318. if (generateMipMaps) {
  7319. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7320. }
  7321. else {
  7322. minFilter = gl.NEAREST;
  7323. }
  7324. break;
  7325. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7326. magFilter = gl.LINEAR;
  7327. if (generateMipMaps) {
  7328. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7329. }
  7330. else {
  7331. minFilter = gl.NEAREST;
  7332. }
  7333. break;
  7334. case BABYLON.Texture.LINEAR_LINEAR:
  7335. magFilter = gl.LINEAR;
  7336. minFilter = gl.LINEAR;
  7337. break;
  7338. case BABYLON.Texture.LINEAR_NEAREST:
  7339. magFilter = gl.LINEAR;
  7340. minFilter = gl.NEAREST;
  7341. break;
  7342. }
  7343. return {
  7344. min: minFilter,
  7345. mag: magFilter
  7346. };
  7347. };
  7348. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7349. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7350. var img;
  7351. var onload = function () {
  7352. loadedImages[index] = img;
  7353. loadedImages._internalCount++;
  7354. if (scene) {
  7355. scene._removePendingData(img);
  7356. }
  7357. if (loadedImages._internalCount === 6) {
  7358. onfinish(loadedImages);
  7359. }
  7360. };
  7361. var onerror = function () {
  7362. if (scene) {
  7363. scene._removePendingData(img);
  7364. }
  7365. if (onErrorCallBack) {
  7366. onErrorCallBack();
  7367. }
  7368. };
  7369. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  7370. if (scene) {
  7371. scene._addPendingData(img);
  7372. }
  7373. };
  7374. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7375. if (onError === void 0) { onError = null; }
  7376. var loadedImages = [];
  7377. loadedImages._internalCount = 0;
  7378. for (var index = 0; index < 6; index++) {
  7379. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7380. }
  7381. };
  7382. var BufferPointer = (function () {
  7383. function BufferPointer() {
  7384. }
  7385. return BufferPointer;
  7386. }());
  7387. var InstancingAttributeInfo = (function () {
  7388. function InstancingAttributeInfo() {
  7389. }
  7390. return InstancingAttributeInfo;
  7391. }());
  7392. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7393. /**
  7394. * Define options used to create a render target texture
  7395. */
  7396. var RenderTargetCreationOptions = (function () {
  7397. function RenderTargetCreationOptions() {
  7398. }
  7399. return RenderTargetCreationOptions;
  7400. }());
  7401. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  7402. /**
  7403. * Regroup several parameters relative to the browser in use
  7404. */
  7405. var EngineCapabilities = (function () {
  7406. function EngineCapabilities() {
  7407. }
  7408. return EngineCapabilities;
  7409. }());
  7410. BABYLON.EngineCapabilities = EngineCapabilities;
  7411. /**
  7412. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7413. */
  7414. var Engine = (function () {
  7415. /**
  7416. * @constructor
  7417. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7418. * @param {boolean} [antialias] - enable antialias
  7419. * @param options - further options to be sent to the getContext function
  7420. */
  7421. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7422. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7423. var _this = this;
  7424. // Public members
  7425. this.forcePOTTextures = false;
  7426. this.isFullscreen = false;
  7427. this.isPointerLock = false;
  7428. this.cullBackFaces = true;
  7429. this.renderEvenInBackground = true;
  7430. this.preventCacheWipeBetweenFrames = false;
  7431. // To enable/disable IDB support and avoid XHR on .manifest
  7432. this.enableOfflineSupport = false;
  7433. this.scenes = new Array();
  7434. this.postProcesses = new Array();
  7435. // Observables
  7436. /**
  7437. * Observable event triggered each time the rendering canvas is resized
  7438. */
  7439. this.onResizeObservable = new BABYLON.Observable();
  7440. /**
  7441. * Observable event triggered each time the canvas lost focus
  7442. */
  7443. this.onCanvasBlurObservable = new BABYLON.Observable();
  7444. // Uniform buffers list
  7445. this._uniformBuffers = new Array();
  7446. this._windowIsBackground = false;
  7447. this._webGLVersion = 1.0;
  7448. this._badOS = false;
  7449. this._badDesktopOS = false;
  7450. this._drawCalls = new BABYLON.PerfCounter();
  7451. this._renderingQueueLaunched = false;
  7452. this._activeRenderLoops = [];
  7453. // Deterministic lockstepMaxSteps
  7454. this._deterministicLockstep = false;
  7455. this._lockstepMaxSteps = 4;
  7456. this._contextWasLost = false;
  7457. this._doNotHandleContextLost = false;
  7458. // FPS
  7459. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  7460. this._fps = 60;
  7461. this._deltaTime = 0;
  7462. /**
  7463. * Turn this value on if you want to pause FPS computation when in background
  7464. */
  7465. this.disablePerformanceMonitorInBackground = false;
  7466. // States
  7467. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7468. this._stencilState = new BABYLON.Internals._StencilState();
  7469. this._alphaState = new BABYLON.Internals._AlphaState();
  7470. this._alphaMode = Engine.ALPHA_DISABLE;
  7471. // Cache
  7472. this._internalTexturesCache = new Array();
  7473. this._maxTextureChannels = 16;
  7474. this._activeTexturesCache = {};
  7475. this._compiledEffects = {};
  7476. this._vertexAttribArraysEnabled = [];
  7477. this._uintIndicesCurrentlySet = false;
  7478. this._currentBoundBuffer = new Array();
  7479. this._currentBufferPointers = new Array();
  7480. this._currentInstanceLocations = new Array();
  7481. this._currentInstanceBuffers = new Array();
  7482. this._vaoRecordInProgress = false;
  7483. this._mustWipeVertexAttributes = false;
  7484. // Hardware supported Compressed Textures
  7485. this._texturesSupported = new Array();
  7486. this._onVRFullScreenTriggered = function () {
  7487. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7488. //get the old size before we change
  7489. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7490. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7491. //get the width and height, change the render size
  7492. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7493. var width, height;
  7494. _this.setHardwareScalingLevel(1);
  7495. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7496. }
  7497. else {
  7498. //When the specs are implemented, need to uncomment this.
  7499. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7500. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7501. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7502. _this._vrDisplayEnabled = undefined;
  7503. }
  7504. };
  7505. var canvas;
  7506. Engine.Instances.push(this);
  7507. options = options || {};
  7508. if (canvasOrContext.getContext) {
  7509. canvas = canvasOrContext;
  7510. this._renderingCanvas = canvas;
  7511. if (antialias != null) {
  7512. options.antialias = antialias;
  7513. }
  7514. if (options.deterministicLockstep === undefined) {
  7515. options.deterministicLockstep = false;
  7516. }
  7517. if (options.lockstepMaxSteps === undefined) {
  7518. options.lockstepMaxSteps = 4;
  7519. }
  7520. if (options.preserveDrawingBuffer === undefined) {
  7521. options.preserveDrawingBuffer = false;
  7522. }
  7523. if (options.audioEngine === undefined) {
  7524. options.audioEngine = true;
  7525. }
  7526. if (options.stencil === undefined) {
  7527. options.stencil = true;
  7528. }
  7529. this._deterministicLockstep = options.deterministicLockstep;
  7530. this._lockstepMaxSteps = options.lockstepMaxSteps;
  7531. this._doNotHandleContextLost = options.doNotHandleContextLost;
  7532. // GL
  7533. if (!options.disableWebGL2Support) {
  7534. try {
  7535. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7536. if (this._gl) {
  7537. this._webGLVersion = 2.0;
  7538. }
  7539. }
  7540. catch (e) {
  7541. // Do nothing
  7542. }
  7543. }
  7544. if (!this._gl) {
  7545. if (!canvas) {
  7546. throw new Error("The provided canvas is null or undefined.");
  7547. }
  7548. try {
  7549. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7550. }
  7551. catch (e) {
  7552. throw new Error("WebGL not supported");
  7553. }
  7554. }
  7555. if (!this._gl) {
  7556. throw new Error("WebGL not supported");
  7557. }
  7558. this._onBlur = function () {
  7559. if (_this.disablePerformanceMonitorInBackground) {
  7560. _this._performanceMonitor.disable();
  7561. }
  7562. _this._windowIsBackground = true;
  7563. };
  7564. this._onFocus = function () {
  7565. if (_this.disablePerformanceMonitorInBackground) {
  7566. _this._performanceMonitor.enable();
  7567. }
  7568. _this._windowIsBackground = false;
  7569. };
  7570. this._onCanvasBlur = function () {
  7571. _this.onCanvasBlurObservable.notifyObservers(_this);
  7572. };
  7573. window.addEventListener("blur", this._onBlur);
  7574. window.addEventListener("focus", this._onFocus);
  7575. canvas.addEventListener("pointerout", this._onCanvasBlur);
  7576. }
  7577. else {
  7578. this._gl = canvasOrContext;
  7579. this._renderingCanvas = this._gl.canvas;
  7580. if (this._gl.renderbufferStorageMultisample) {
  7581. this._webGLVersion = 2.0;
  7582. }
  7583. options.stencil = this._gl.getContextAttributes().stencil;
  7584. }
  7585. // Context lost
  7586. if (!this._doNotHandleContextLost) {
  7587. this._onContextLost = function (evt) {
  7588. evt.preventDefault();
  7589. _this._contextWasLost = true;
  7590. BABYLON.Tools.Warn("WebGL context lost.");
  7591. };
  7592. this._onContextRestored = function (evt) {
  7593. // Rebuild gl context
  7594. _this._initGLContext();
  7595. // Rebuild effects
  7596. _this._rebuildEffects();
  7597. // Rebuild textures
  7598. _this._rebuildInternalTextures();
  7599. // Rebuild buffers
  7600. _this._rebuildBuffers();
  7601. // Cache
  7602. _this.wipeCaches(true);
  7603. BABYLON.Tools.Warn("WebGL context successfully restored.");
  7604. _this._contextWasLost = false;
  7605. };
  7606. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  7607. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  7608. }
  7609. // Viewport
  7610. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7611. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7612. this.resize();
  7613. this._isStencilEnable = options.stencil;
  7614. this._initGLContext();
  7615. if (canvas) {
  7616. // Fullscreen
  7617. this._onFullscreenChange = function () {
  7618. if (document.fullscreen !== undefined) {
  7619. _this.isFullscreen = document.fullscreen;
  7620. }
  7621. else if (document.mozFullScreen !== undefined) {
  7622. _this.isFullscreen = document.mozFullScreen;
  7623. }
  7624. else if (document.webkitIsFullScreen !== undefined) {
  7625. _this.isFullscreen = document.webkitIsFullScreen;
  7626. }
  7627. else if (document.msIsFullScreen !== undefined) {
  7628. _this.isFullscreen = document.msIsFullScreen;
  7629. }
  7630. // Pointer lock
  7631. if (_this.isFullscreen && _this._pointerLockRequested) {
  7632. canvas.requestPointerLock = canvas.requestPointerLock ||
  7633. canvas.msRequestPointerLock ||
  7634. canvas.mozRequestPointerLock ||
  7635. canvas.webkitRequestPointerLock;
  7636. if (canvas.requestPointerLock) {
  7637. canvas.requestPointerLock();
  7638. }
  7639. }
  7640. };
  7641. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7642. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7643. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7644. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7645. // Pointer lock
  7646. this._onPointerLockChange = function () {
  7647. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7648. document.webkitPointerLockElement === canvas ||
  7649. document.msPointerLockElement === canvas ||
  7650. document.pointerLockElement === canvas);
  7651. };
  7652. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7653. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7654. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7655. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7656. this._onVRDisplayPointerRestricted = function () {
  7657. canvas.requestPointerLock();
  7658. };
  7659. this._onVRDisplayPointerUnrestricted = function () {
  7660. document.exitPointerLock();
  7661. };
  7662. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  7663. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  7664. }
  7665. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7666. Engine.audioEngine = new BABYLON.AudioEngine();
  7667. }
  7668. // Prepare buffer pointers
  7669. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  7670. this._currentBufferPointers[i] = new BufferPointer();
  7671. }
  7672. // Load WebVR Devices
  7673. if (options.autoEnableWebVR) {
  7674. this.initWebVR();
  7675. }
  7676. // Detect if we are running on a faulty buggy OS.
  7677. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  7678. // Detect if we are running on a faulty buggy desktop OS.
  7679. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  7680. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7681. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  7682. }
  7683. Object.defineProperty(Engine, "LastCreatedEngine", {
  7684. get: function () {
  7685. if (Engine.Instances.length === 0) {
  7686. return null;
  7687. }
  7688. return Engine.Instances[Engine.Instances.length - 1];
  7689. },
  7690. enumerable: true,
  7691. configurable: true
  7692. });
  7693. Object.defineProperty(Engine, "LastCreatedScene", {
  7694. get: function () {
  7695. var lastCreatedEngine = Engine.LastCreatedEngine;
  7696. if (!lastCreatedEngine) {
  7697. return null;
  7698. }
  7699. if (lastCreatedEngine.scenes.length === 0) {
  7700. return null;
  7701. }
  7702. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7703. },
  7704. enumerable: true,
  7705. configurable: true
  7706. });
  7707. /**
  7708. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  7709. */
  7710. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  7711. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  7712. var engine = Engine.Instances[engineIndex];
  7713. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  7714. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  7715. }
  7716. }
  7717. };
  7718. Object.defineProperty(Engine, "NEVER", {
  7719. get: function () {
  7720. return Engine._NEVER;
  7721. },
  7722. enumerable: true,
  7723. configurable: true
  7724. });
  7725. Object.defineProperty(Engine, "ALWAYS", {
  7726. get: function () {
  7727. return Engine._ALWAYS;
  7728. },
  7729. enumerable: true,
  7730. configurable: true
  7731. });
  7732. Object.defineProperty(Engine, "LESS", {
  7733. get: function () {
  7734. return Engine._LESS;
  7735. },
  7736. enumerable: true,
  7737. configurable: true
  7738. });
  7739. Object.defineProperty(Engine, "EQUAL", {
  7740. get: function () {
  7741. return Engine._EQUAL;
  7742. },
  7743. enumerable: true,
  7744. configurable: true
  7745. });
  7746. Object.defineProperty(Engine, "LEQUAL", {
  7747. get: function () {
  7748. return Engine._LEQUAL;
  7749. },
  7750. enumerable: true,
  7751. configurable: true
  7752. });
  7753. Object.defineProperty(Engine, "GREATER", {
  7754. get: function () {
  7755. return Engine._GREATER;
  7756. },
  7757. enumerable: true,
  7758. configurable: true
  7759. });
  7760. Object.defineProperty(Engine, "GEQUAL", {
  7761. get: function () {
  7762. return Engine._GEQUAL;
  7763. },
  7764. enumerable: true,
  7765. configurable: true
  7766. });
  7767. Object.defineProperty(Engine, "NOTEQUAL", {
  7768. get: function () {
  7769. return Engine._NOTEQUAL;
  7770. },
  7771. enumerable: true,
  7772. configurable: true
  7773. });
  7774. Object.defineProperty(Engine, "KEEP", {
  7775. get: function () {
  7776. return Engine._KEEP;
  7777. },
  7778. enumerable: true,
  7779. configurable: true
  7780. });
  7781. Object.defineProperty(Engine, "REPLACE", {
  7782. get: function () {
  7783. return Engine._REPLACE;
  7784. },
  7785. enumerable: true,
  7786. configurable: true
  7787. });
  7788. Object.defineProperty(Engine, "INCR", {
  7789. get: function () {
  7790. return Engine._INCR;
  7791. },
  7792. enumerable: true,
  7793. configurable: true
  7794. });
  7795. Object.defineProperty(Engine, "DECR", {
  7796. get: function () {
  7797. return Engine._DECR;
  7798. },
  7799. enumerable: true,
  7800. configurable: true
  7801. });
  7802. Object.defineProperty(Engine, "INVERT", {
  7803. get: function () {
  7804. return Engine._INVERT;
  7805. },
  7806. enumerable: true,
  7807. configurable: true
  7808. });
  7809. Object.defineProperty(Engine, "INCR_WRAP", {
  7810. get: function () {
  7811. return Engine._INCR_WRAP;
  7812. },
  7813. enumerable: true,
  7814. configurable: true
  7815. });
  7816. Object.defineProperty(Engine, "DECR_WRAP", {
  7817. get: function () {
  7818. return Engine._DECR_WRAP;
  7819. },
  7820. enumerable: true,
  7821. configurable: true
  7822. });
  7823. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  7824. get: function () {
  7825. return Engine._ALPHA_DISABLE;
  7826. },
  7827. enumerable: true,
  7828. configurable: true
  7829. });
  7830. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  7831. get: function () {
  7832. return Engine._ALPHA_ONEONE;
  7833. },
  7834. enumerable: true,
  7835. configurable: true
  7836. });
  7837. Object.defineProperty(Engine, "ALPHA_ADD", {
  7838. get: function () {
  7839. return Engine._ALPHA_ADD;
  7840. },
  7841. enumerable: true,
  7842. configurable: true
  7843. });
  7844. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  7845. get: function () {
  7846. return Engine._ALPHA_COMBINE;
  7847. },
  7848. enumerable: true,
  7849. configurable: true
  7850. });
  7851. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  7852. get: function () {
  7853. return Engine._ALPHA_SUBTRACT;
  7854. },
  7855. enumerable: true,
  7856. configurable: true
  7857. });
  7858. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  7859. get: function () {
  7860. return Engine._ALPHA_MULTIPLY;
  7861. },
  7862. enumerable: true,
  7863. configurable: true
  7864. });
  7865. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  7866. get: function () {
  7867. return Engine._ALPHA_MAXIMIZED;
  7868. },
  7869. enumerable: true,
  7870. configurable: true
  7871. });
  7872. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  7873. get: function () {
  7874. return Engine._ALPHA_PREMULTIPLIED;
  7875. },
  7876. enumerable: true,
  7877. configurable: true
  7878. });
  7879. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  7880. get: function () {
  7881. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  7882. },
  7883. enumerable: true,
  7884. configurable: true
  7885. });
  7886. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  7887. get: function () {
  7888. return Engine._ALPHA_INTERPOLATE;
  7889. },
  7890. enumerable: true,
  7891. configurable: true
  7892. });
  7893. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  7894. get: function () {
  7895. return Engine._ALPHA_SCREENMODE;
  7896. },
  7897. enumerable: true,
  7898. configurable: true
  7899. });
  7900. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  7901. get: function () {
  7902. return Engine._DELAYLOADSTATE_NONE;
  7903. },
  7904. enumerable: true,
  7905. configurable: true
  7906. });
  7907. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  7908. get: function () {
  7909. return Engine._DELAYLOADSTATE_LOADED;
  7910. },
  7911. enumerable: true,
  7912. configurable: true
  7913. });
  7914. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  7915. get: function () {
  7916. return Engine._DELAYLOADSTATE_LOADING;
  7917. },
  7918. enumerable: true,
  7919. configurable: true
  7920. });
  7921. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  7922. get: function () {
  7923. return Engine._DELAYLOADSTATE_NOTLOADED;
  7924. },
  7925. enumerable: true,
  7926. configurable: true
  7927. });
  7928. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  7929. get: function () {
  7930. return Engine._TEXTUREFORMAT_ALPHA;
  7931. },
  7932. enumerable: true,
  7933. configurable: true
  7934. });
  7935. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  7936. get: function () {
  7937. return Engine._TEXTUREFORMAT_LUMINANCE;
  7938. },
  7939. enumerable: true,
  7940. configurable: true
  7941. });
  7942. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  7943. get: function () {
  7944. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  7945. },
  7946. enumerable: true,
  7947. configurable: true
  7948. });
  7949. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  7950. get: function () {
  7951. return Engine._TEXTUREFORMAT_RGB;
  7952. },
  7953. enumerable: true,
  7954. configurable: true
  7955. });
  7956. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  7957. get: function () {
  7958. return Engine._TEXTUREFORMAT_RGBA;
  7959. },
  7960. enumerable: true,
  7961. configurable: true
  7962. });
  7963. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  7964. get: function () {
  7965. return Engine._TEXTURETYPE_UNSIGNED_INT;
  7966. },
  7967. enumerable: true,
  7968. configurable: true
  7969. });
  7970. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  7971. get: function () {
  7972. return Engine._TEXTURETYPE_FLOAT;
  7973. },
  7974. enumerable: true,
  7975. configurable: true
  7976. });
  7977. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  7978. get: function () {
  7979. return Engine._TEXTURETYPE_HALF_FLOAT;
  7980. },
  7981. enumerable: true,
  7982. configurable: true
  7983. });
  7984. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  7985. get: function () {
  7986. return Engine._SCALEMODE_FLOOR;
  7987. },
  7988. enumerable: true,
  7989. configurable: true
  7990. });
  7991. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  7992. get: function () {
  7993. return Engine._SCALEMODE_NEAREST;
  7994. },
  7995. enumerable: true,
  7996. configurable: true
  7997. });
  7998. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  7999. get: function () {
  8000. return Engine._SCALEMODE_CEILING;
  8001. },
  8002. enumerable: true,
  8003. configurable: true
  8004. });
  8005. Object.defineProperty(Engine, "Version", {
  8006. get: function () {
  8007. return "3.1-alpha";
  8008. },
  8009. enumerable: true,
  8010. configurable: true
  8011. });
  8012. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8013. get: function () {
  8014. return this._webGLVersion < 2 || this.forcePOTTextures;
  8015. },
  8016. enumerable: true,
  8017. configurable: true
  8018. });
  8019. Object.defineProperty(Engine.prototype, "badOS", {
  8020. get: function () {
  8021. return this._badOS;
  8022. },
  8023. enumerable: true,
  8024. configurable: true
  8025. });
  8026. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8027. get: function () {
  8028. return this._badDesktopOS;
  8029. },
  8030. enumerable: true,
  8031. configurable: true
  8032. });
  8033. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8034. get: function () {
  8035. return this._performanceMonitor;
  8036. },
  8037. enumerable: true,
  8038. configurable: true
  8039. });
  8040. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8041. get: function () {
  8042. return this._texturesSupported;
  8043. },
  8044. enumerable: true,
  8045. configurable: true
  8046. });
  8047. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8048. get: function () {
  8049. return this._textureFormatInUse;
  8050. },
  8051. enumerable: true,
  8052. configurable: true
  8053. });
  8054. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8055. // Empty texture
  8056. get: function () {
  8057. if (!this._emptyTexture) {
  8058. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8059. }
  8060. return this._emptyTexture;
  8061. },
  8062. enumerable: true,
  8063. configurable: true
  8064. });
  8065. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8066. get: function () {
  8067. if (!this._emptyCubeTexture) {
  8068. var faceData = new Uint8Array(4);
  8069. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8070. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8071. }
  8072. return this._emptyCubeTexture;
  8073. },
  8074. enumerable: true,
  8075. configurable: true
  8076. });
  8077. Engine.prototype._rebuildInternalTextures = function () {
  8078. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  8079. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  8080. var internalTexture = currentState_1[_i];
  8081. internalTexture._rebuild();
  8082. }
  8083. };
  8084. Engine.prototype._rebuildEffects = function () {
  8085. for (var key in this._compiledEffects) {
  8086. var effect = this._compiledEffects[key];
  8087. effect._prepareEffect();
  8088. }
  8089. BABYLON.Effect.ResetCache();
  8090. };
  8091. Engine.prototype._rebuildBuffers = function () {
  8092. // Index / Vertex
  8093. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  8094. var scene = _a[_i];
  8095. scene.resetCachedMaterial();
  8096. scene._rebuildGeometries();
  8097. scene._rebuildTextures();
  8098. }
  8099. // Uniforms
  8100. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  8101. var uniformBuffer = _c[_b];
  8102. uniformBuffer._rebuild();
  8103. }
  8104. };
  8105. Engine.prototype._initGLContext = function () {
  8106. // Caps
  8107. this._caps = new EngineCapabilities();
  8108. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8109. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8110. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8111. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8112. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8113. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8114. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8115. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8116. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8117. // Infos
  8118. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8119. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8120. if (rendererInfo != null) {
  8121. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8122. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8123. }
  8124. if (!this._glVendor) {
  8125. this._glVendor = "Unknown vendor";
  8126. }
  8127. if (!this._glRenderer) {
  8128. this._glRenderer = "Unknown renderer";
  8129. }
  8130. // Constants
  8131. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  8132. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8133. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8134. this._gl.DEPTH24_STENCIL8 = 35056;
  8135. // Extensions
  8136. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8137. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8138. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8139. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8140. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8141. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8142. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8143. 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');
  8144. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8145. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8146. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8147. this._caps.highPrecisionShaderSupported = true;
  8148. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  8149. // Checks if some of the format renders first to allow the use of webgl inspector.
  8150. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8151. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8152. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8153. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8154. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8155. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8156. if (this._webGLVersion > 1) {
  8157. this._gl.HALF_FLOAT_OES = 0x140B;
  8158. }
  8159. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8160. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8161. // Vertex array object
  8162. if (this._webGLVersion > 1) {
  8163. this._caps.vertexArrayObject = true;
  8164. }
  8165. else {
  8166. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8167. if (vertexArrayObjectExtension != null) {
  8168. this._caps.vertexArrayObject = true;
  8169. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8170. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8171. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8172. }
  8173. else {
  8174. this._caps.vertexArrayObject = false;
  8175. }
  8176. }
  8177. // Instances count
  8178. if (this._webGLVersion > 1) {
  8179. this._caps.instancedArrays = true;
  8180. }
  8181. else {
  8182. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8183. if (instanceExtension != null) {
  8184. this._caps.instancedArrays = true;
  8185. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8186. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8187. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8188. }
  8189. else {
  8190. this._caps.instancedArrays = false;
  8191. }
  8192. }
  8193. // Intelligently add supported compressed formats in order to check for.
  8194. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8195. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8196. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8197. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8198. if (this._caps.astc)
  8199. this.texturesSupported.push('-astc.ktx');
  8200. if (this._caps.s3tc)
  8201. this.texturesSupported.push('-dxt.ktx');
  8202. if (this._caps.pvrtc)
  8203. this.texturesSupported.push('-pvrtc.ktx');
  8204. if (this._caps.etc2)
  8205. this.texturesSupported.push('-etc2.ktx');
  8206. if (this._caps.etc1)
  8207. this.texturesSupported.push('-etc1.ktx');
  8208. if (this._gl.getShaderPrecisionFormat) {
  8209. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8210. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8211. }
  8212. // Depth buffer
  8213. this.setDepthBuffer(true);
  8214. this.setDepthFunctionToLessOrEqual();
  8215. this.setDepthWrite(true);
  8216. };
  8217. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8218. get: function () {
  8219. return this._webGLVersion;
  8220. },
  8221. enumerable: true,
  8222. configurable: true
  8223. });
  8224. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8225. /**
  8226. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8227. */
  8228. get: function () {
  8229. return this._isStencilEnable;
  8230. },
  8231. enumerable: true,
  8232. configurable: true
  8233. });
  8234. Engine.prototype._prepareWorkingCanvas = function () {
  8235. if (this._workingCanvas) {
  8236. return;
  8237. }
  8238. this._workingCanvas = document.createElement("canvas");
  8239. this._workingContext = this._workingCanvas.getContext("2d");
  8240. };
  8241. Engine.prototype.resetTextureCache = function () {
  8242. for (var key in this._activeTexturesCache) {
  8243. this._activeTexturesCache[key] = null;
  8244. }
  8245. };
  8246. Engine.prototype.isDeterministicLockStep = function () {
  8247. return this._deterministicLockstep;
  8248. };
  8249. Engine.prototype.getLockstepMaxSteps = function () {
  8250. return this._lockstepMaxSteps;
  8251. };
  8252. Engine.prototype.getGlInfo = function () {
  8253. return {
  8254. vendor: this._glVendor,
  8255. renderer: this._glRenderer,
  8256. version: this._glVersion
  8257. };
  8258. };
  8259. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8260. if (useScreen === void 0) { useScreen = false; }
  8261. var viewport = camera.viewport;
  8262. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8263. };
  8264. Engine.prototype.getRenderWidth = function (useScreen) {
  8265. if (useScreen === void 0) { useScreen = false; }
  8266. if (!useScreen && this._currentRenderTarget) {
  8267. return this._currentRenderTarget.width;
  8268. }
  8269. return this._gl.drawingBufferWidth;
  8270. };
  8271. Engine.prototype.getRenderHeight = function (useScreen) {
  8272. if (useScreen === void 0) { useScreen = false; }
  8273. if (!useScreen && this._currentRenderTarget) {
  8274. return this._currentRenderTarget.height;
  8275. }
  8276. return this._gl.drawingBufferHeight;
  8277. };
  8278. Engine.prototype.getRenderingCanvas = function () {
  8279. return this._renderingCanvas;
  8280. };
  8281. Engine.prototype.getRenderingCanvasClientRect = function () {
  8282. return this._renderingCanvas.getBoundingClientRect();
  8283. };
  8284. Engine.prototype.setHardwareScalingLevel = function (level) {
  8285. this._hardwareScalingLevel = level;
  8286. this.resize();
  8287. };
  8288. Engine.prototype.getHardwareScalingLevel = function () {
  8289. return this._hardwareScalingLevel;
  8290. };
  8291. Engine.prototype.getLoadedTexturesCache = function () {
  8292. return this._internalTexturesCache;
  8293. };
  8294. Engine.prototype.getCaps = function () {
  8295. return this._caps;
  8296. };
  8297. Object.defineProperty(Engine.prototype, "drawCalls", {
  8298. /** The number of draw calls submitted last frame */
  8299. get: function () {
  8300. return this._drawCalls.current;
  8301. },
  8302. enumerable: true,
  8303. configurable: true
  8304. });
  8305. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8306. get: function () {
  8307. return this._drawCalls;
  8308. },
  8309. enumerable: true,
  8310. configurable: true
  8311. });
  8312. Engine.prototype.getDepthFunction = function () {
  8313. return this._depthCullingState.depthFunc;
  8314. };
  8315. Engine.prototype.setDepthFunction = function (depthFunc) {
  8316. this._depthCullingState.depthFunc = depthFunc;
  8317. };
  8318. Engine.prototype.setDepthFunctionToGreater = function () {
  8319. this._depthCullingState.depthFunc = this._gl.GREATER;
  8320. };
  8321. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8322. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8323. };
  8324. Engine.prototype.setDepthFunctionToLess = function () {
  8325. this._depthCullingState.depthFunc = this._gl.LESS;
  8326. };
  8327. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8328. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8329. };
  8330. Engine.prototype.getStencilBuffer = function () {
  8331. return this._stencilState.stencilTest;
  8332. };
  8333. Engine.prototype.setStencilBuffer = function (enable) {
  8334. this._stencilState.stencilTest = enable;
  8335. };
  8336. Engine.prototype.getStencilMask = function () {
  8337. return this._stencilState.stencilMask;
  8338. };
  8339. Engine.prototype.setStencilMask = function (mask) {
  8340. this._stencilState.stencilMask = mask;
  8341. };
  8342. Engine.prototype.getStencilFunction = function () {
  8343. return this._stencilState.stencilFunc;
  8344. };
  8345. Engine.prototype.getStencilFunctionReference = function () {
  8346. return this._stencilState.stencilFuncRef;
  8347. };
  8348. Engine.prototype.getStencilFunctionMask = function () {
  8349. return this._stencilState.stencilFuncMask;
  8350. };
  8351. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8352. this._stencilState.stencilFunc = stencilFunc;
  8353. };
  8354. Engine.prototype.setStencilFunctionReference = function (reference) {
  8355. this._stencilState.stencilFuncRef = reference;
  8356. };
  8357. Engine.prototype.setStencilFunctionMask = function (mask) {
  8358. this._stencilState.stencilFuncMask = mask;
  8359. };
  8360. Engine.prototype.getStencilOperationFail = function () {
  8361. return this._stencilState.stencilOpStencilFail;
  8362. };
  8363. Engine.prototype.getStencilOperationDepthFail = function () {
  8364. return this._stencilState.stencilOpDepthFail;
  8365. };
  8366. Engine.prototype.getStencilOperationPass = function () {
  8367. return this._stencilState.stencilOpStencilDepthPass;
  8368. };
  8369. Engine.prototype.setStencilOperationFail = function (operation) {
  8370. this._stencilState.stencilOpStencilFail = operation;
  8371. };
  8372. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8373. this._stencilState.stencilOpDepthFail = operation;
  8374. };
  8375. Engine.prototype.setStencilOperationPass = function (operation) {
  8376. this._stencilState.stencilOpStencilDepthPass = operation;
  8377. };
  8378. Engine.prototype.setDitheringState = function (value) {
  8379. if (value) {
  8380. this._gl.enable(this._gl.DITHER);
  8381. }
  8382. else {
  8383. this._gl.disable(this._gl.DITHER);
  8384. }
  8385. };
  8386. /**
  8387. * stop executing a render loop function and remove it from the execution array
  8388. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8389. */
  8390. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8391. if (!renderFunction) {
  8392. this._activeRenderLoops = [];
  8393. return;
  8394. }
  8395. var index = this._activeRenderLoops.indexOf(renderFunction);
  8396. if (index >= 0) {
  8397. this._activeRenderLoops.splice(index, 1);
  8398. }
  8399. };
  8400. Engine.prototype._renderLoop = function () {
  8401. if (!this._contextWasLost) {
  8402. var shouldRender = true;
  8403. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8404. shouldRender = false;
  8405. }
  8406. if (shouldRender) {
  8407. // Start new frame
  8408. this.beginFrame();
  8409. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8410. var renderFunction = this._activeRenderLoops[index];
  8411. renderFunction();
  8412. }
  8413. // Present
  8414. this.endFrame();
  8415. }
  8416. }
  8417. if (this._activeRenderLoops.length > 0) {
  8418. // Register new frame
  8419. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  8420. }
  8421. else {
  8422. this._renderingQueueLaunched = false;
  8423. }
  8424. };
  8425. /**
  8426. * Register and execute a render loop. The engine can have more than one render function.
  8427. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8428. * @example
  8429. * engine.runRenderLoop(function () {
  8430. * scene.render()
  8431. * })
  8432. */
  8433. Engine.prototype.runRenderLoop = function (renderFunction) {
  8434. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8435. return;
  8436. }
  8437. this._activeRenderLoops.push(renderFunction);
  8438. if (!this._renderingQueueLaunched) {
  8439. this._renderingQueueLaunched = true;
  8440. this._bindedRenderFunction = this._renderLoop.bind(this);
  8441. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8442. }
  8443. };
  8444. /**
  8445. * Toggle full screen mode.
  8446. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8447. * @param {any} options - an options object to be sent to the requestFullscreen function
  8448. */
  8449. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8450. if (this.isFullscreen) {
  8451. BABYLON.Tools.ExitFullscreen();
  8452. }
  8453. else {
  8454. this._pointerLockRequested = requestPointerLock;
  8455. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8456. }
  8457. };
  8458. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8459. if (stencil === void 0) { stencil = false; }
  8460. this.applyStates();
  8461. var mode = 0;
  8462. if (backBuffer && color) {
  8463. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8464. mode |= this._gl.COLOR_BUFFER_BIT;
  8465. }
  8466. if (depth) {
  8467. this._gl.clearDepth(1.0);
  8468. mode |= this._gl.DEPTH_BUFFER_BIT;
  8469. }
  8470. if (stencil) {
  8471. this._gl.clearStencil(0);
  8472. mode |= this._gl.STENCIL_BUFFER_BIT;
  8473. }
  8474. this._gl.clear(mode);
  8475. };
  8476. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8477. var gl = this._gl;
  8478. // Save state
  8479. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8480. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8481. // Change state
  8482. gl.enable(gl.SCISSOR_TEST);
  8483. gl.scissor(x, y, width, height);
  8484. // Clear
  8485. this.clear(clearColor, true, true, true);
  8486. // Restore state
  8487. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8488. if (curScissor === true) {
  8489. gl.enable(gl.SCISSOR_TEST);
  8490. }
  8491. else {
  8492. gl.disable(gl.SCISSOR_TEST);
  8493. }
  8494. };
  8495. /**
  8496. * Set the WebGL's viewport
  8497. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8498. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8499. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8500. */
  8501. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8502. var width = requiredWidth || this.getRenderWidth();
  8503. var height = requiredHeight || this.getRenderHeight();
  8504. var x = viewport.x || 0;
  8505. var y = viewport.y || 0;
  8506. this._cachedViewport = viewport;
  8507. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8508. };
  8509. /**
  8510. * Directly set the WebGL Viewport
  8511. * The x, y, width & height are directly passed to the WebGL call
  8512. * @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.
  8513. */
  8514. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8515. var currentViewport = this._cachedViewport;
  8516. this._cachedViewport = null;
  8517. this._gl.viewport(x, y, width, height);
  8518. return currentViewport;
  8519. };
  8520. Engine.prototype.beginFrame = function () {
  8521. this._measureFps();
  8522. };
  8523. Engine.prototype.endFrame = function () {
  8524. //force a flush in case we are using a bad OS.
  8525. if (this._badOS) {
  8526. this.flushFramebuffer();
  8527. }
  8528. //submit frame to the vr device, if enabled
  8529. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8530. this._vrDisplayEnabled.submitFrame();
  8531. }
  8532. };
  8533. /**
  8534. * resize the view according to the canvas' size.
  8535. * @example
  8536. * window.addEventListener("resize", function () {
  8537. * engine.resize();
  8538. * });
  8539. */
  8540. Engine.prototype.resize = function () {
  8541. // We're not resizing the size of the canvas while in VR mode & presenting
  8542. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  8543. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8544. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8545. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8546. }
  8547. };
  8548. /**
  8549. * force a specific size of the canvas
  8550. * @param {number} width - the new canvas' width
  8551. * @param {number} height - the new canvas' height
  8552. */
  8553. Engine.prototype.setSize = function (width, height) {
  8554. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  8555. return;
  8556. }
  8557. this._renderingCanvas.width = width;
  8558. this._renderingCanvas.height = height;
  8559. for (var index = 0; index < this.scenes.length; index++) {
  8560. var scene = this.scenes[index];
  8561. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8562. var cam = scene.cameras[camIndex];
  8563. cam._currentRenderId = 0;
  8564. }
  8565. }
  8566. if (this.onResizeObservable.hasObservers) {
  8567. this.onResizeObservable.notifyObservers(this);
  8568. }
  8569. };
  8570. //WebVR functions
  8571. Engine.prototype.isVRDevicePresent = function (callback) {
  8572. this.getVRDevice(null, function (device) {
  8573. callback(device !== null);
  8574. });
  8575. };
  8576. Engine.prototype.getVRDevice = function (name, callback) {
  8577. if (!this.vrDisplaysPromise) {
  8578. callback(null);
  8579. return;
  8580. }
  8581. this.vrDisplaysPromise.then(function (devices) {
  8582. if (devices.length > 0) {
  8583. if (name) {
  8584. var found = devices.some(function (device) {
  8585. if (device.displayName === name) {
  8586. callback(device);
  8587. return true;
  8588. }
  8589. else {
  8590. return false;
  8591. }
  8592. });
  8593. if (!found) {
  8594. BABYLON.Tools.Warn("Display " + name + " was not found. Using " + devices[0].displayName);
  8595. callback(devices[0]);
  8596. }
  8597. }
  8598. else {
  8599. //choose the first one
  8600. callback(devices[0]);
  8601. }
  8602. }
  8603. else {
  8604. BABYLON.Tools.Error("No WebVR devices found!");
  8605. callback(null);
  8606. }
  8607. });
  8608. };
  8609. Engine.prototype.initWebVR = function () {
  8610. if (!this.vrDisplaysPromise) {
  8611. this._getVRDisplays();
  8612. }
  8613. };
  8614. Engine.prototype.enableVR = function (vrDevice) {
  8615. this._vrDisplayEnabled = vrDevice;
  8616. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8617. };
  8618. Engine.prototype.disableVR = function () {
  8619. if (this._vrDisplayEnabled) {
  8620. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8621. }
  8622. };
  8623. Engine.prototype._getVRDisplays = function () {
  8624. var _this = this;
  8625. var getWebVRDevices = function (devices) {
  8626. _this._vrDisplays = devices.filter(function (device) {
  8627. return device instanceof VRDisplay;
  8628. });
  8629. return _this._vrDisplays;
  8630. };
  8631. if (navigator.getVRDisplays) {
  8632. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8633. }
  8634. };
  8635. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  8636. if (this._currentRenderTarget) {
  8637. this.unBindFramebuffer(this._currentRenderTarget);
  8638. }
  8639. this._currentRenderTarget = texture;
  8640. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8641. var gl = this._gl;
  8642. if (texture.isCube) {
  8643. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  8644. }
  8645. if (this._cachedViewport && !forceFullscreenViewport) {
  8646. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  8647. }
  8648. else {
  8649. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  8650. }
  8651. this.wipeCaches();
  8652. };
  8653. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8654. if (this._currentFramebuffer !== framebuffer) {
  8655. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8656. this._currentFramebuffer = framebuffer;
  8657. }
  8658. };
  8659. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8660. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8661. this._currentRenderTarget = null;
  8662. // If MSAA, we need to bitblt back to main texture
  8663. var gl = this._gl;
  8664. if (texture._MSAAFramebuffer) {
  8665. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8666. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8667. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8668. }
  8669. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  8670. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8671. gl.generateMipmap(gl.TEXTURE_2D);
  8672. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8673. }
  8674. if (onBeforeUnbind) {
  8675. if (texture._MSAAFramebuffer) {
  8676. // Bind the correct framebuffer
  8677. this.bindUnboundFramebuffer(texture._framebuffer);
  8678. }
  8679. onBeforeUnbind();
  8680. }
  8681. this.bindUnboundFramebuffer(null);
  8682. };
  8683. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8684. if (texture.generateMipMaps) {
  8685. var gl = this._gl;
  8686. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8687. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8688. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8689. }
  8690. };
  8691. Engine.prototype.flushFramebuffer = function () {
  8692. this._gl.flush();
  8693. };
  8694. Engine.prototype.restoreDefaultFramebuffer = function () {
  8695. if (this._currentRenderTarget) {
  8696. this.unBindFramebuffer(this._currentRenderTarget);
  8697. }
  8698. else {
  8699. this.bindUnboundFramebuffer(null);
  8700. }
  8701. if (this._cachedViewport) {
  8702. this.setViewport(this._cachedViewport);
  8703. }
  8704. this.wipeCaches();
  8705. };
  8706. // UBOs
  8707. Engine.prototype.createUniformBuffer = function (elements) {
  8708. var ubo = this._gl.createBuffer();
  8709. this.bindUniformBuffer(ubo);
  8710. if (elements instanceof Float32Array) {
  8711. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  8712. }
  8713. else {
  8714. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  8715. }
  8716. this.bindUniformBuffer(null);
  8717. ubo.references = 1;
  8718. return ubo;
  8719. };
  8720. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  8721. var ubo = this._gl.createBuffer();
  8722. this.bindUniformBuffer(ubo);
  8723. if (elements instanceof Float32Array) {
  8724. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  8725. }
  8726. else {
  8727. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  8728. }
  8729. this.bindUniformBuffer(null);
  8730. ubo.references = 1;
  8731. return ubo;
  8732. };
  8733. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  8734. this.bindUniformBuffer(uniformBuffer);
  8735. if (offset === undefined) {
  8736. offset = 0;
  8737. }
  8738. if (count === undefined) {
  8739. if (elements instanceof Float32Array) {
  8740. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  8741. }
  8742. else {
  8743. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  8744. }
  8745. }
  8746. else {
  8747. if (elements instanceof Float32Array) {
  8748. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  8749. }
  8750. else {
  8751. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  8752. }
  8753. }
  8754. this.bindUniformBuffer(null);
  8755. };
  8756. // VBOs
  8757. Engine.prototype._resetVertexBufferBinding = function () {
  8758. this.bindArrayBuffer(null);
  8759. this._cachedVertexBuffers = null;
  8760. };
  8761. Engine.prototype.createVertexBuffer = function (vertices) {
  8762. var vbo = this._gl.createBuffer();
  8763. this.bindArrayBuffer(vbo);
  8764. if (vertices instanceof Float32Array) {
  8765. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8766. }
  8767. else {
  8768. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8769. }
  8770. this._resetVertexBufferBinding();
  8771. vbo.references = 1;
  8772. return vbo;
  8773. };
  8774. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8775. var vbo = this._gl.createBuffer();
  8776. this.bindArrayBuffer(vbo);
  8777. if (vertices instanceof Float32Array) {
  8778. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8779. }
  8780. else {
  8781. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8782. }
  8783. this._resetVertexBufferBinding();
  8784. vbo.references = 1;
  8785. return vbo;
  8786. };
  8787. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8788. this.bindArrayBuffer(vertexBuffer);
  8789. if (offset === undefined) {
  8790. offset = 0;
  8791. }
  8792. if (count === undefined) {
  8793. if (vertices instanceof Float32Array) {
  8794. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8795. }
  8796. else {
  8797. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8798. }
  8799. }
  8800. else {
  8801. if (vertices instanceof Float32Array) {
  8802. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8803. }
  8804. else {
  8805. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8806. }
  8807. }
  8808. this._resetVertexBufferBinding();
  8809. };
  8810. Engine.prototype._resetIndexBufferBinding = function () {
  8811. this.bindIndexBuffer(null);
  8812. this._cachedIndexBuffer = null;
  8813. };
  8814. Engine.prototype.createIndexBuffer = function (indices) {
  8815. var vbo = this._gl.createBuffer();
  8816. this.bindIndexBuffer(vbo);
  8817. // Check for 32 bits indices
  8818. var arrayBuffer;
  8819. var need32Bits = false;
  8820. if (indices instanceof Uint16Array) {
  8821. arrayBuffer = indices;
  8822. }
  8823. else {
  8824. //check 32 bit support
  8825. if (this._caps.uintIndices) {
  8826. if (indices instanceof Uint32Array) {
  8827. arrayBuffer = indices;
  8828. need32Bits = true;
  8829. }
  8830. else {
  8831. //number[] or Int32Array, check if 32 bit is necessary
  8832. for (var index = 0; index < indices.length; index++) {
  8833. if (indices[index] > 65535) {
  8834. need32Bits = true;
  8835. break;
  8836. }
  8837. }
  8838. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8839. }
  8840. }
  8841. else {
  8842. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8843. arrayBuffer = new Uint16Array(indices);
  8844. }
  8845. }
  8846. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8847. this._resetIndexBufferBinding();
  8848. vbo.references = 1;
  8849. vbo.is32Bits = need32Bits;
  8850. return vbo;
  8851. };
  8852. Engine.prototype.bindArrayBuffer = function (buffer) {
  8853. if (!this._vaoRecordInProgress) {
  8854. this._unbindVertexArrayObject();
  8855. }
  8856. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8857. };
  8858. Engine.prototype.bindUniformBuffer = function (buffer) {
  8859. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  8860. };
  8861. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  8862. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  8863. };
  8864. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  8865. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  8866. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  8867. };
  8868. ;
  8869. Engine.prototype.bindIndexBuffer = function (buffer) {
  8870. if (!this._vaoRecordInProgress) {
  8871. this._unbindVertexArrayObject();
  8872. }
  8873. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8874. };
  8875. Engine.prototype.bindBuffer = function (buffer, target) {
  8876. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8877. this._gl.bindBuffer(target, buffer);
  8878. this._currentBoundBuffer[target] = buffer;
  8879. }
  8880. };
  8881. Engine.prototype.updateArrayBuffer = function (data) {
  8882. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8883. };
  8884. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  8885. var pointer = this._currentBufferPointers[indx];
  8886. var changed = false;
  8887. if (!pointer.active) {
  8888. changed = true;
  8889. pointer.active = true;
  8890. pointer.index = indx;
  8891. pointer.size = size;
  8892. pointer.type = type;
  8893. pointer.normalized = normalized;
  8894. pointer.stride = stride;
  8895. pointer.offset = offset;
  8896. pointer.buffer = buffer;
  8897. }
  8898. else {
  8899. if (pointer.buffer !== buffer) {
  8900. pointer.buffer = buffer;
  8901. changed = true;
  8902. }
  8903. if (pointer.size !== size) {
  8904. pointer.size = size;
  8905. changed = true;
  8906. }
  8907. if (pointer.type !== type) {
  8908. pointer.type = type;
  8909. changed = true;
  8910. }
  8911. if (pointer.normalized !== normalized) {
  8912. pointer.normalized = normalized;
  8913. changed = true;
  8914. }
  8915. if (pointer.stride !== stride) {
  8916. pointer.stride = stride;
  8917. changed = true;
  8918. }
  8919. if (pointer.offset !== offset) {
  8920. pointer.offset = offset;
  8921. changed = true;
  8922. }
  8923. }
  8924. if (changed || this._vaoRecordInProgress) {
  8925. this.bindArrayBuffer(buffer);
  8926. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  8927. }
  8928. };
  8929. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  8930. if (indexBuffer == null) {
  8931. return;
  8932. }
  8933. if (this._cachedIndexBuffer !== indexBuffer) {
  8934. this._cachedIndexBuffer = indexBuffer;
  8935. this.bindIndexBuffer(indexBuffer);
  8936. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  8937. }
  8938. };
  8939. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  8940. var attributes = effect.getAttributesNames();
  8941. if (!this._vaoRecordInProgress) {
  8942. this._unbindVertexArrayObject();
  8943. }
  8944. this.unbindAllAttributes();
  8945. for (var index = 0; index < attributes.length; index++) {
  8946. var order = effect.getAttributeLocation(index);
  8947. if (order >= 0) {
  8948. var vertexBuffer = vertexBuffers[attributes[index]];
  8949. if (!vertexBuffer) {
  8950. continue;
  8951. }
  8952. this._gl.enableVertexAttribArray(order);
  8953. if (!this._vaoRecordInProgress) {
  8954. this._vertexAttribArraysEnabled[order] = true;
  8955. }
  8956. var buffer = vertexBuffer.getBuffer();
  8957. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  8958. if (vertexBuffer.getIsInstanced()) {
  8959. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  8960. if (!this._vaoRecordInProgress) {
  8961. this._currentInstanceLocations.push(order);
  8962. this._currentInstanceBuffers.push(buffer);
  8963. }
  8964. }
  8965. }
  8966. }
  8967. };
  8968. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  8969. var vao = this._gl.createVertexArray();
  8970. this._vaoRecordInProgress = true;
  8971. this._gl.bindVertexArray(vao);
  8972. this._mustWipeVertexAttributes = true;
  8973. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8974. this.bindIndexBuffer(indexBuffer);
  8975. this._vaoRecordInProgress = false;
  8976. this._gl.bindVertexArray(null);
  8977. return vao;
  8978. };
  8979. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  8980. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  8981. this._cachedVertexArrayObject = vertexArrayObject;
  8982. this._gl.bindVertexArray(vertexArrayObject);
  8983. this._cachedVertexBuffers = null;
  8984. this._cachedIndexBuffer = null;
  8985. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  8986. this._mustWipeVertexAttributes = true;
  8987. }
  8988. };
  8989. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  8990. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  8991. this._cachedVertexBuffers = vertexBuffer;
  8992. this._cachedEffectForVertexBuffers = effect;
  8993. var attributesCount = effect.getAttributesCount();
  8994. this._unbindVertexArrayObject();
  8995. this.unbindAllAttributes();
  8996. var offset = 0;
  8997. for (var index = 0; index < attributesCount; index++) {
  8998. if (index < vertexDeclaration.length) {
  8999. var order = effect.getAttributeLocation(index);
  9000. if (order >= 0) {
  9001. this._gl.enableVertexAttribArray(order);
  9002. this._vertexAttribArraysEnabled[order] = true;
  9003. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9004. }
  9005. offset += vertexDeclaration[index] * 4;
  9006. }
  9007. }
  9008. }
  9009. this._bindIndexBufferWithCache(indexBuffer);
  9010. };
  9011. Engine.prototype._unbindVertexArrayObject = function () {
  9012. if (!this._cachedVertexArrayObject) {
  9013. return;
  9014. }
  9015. this._cachedVertexArrayObject = null;
  9016. this._gl.bindVertexArray(null);
  9017. };
  9018. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9019. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9020. this._cachedVertexBuffers = vertexBuffers;
  9021. this._cachedEffectForVertexBuffers = effect;
  9022. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9023. }
  9024. this._bindIndexBufferWithCache(indexBuffer);
  9025. };
  9026. Engine.prototype.unbindInstanceAttributes = function () {
  9027. var boundBuffer;
  9028. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9029. var instancesBuffer = this._currentInstanceBuffers[i];
  9030. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9031. boundBuffer = instancesBuffer;
  9032. this.bindArrayBuffer(instancesBuffer);
  9033. }
  9034. var offsetLocation = this._currentInstanceLocations[i];
  9035. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9036. }
  9037. this._currentInstanceBuffers.length = 0;
  9038. this._currentInstanceLocations.length = 0;
  9039. };
  9040. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9041. this._gl.deleteVertexArray(vao);
  9042. };
  9043. Engine.prototype._releaseBuffer = function (buffer) {
  9044. buffer.references--;
  9045. if (buffer.references === 0) {
  9046. this._gl.deleteBuffer(buffer);
  9047. return true;
  9048. }
  9049. return false;
  9050. };
  9051. Engine.prototype.createInstancesBuffer = function (capacity) {
  9052. var buffer = this._gl.createBuffer();
  9053. buffer.capacity = capacity;
  9054. this.bindArrayBuffer(buffer);
  9055. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9056. return buffer;
  9057. };
  9058. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9059. this._gl.deleteBuffer(buffer);
  9060. };
  9061. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9062. this.bindArrayBuffer(instancesBuffer);
  9063. if (data) {
  9064. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9065. }
  9066. if (offsetLocations[0].index !== undefined) {
  9067. var stride = 0;
  9068. for (var i = 0; i < offsetLocations.length; i++) {
  9069. var ai = offsetLocations[i];
  9070. stride += ai.attributeSize * 4;
  9071. }
  9072. for (var i = 0; i < offsetLocations.length; i++) {
  9073. var ai = offsetLocations[i];
  9074. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9075. this._gl.enableVertexAttribArray(ai.index);
  9076. this._vertexAttribArraysEnabled[ai.index] = true;
  9077. }
  9078. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9079. this._gl.vertexAttribDivisor(ai.index, 1);
  9080. this._currentInstanceLocations.push(ai.index);
  9081. this._currentInstanceBuffers.push(instancesBuffer);
  9082. }
  9083. }
  9084. else {
  9085. for (var index = 0; index < 4; index++) {
  9086. var offsetLocation = offsetLocations[index];
  9087. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9088. this._gl.enableVertexAttribArray(offsetLocation);
  9089. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9090. }
  9091. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9092. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9093. this._currentInstanceLocations.push(offsetLocation);
  9094. this._currentInstanceBuffers.push(instancesBuffer);
  9095. }
  9096. }
  9097. };
  9098. Engine.prototype.applyStates = function () {
  9099. this._depthCullingState.apply(this._gl);
  9100. this._stencilState.apply(this._gl);
  9101. this._alphaState.apply(this._gl);
  9102. };
  9103. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9104. // Apply states
  9105. this.applyStates();
  9106. this._drawCalls.addCount(1, false);
  9107. // Render
  9108. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9109. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9110. if (instancesCount) {
  9111. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9112. return;
  9113. }
  9114. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9115. };
  9116. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9117. // Apply states
  9118. this.applyStates();
  9119. this._drawCalls.addCount(1, false);
  9120. if (instancesCount) {
  9121. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9122. return;
  9123. }
  9124. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9125. };
  9126. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9127. // Apply states
  9128. this.applyStates();
  9129. this._drawCalls.addCount(1, false);
  9130. if (instancesCount) {
  9131. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9132. return;
  9133. }
  9134. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9135. };
  9136. // Shaders
  9137. Engine.prototype._releaseEffect = function (effect) {
  9138. if (this._compiledEffects[effect._key]) {
  9139. delete this._compiledEffects[effect._key];
  9140. if (effect.getProgram()) {
  9141. this._gl.deleteProgram(effect.getProgram());
  9142. }
  9143. }
  9144. };
  9145. /**
  9146. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9147. * @param samplers An array of string used to represent textures
  9148. */
  9149. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9150. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9151. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9152. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9153. if (this._compiledEffects[name]) {
  9154. var compiledEffect = this._compiledEffects[name];
  9155. if (onCompiled && compiledEffect.isReady()) {
  9156. onCompiled(compiledEffect);
  9157. }
  9158. return compiledEffect;
  9159. }
  9160. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9161. effect._key = name;
  9162. this._compiledEffects[name] = effect;
  9163. return effect;
  9164. };
  9165. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9166. if (uniformsNames === void 0) { uniformsNames = []; }
  9167. if (samplers === void 0) { samplers = []; }
  9168. if (defines === void 0) { defines = ""; }
  9169. return this.createEffect({
  9170. vertex: "particles",
  9171. fragmentElement: fragmentName
  9172. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9173. };
  9174. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  9175. context = context || this._gl;
  9176. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9177. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9178. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9179. var shaderProgram = context.createProgram();
  9180. context.attachShader(shaderProgram, vertexShader);
  9181. context.attachShader(shaderProgram, fragmentShader);
  9182. context.linkProgram(shaderProgram);
  9183. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9184. if (!linked) {
  9185. context.validateProgram(shaderProgram);
  9186. var error = context.getProgramInfoLog(shaderProgram);
  9187. if (error) {
  9188. throw new Error(error);
  9189. }
  9190. }
  9191. context.deleteShader(vertexShader);
  9192. context.deleteShader(fragmentShader);
  9193. return shaderProgram;
  9194. };
  9195. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9196. var results = [];
  9197. for (var index = 0; index < uniformsNames.length; index++) {
  9198. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9199. }
  9200. return results;
  9201. };
  9202. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9203. var results = [];
  9204. for (var index = 0; index < attributesNames.length; index++) {
  9205. try {
  9206. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9207. }
  9208. catch (e) {
  9209. results.push(-1);
  9210. }
  9211. }
  9212. return results;
  9213. };
  9214. Engine.prototype.enableEffect = function (effect) {
  9215. // Use program
  9216. this.setProgram(effect.getProgram());
  9217. this._currentEffect = effect;
  9218. if (effect.onBind) {
  9219. effect.onBind(effect);
  9220. }
  9221. effect.onBindObservable.notifyObservers(effect);
  9222. };
  9223. Engine.prototype.setIntArray = function (uniform, array) {
  9224. if (!uniform)
  9225. return;
  9226. this._gl.uniform1iv(uniform, array);
  9227. };
  9228. Engine.prototype.setIntArray2 = function (uniform, array) {
  9229. if (!uniform || array.length % 2 !== 0)
  9230. return;
  9231. this._gl.uniform2iv(uniform, array);
  9232. };
  9233. Engine.prototype.setIntArray3 = function (uniform, array) {
  9234. if (!uniform || array.length % 3 !== 0)
  9235. return;
  9236. this._gl.uniform3iv(uniform, array);
  9237. };
  9238. Engine.prototype.setIntArray4 = function (uniform, array) {
  9239. if (!uniform || array.length % 4 !== 0)
  9240. return;
  9241. this._gl.uniform4iv(uniform, array);
  9242. };
  9243. Engine.prototype.setFloatArray = function (uniform, array) {
  9244. if (!uniform)
  9245. return;
  9246. this._gl.uniform1fv(uniform, array);
  9247. };
  9248. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9249. if (!uniform || array.length % 2 !== 0)
  9250. return;
  9251. this._gl.uniform2fv(uniform, array);
  9252. };
  9253. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9254. if (!uniform || array.length % 3 !== 0)
  9255. return;
  9256. this._gl.uniform3fv(uniform, array);
  9257. };
  9258. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9259. if (!uniform || array.length % 4 !== 0)
  9260. return;
  9261. this._gl.uniform4fv(uniform, array);
  9262. };
  9263. Engine.prototype.setArray = function (uniform, array) {
  9264. if (!uniform)
  9265. return;
  9266. this._gl.uniform1fv(uniform, array);
  9267. };
  9268. Engine.prototype.setArray2 = function (uniform, array) {
  9269. if (!uniform || array.length % 2 !== 0)
  9270. return;
  9271. this._gl.uniform2fv(uniform, array);
  9272. };
  9273. Engine.prototype.setArray3 = function (uniform, array) {
  9274. if (!uniform || array.length % 3 !== 0)
  9275. return;
  9276. this._gl.uniform3fv(uniform, array);
  9277. };
  9278. Engine.prototype.setArray4 = function (uniform, array) {
  9279. if (!uniform || array.length % 4 !== 0)
  9280. return;
  9281. this._gl.uniform4fv(uniform, array);
  9282. };
  9283. Engine.prototype.setMatrices = function (uniform, matrices) {
  9284. if (!uniform)
  9285. return;
  9286. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9287. };
  9288. Engine.prototype.setMatrix = function (uniform, matrix) {
  9289. if (!uniform)
  9290. return;
  9291. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9292. };
  9293. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9294. if (!uniform)
  9295. return;
  9296. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9297. };
  9298. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9299. if (!uniform)
  9300. return;
  9301. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9302. };
  9303. Engine.prototype.setFloat = function (uniform, value) {
  9304. if (!uniform)
  9305. return;
  9306. this._gl.uniform1f(uniform, value);
  9307. };
  9308. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9309. if (!uniform)
  9310. return;
  9311. this._gl.uniform2f(uniform, x, y);
  9312. };
  9313. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9314. if (!uniform)
  9315. return;
  9316. this._gl.uniform3f(uniform, x, y, z);
  9317. };
  9318. Engine.prototype.setBool = function (uniform, bool) {
  9319. if (!uniform)
  9320. return;
  9321. this._gl.uniform1i(uniform, bool);
  9322. };
  9323. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9324. if (!uniform)
  9325. return;
  9326. this._gl.uniform4f(uniform, x, y, z, w);
  9327. };
  9328. Engine.prototype.setColor3 = function (uniform, color3) {
  9329. if (!uniform)
  9330. return;
  9331. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9332. };
  9333. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9334. if (!uniform)
  9335. return;
  9336. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9337. };
  9338. // States
  9339. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9340. if (zOffset === void 0) { zOffset = 0; }
  9341. if (reverseSide === void 0) { reverseSide = false; }
  9342. // Culling
  9343. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9344. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9345. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9346. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9347. if (culling) {
  9348. this._depthCullingState.cullFace = cullFace;
  9349. this._depthCullingState.cull = true;
  9350. }
  9351. else {
  9352. this._depthCullingState.cull = false;
  9353. }
  9354. }
  9355. // Z offset
  9356. this.setZOffset(zOffset);
  9357. };
  9358. Engine.prototype.setZOffset = function (value) {
  9359. this._depthCullingState.zOffset = value;
  9360. };
  9361. Engine.prototype.getZOffset = function () {
  9362. return this._depthCullingState.zOffset;
  9363. };
  9364. Engine.prototype.setDepthBuffer = function (enable) {
  9365. this._depthCullingState.depthTest = enable;
  9366. };
  9367. Engine.prototype.getDepthWrite = function () {
  9368. return this._depthCullingState.depthMask;
  9369. };
  9370. Engine.prototype.setDepthWrite = function (enable) {
  9371. this._depthCullingState.depthMask = enable;
  9372. };
  9373. Engine.prototype.setColorWrite = function (enable) {
  9374. this._gl.colorMask(enable, enable, enable, enable);
  9375. };
  9376. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  9377. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  9378. };
  9379. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  9380. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  9381. if (this._alphaMode === mode) {
  9382. return;
  9383. }
  9384. switch (mode) {
  9385. case Engine.ALPHA_DISABLE:
  9386. this._alphaState.alphaBlend = false;
  9387. break;
  9388. case Engine.ALPHA_PREMULTIPLIED:
  9389. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9390. this._alphaState.alphaBlend = true;
  9391. break;
  9392. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  9393. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9394. this._alphaState.alphaBlend = true;
  9395. break;
  9396. case Engine.ALPHA_COMBINE:
  9397. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9398. this._alphaState.alphaBlend = true;
  9399. break;
  9400. case Engine.ALPHA_ONEONE:
  9401. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9402. this._alphaState.alphaBlend = true;
  9403. break;
  9404. case Engine.ALPHA_ADD:
  9405. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9406. this._alphaState.alphaBlend = true;
  9407. break;
  9408. case Engine.ALPHA_SUBTRACT:
  9409. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9410. this._alphaState.alphaBlend = true;
  9411. break;
  9412. case Engine.ALPHA_MULTIPLY:
  9413. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  9414. this._alphaState.alphaBlend = true;
  9415. break;
  9416. case Engine.ALPHA_MAXIMIZED:
  9417. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9418. this._alphaState.alphaBlend = true;
  9419. break;
  9420. case Engine.ALPHA_INTERPOLATE:
  9421. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  9422. this._alphaState.alphaBlend = true;
  9423. break;
  9424. case Engine.ALPHA_SCREENMODE:
  9425. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9426. this._alphaState.alphaBlend = true;
  9427. break;
  9428. }
  9429. if (!noDepthWriteChange) {
  9430. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9431. }
  9432. this._alphaMode = mode;
  9433. };
  9434. Engine.prototype.getAlphaMode = function () {
  9435. return this._alphaMode;
  9436. };
  9437. Engine.prototype.setAlphaTesting = function (enable) {
  9438. this._alphaTest = enable;
  9439. };
  9440. Engine.prototype.getAlphaTesting = function () {
  9441. return !!this._alphaTest;
  9442. };
  9443. // Textures
  9444. Engine.prototype.wipeCaches = function (bruteForce) {
  9445. if (this.preventCacheWipeBetweenFrames) {
  9446. return;
  9447. }
  9448. this.resetTextureCache();
  9449. this._currentEffect = null;
  9450. // 6/8/2017: deltakosh: Should not be required anymore.
  9451. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  9452. if (bruteForce) {
  9453. this._currentProgram = null;
  9454. this._stencilState.reset();
  9455. this._depthCullingState.reset();
  9456. this.setDepthFunctionToLessOrEqual();
  9457. this._alphaState.reset();
  9458. }
  9459. this._cachedVertexBuffers = null;
  9460. this._cachedIndexBuffer = null;
  9461. this._cachedEffectForVertexBuffers = null;
  9462. this._unbindVertexArrayObject();
  9463. this.bindIndexBuffer(null);
  9464. this.bindArrayBuffer(null);
  9465. };
  9466. /**
  9467. * Set the compressed texture format to use, based on the formats you have, and the formats
  9468. * supported by the hardware / browser.
  9469. *
  9470. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9471. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9472. * to API arguments needed to compressed textures. This puts the burden on the container
  9473. * generator to house the arcane code for determining these for current & future formats.
  9474. *
  9475. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9476. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9477. *
  9478. * Note: The result of this call is not taken into account when a texture is base64.
  9479. *
  9480. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9481. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9482. *
  9483. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  9484. * @returns The extension selected.
  9485. */
  9486. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9487. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9488. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9489. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9490. return this._textureFormatInUse = this._texturesSupported[i];
  9491. }
  9492. }
  9493. }
  9494. // actively set format to nothing, to allow this to be called more than once
  9495. // and possibly fail the 2nd time
  9496. return this._textureFormatInUse = null;
  9497. };
  9498. Engine.prototype._createTexture = function () {
  9499. return this._gl.createTexture();
  9500. };
  9501. /**
  9502. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  9503. * @param {string} urlArg- This contains one of the following:
  9504. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  9505. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  9506. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  9507. *
  9508. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  9509. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  9510. * @param {Scene} scene- Needed for loading to the correct scene.
  9511. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  9512. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  9513. * @param {callback} onError- Optional callback to be called upon failure.
  9514. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  9515. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  9516. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  9517. *
  9518. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  9519. */
  9520. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9521. var _this = this;
  9522. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9523. if (onLoad === void 0) { onLoad = null; }
  9524. if (onError === void 0) { onError = null; }
  9525. if (buffer === void 0) { buffer = null; }
  9526. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  9527. var fromData = url.substr(0, 5) === "data:";
  9528. var fromBlob = url.substr(0, 5) === "blob:";
  9529. var isBase64 = fromData && url.indexOf("base64") !== -1;
  9530. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  9531. // establish the file extension, if possible
  9532. var lastDot = url.lastIndexOf('.');
  9533. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  9534. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9535. var isTGA = (extension === ".tga");
  9536. // determine if a ktx file should be substituted
  9537. var isKTX = false;
  9538. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  9539. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9540. isKTX = true;
  9541. }
  9542. if (scene) {
  9543. scene._addPendingData(texture);
  9544. }
  9545. texture.url = url;
  9546. texture.generateMipMaps = !noMipmap;
  9547. texture.samplingMode = samplingMode;
  9548. texture.invertY = invertY;
  9549. if (!this._doNotHandleContextLost) {
  9550. // Keep a link to the buffer only if we plan to handle context lost
  9551. texture._buffer = buffer;
  9552. }
  9553. if (onLoad) {
  9554. texture.onLoadedObservable.add(onLoad);
  9555. }
  9556. if (!fallBack)
  9557. this._internalTexturesCache.push(texture);
  9558. var onerror = function () {
  9559. if (scene) {
  9560. scene._removePendingData(texture);
  9561. }
  9562. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9563. if (isKTX) {
  9564. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  9565. }
  9566. else if (onError) {
  9567. onError();
  9568. }
  9569. };
  9570. var callback;
  9571. // processing for non-image formats
  9572. if (isKTX || isTGA || isDDS) {
  9573. if (isKTX) {
  9574. callback = function (data) {
  9575. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9576. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9577. ktx.uploadLevels(_this._gl, !noMipmap);
  9578. return false;
  9579. }, samplingMode);
  9580. };
  9581. }
  9582. else if (isTGA) {
  9583. callback = function (arrayBuffer) {
  9584. var data = new Uint8Array(arrayBuffer);
  9585. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9586. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9587. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9588. return false;
  9589. }, samplingMode);
  9590. };
  9591. }
  9592. else if (isDDS) {
  9593. callback = function (data) {
  9594. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9595. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9596. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9597. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  9598. return false;
  9599. }, samplingMode);
  9600. };
  9601. }
  9602. if (!buffer) {
  9603. BABYLON.Tools.LoadFile(url, function (data) {
  9604. callback(data);
  9605. }, null, scene ? scene.database : null, true, onerror);
  9606. }
  9607. else {
  9608. callback(buffer);
  9609. }
  9610. // image format processing
  9611. }
  9612. else {
  9613. var onload = function (img) {
  9614. if (fromBlob && !_this._doNotHandleContextLost) {
  9615. // We need to store the image if we need to rebuild the texture
  9616. // in case of a webgl context lost
  9617. texture._buffer = img;
  9618. }
  9619. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  9620. var gl = _this._gl;
  9621. var isPot = (img.width === potWidth && img.height === potHeight);
  9622. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  9623. if (isPot) {
  9624. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  9625. return false;
  9626. }
  9627. // Using shaders to rescale because canvas.drawImage is lossy
  9628. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  9629. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  9630. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  9631. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9632. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  9633. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9634. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9635. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  9636. _this._releaseTexture(source);
  9637. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9638. continuationCallback();
  9639. });
  9640. return true;
  9641. }, samplingMode);
  9642. };
  9643. if (!fromData || isBase64)
  9644. if (buffer instanceof HTMLImageElement) {
  9645. onload(buffer);
  9646. }
  9647. else {
  9648. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  9649. }
  9650. else if (buffer instanceof Array || typeof buffer === "string")
  9651. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  9652. else
  9653. onload(buffer);
  9654. }
  9655. return texture;
  9656. };
  9657. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  9658. var _this = this;
  9659. var rtt = this.createRenderTargetTexture({
  9660. width: destination.width,
  9661. height: destination.height,
  9662. }, {
  9663. generateMipMaps: false,
  9664. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  9665. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  9666. generateDepthBuffer: false,
  9667. generateStencilBuffer: false
  9668. });
  9669. if (!this._rescalePostProcess) {
  9670. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  9671. }
  9672. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  9673. _this._rescalePostProcess.onApply = function (effect) {
  9674. effect._bindTexture("textureSampler", source);
  9675. };
  9676. scene.postProcessManager.directRender([_this._rescalePostProcess], rtt);
  9677. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  9678. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  9679. _this.unBindFramebuffer(rtt);
  9680. _this._releaseTexture(rtt);
  9681. if (onComplete) {
  9682. onComplete();
  9683. }
  9684. });
  9685. };
  9686. Engine.prototype._getInternalFormat = function (format) {
  9687. var internalFormat = this._gl.RGBA;
  9688. switch (format) {
  9689. case Engine.TEXTUREFORMAT_ALPHA:
  9690. internalFormat = this._gl.ALPHA;
  9691. break;
  9692. case Engine.TEXTUREFORMAT_LUMINANCE:
  9693. internalFormat = this._gl.LUMINANCE;
  9694. break;
  9695. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9696. internalFormat = this._gl.LUMINANCE_ALPHA;
  9697. break;
  9698. case Engine.TEXTUREFORMAT_RGB:
  9699. internalFormat = this._gl.RGB;
  9700. break;
  9701. case Engine.TEXTUREFORMAT_RGBA:
  9702. internalFormat = this._gl.RGBA;
  9703. break;
  9704. }
  9705. return internalFormat;
  9706. };
  9707. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9708. if (compression === void 0) { compression = null; }
  9709. var internalFormat = this._getInternalFormat(format);
  9710. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9711. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9712. if (!this._doNotHandleContextLost) {
  9713. texture._bufferView = data;
  9714. texture.format = format;
  9715. texture.invertY = invertY;
  9716. texture._compression = compression;
  9717. }
  9718. if (texture.width % 4 !== 0) {
  9719. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9720. }
  9721. if (compression) {
  9722. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  9723. }
  9724. else {
  9725. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture.width, texture.height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9726. }
  9727. if (texture.generateMipMaps) {
  9728. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9729. }
  9730. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9731. this.resetTextureCache();
  9732. texture.isReady = true;
  9733. };
  9734. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9735. if (compression === void 0) { compression = null; }
  9736. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  9737. texture.baseWidth = width;
  9738. texture.baseHeight = height;
  9739. texture.width = width;
  9740. texture.height = height;
  9741. texture.format = format;
  9742. texture.generateMipMaps = generateMipMaps;
  9743. texture.samplingMode = samplingMode;
  9744. texture.invertY = invertY;
  9745. texture._compression = compression;
  9746. if (!this._doNotHandleContextLost) {
  9747. texture._bufferView = data;
  9748. }
  9749. this.updateRawTexture(texture, data, format, invertY, compression);
  9750. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9751. // Filters
  9752. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9753. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9754. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9755. if (generateMipMaps) {
  9756. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9757. }
  9758. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9759. this._internalTexturesCache.push(texture);
  9760. return texture;
  9761. };
  9762. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9763. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  9764. texture.baseWidth = width;
  9765. texture.baseHeight = height;
  9766. if (generateMipMaps) {
  9767. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  9768. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  9769. }
  9770. this.resetTextureCache();
  9771. texture.width = width;
  9772. texture.height = height;
  9773. texture.isReady = false;
  9774. texture.generateMipMaps = generateMipMaps;
  9775. texture.samplingMode = samplingMode;
  9776. this.updateTextureSamplingMode(samplingMode, texture);
  9777. this._internalTexturesCache.push(texture);
  9778. return texture;
  9779. };
  9780. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9781. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9782. if (texture.isCube) {
  9783. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9784. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9785. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9786. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9787. }
  9788. else {
  9789. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9790. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9791. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9792. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9793. }
  9794. texture.samplingMode = samplingMode;
  9795. };
  9796. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9797. if (premulAlpha === void 0) { premulAlpha = false; }
  9798. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9799. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9800. if (premulAlpha) {
  9801. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9802. }
  9803. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9804. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9805. if (texture.generateMipMaps) {
  9806. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9807. }
  9808. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9809. if (premulAlpha) {
  9810. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9811. }
  9812. this.resetTextureCache();
  9813. texture.isReady = true;
  9814. };
  9815. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9816. if (texture._isDisabled) {
  9817. return;
  9818. }
  9819. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9820. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  9821. try {
  9822. // Testing video texture support
  9823. if (this._videoTextureSupported === undefined) {
  9824. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9825. if (this._gl.getError() !== 0) {
  9826. this._videoTextureSupported = false;
  9827. }
  9828. else {
  9829. this._videoTextureSupported = true;
  9830. }
  9831. }
  9832. // Copy video through the current working canvas if video texture is not supported
  9833. if (!this._videoTextureSupported) {
  9834. if (!texture._workingCanvas) {
  9835. texture._workingCanvas = document.createElement("canvas");
  9836. texture._workingContext = texture._workingCanvas.getContext("2d");
  9837. texture._workingCanvas.width = texture.width;
  9838. texture._workingCanvas.height = texture.height;
  9839. }
  9840. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  9841. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9842. }
  9843. else {
  9844. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9845. }
  9846. if (texture.generateMipMaps) {
  9847. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9848. }
  9849. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9850. this.resetTextureCache();
  9851. texture.isReady = true;
  9852. }
  9853. catch (ex) {
  9854. // Something unexpected
  9855. // Let's disable the texture
  9856. texture._isDisabled = true;
  9857. }
  9858. };
  9859. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9860. var fullOptions = new RenderTargetCreationOptions();
  9861. if (options !== undefined && typeof options === "object") {
  9862. fullOptions.generateMipMaps = options.generateMipMaps;
  9863. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9864. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  9865. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  9866. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  9867. }
  9868. else {
  9869. fullOptions.generateMipMaps = options;
  9870. fullOptions.generateDepthBuffer = true;
  9871. fullOptions.generateStencilBuffer = false;
  9872. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9873. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9874. }
  9875. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9876. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9877. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9878. }
  9879. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9880. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9881. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9882. }
  9883. var gl = this._gl;
  9884. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  9885. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9886. var width = size.width || size;
  9887. var height = size.height || size;
  9888. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  9889. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9890. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9891. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9892. }
  9893. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9894. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9895. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9896. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9897. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  9898. // Create the framebuffer
  9899. var framebuffer = gl.createFramebuffer();
  9900. this.bindUnboundFramebuffer(framebuffer);
  9901. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  9902. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, width, height);
  9903. if (fullOptions.generateMipMaps) {
  9904. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9905. }
  9906. // Unbind
  9907. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9908. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9909. this.bindUnboundFramebuffer(null);
  9910. texture._framebuffer = framebuffer;
  9911. texture.baseWidth = width;
  9912. texture.baseHeight = height;
  9913. texture.width = width;
  9914. texture.height = height;
  9915. texture.isReady = true;
  9916. texture.samples = 1;
  9917. texture.generateMipMaps = fullOptions.generateMipMaps;
  9918. texture.samplingMode = fullOptions.samplingMode;
  9919. texture.type = fullOptions.type;
  9920. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  9921. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  9922. this.resetTextureCache();
  9923. this._internalTexturesCache.push(texture);
  9924. return texture;
  9925. };
  9926. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  9927. var generateMipMaps = false;
  9928. var generateDepthBuffer = true;
  9929. var generateStencilBuffer = false;
  9930. var generateDepthTexture = false;
  9931. var textureCount = 1;
  9932. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  9933. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9934. var types = [], samplingModes = [];
  9935. if (options !== undefined) {
  9936. generateMipMaps = options.generateMipMaps;
  9937. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9938. generateStencilBuffer = options.generateStencilBuffer;
  9939. generateDepthTexture = options.generateDepthTexture;
  9940. textureCount = options.textureCount || 1;
  9941. if (options.types) {
  9942. types = options.types;
  9943. }
  9944. if (options.samplingModes) {
  9945. samplingModes = options.samplingModes;
  9946. }
  9947. }
  9948. var gl = this._gl;
  9949. // Create the framebuffer
  9950. var framebuffer = gl.createFramebuffer();
  9951. this.bindUnboundFramebuffer(framebuffer);
  9952. var width = size.width || size;
  9953. var height = size.height || size;
  9954. var textures = [];
  9955. var attachments = [];
  9956. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9957. for (var i = 0; i < textureCount; i++) {
  9958. var samplingMode = samplingModes[i] || defaultSamplingMode;
  9959. var type = types[i] || defaultType;
  9960. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9961. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9962. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9963. }
  9964. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9965. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9966. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9967. }
  9968. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9969. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9970. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9971. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9972. }
  9973. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  9974. var attachment = gl["COLOR_ATTACHMENT" + i];
  9975. textures.push(texture);
  9976. attachments.push(attachment);
  9977. gl.activeTexture(gl["TEXTURE" + i]);
  9978. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  9979. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9980. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9981. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9982. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9983. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9984. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  9985. if (generateMipMaps) {
  9986. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9987. }
  9988. // Unbind
  9989. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9990. texture._framebuffer = framebuffer;
  9991. texture._depthStencilBuffer = depthStencilBuffer;
  9992. texture.baseWidth = width;
  9993. texture.baseHeight = height;
  9994. texture.width = width;
  9995. texture.height = height;
  9996. texture.isReady = true;
  9997. texture.samples = 1;
  9998. texture.generateMipMaps = generateMipMaps;
  9999. texture.samplingMode = samplingMode;
  10000. texture.type = type;
  10001. texture._generateDepthBuffer = generateDepthBuffer;
  10002. texture._generateStencilBuffer = generateStencilBuffer;
  10003. this._internalTexturesCache.push(texture);
  10004. }
  10005. if (generateDepthTexture) {
  10006. // Depth texture
  10007. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10008. gl.activeTexture(gl.TEXTURE0);
  10009. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  10010. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10011. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10012. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10013. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10014. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  10015. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  10016. depthTexture._framebuffer = framebuffer;
  10017. depthTexture.baseWidth = width;
  10018. depthTexture.baseHeight = height;
  10019. depthTexture.width = width;
  10020. depthTexture.height = height;
  10021. depthTexture.isReady = true;
  10022. depthTexture.samples = 1;
  10023. depthTexture.generateMipMaps = generateMipMaps;
  10024. depthTexture.samplingMode = gl.NEAREST;
  10025. depthTexture._generateDepthBuffer = generateDepthBuffer;
  10026. depthTexture._generateStencilBuffer = generateStencilBuffer;
  10027. textures.push(depthTexture);
  10028. this._internalTexturesCache.push(depthTexture);
  10029. }
  10030. gl.drawBuffers(attachments);
  10031. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10032. this.bindUnboundFramebuffer(null);
  10033. this.resetTextureCache();
  10034. return textures;
  10035. };
  10036. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  10037. if (samples === void 0) { samples = 1; }
  10038. var depthStencilBuffer = null;
  10039. var gl = this._gl;
  10040. // Create the depth/stencil buffer
  10041. if (generateStencilBuffer) {
  10042. depthStencilBuffer = gl.createRenderbuffer();
  10043. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10044. if (samples > 1) {
  10045. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  10046. }
  10047. else {
  10048. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  10049. }
  10050. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10051. }
  10052. else if (generateDepthBuffer) {
  10053. depthStencilBuffer = gl.createRenderbuffer();
  10054. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10055. if (samples > 1) {
  10056. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  10057. }
  10058. else {
  10059. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  10060. }
  10061. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10062. }
  10063. return depthStencilBuffer;
  10064. };
  10065. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  10066. if (this.webGLVersion < 2) {
  10067. return 1;
  10068. }
  10069. if (texture.samples === samples) {
  10070. return samples;
  10071. }
  10072. var gl = this._gl;
  10073. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10074. // Dispose previous render buffers
  10075. if (texture._depthStencilBuffer) {
  10076. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10077. }
  10078. if (texture._MSAAFramebuffer) {
  10079. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10080. }
  10081. if (texture._MSAARenderBuffer) {
  10082. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10083. }
  10084. if (samples > 1) {
  10085. texture._MSAAFramebuffer = gl.createFramebuffer();
  10086. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  10087. var colorRenderbuffer = gl.createRenderbuffer();
  10088. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  10089. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  10090. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  10091. texture._MSAARenderBuffer = colorRenderbuffer;
  10092. }
  10093. else {
  10094. this.bindUnboundFramebuffer(texture._framebuffer);
  10095. }
  10096. texture.samples = samples;
  10097. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  10098. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10099. this.bindUnboundFramebuffer(null);
  10100. return samples;
  10101. };
  10102. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  10103. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  10104. };
  10105. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  10106. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  10107. };
  10108. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  10109. var gl = this._gl;
  10110. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10111. var generateMipMaps = true;
  10112. var generateDepthBuffer = true;
  10113. var generateStencilBuffer = false;
  10114. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10115. if (options !== undefined) {
  10116. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  10117. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10118. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  10119. if (options.samplingMode !== undefined) {
  10120. samplingMode = options.samplingMode;
  10121. }
  10122. }
  10123. texture.isCube = true;
  10124. texture.generateMipMaps = generateMipMaps;
  10125. texture.samples = 1;
  10126. texture.samplingMode = samplingMode;
  10127. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10128. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10129. for (var face = 0; face < 6; face++) {
  10130. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10131. }
  10132. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10133. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10134. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10135. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10136. // Create the framebuffer
  10137. var framebuffer = gl.createFramebuffer();
  10138. this.bindUnboundFramebuffer(framebuffer);
  10139. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10140. // Mipmaps
  10141. if (texture.generateMipMaps) {
  10142. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10143. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10144. }
  10145. // Unbind
  10146. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10147. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10148. this.bindUnboundFramebuffer(null);
  10149. texture._framebuffer = framebuffer;
  10150. texture.width = size;
  10151. texture.height = size;
  10152. texture.isReady = true;
  10153. this.resetTextureCache();
  10154. this._internalTexturesCache.push(texture);
  10155. return texture;
  10156. };
  10157. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  10158. var _this = this;
  10159. if (onError === void 0) { onError = null; }
  10160. if (forcedExtension === void 0) { forcedExtension = null; }
  10161. var callback = function (loadData) {
  10162. if (!loadData) {
  10163. if (onLoad) {
  10164. onLoad(null);
  10165. }
  10166. return;
  10167. }
  10168. var texture = loadData.texture;
  10169. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  10170. texture._lodGenerationScale = scale;
  10171. texture._lodGenerationOffset = offset;
  10172. if (_this._caps.textureLOD) {
  10173. // Do not add extra process if texture lod is supported.
  10174. if (onLoad) {
  10175. onLoad(texture);
  10176. }
  10177. return;
  10178. }
  10179. var mipSlices = 3;
  10180. var gl = _this._gl;
  10181. var width = loadData.width;
  10182. if (!width) {
  10183. return;
  10184. }
  10185. var textures = [];
  10186. for (var i = 0; i < mipSlices; i++) {
  10187. //compute LOD from even spacing in smoothness (matching shader calculation)
  10188. var smoothness = i / (mipSlices - 1);
  10189. var roughness = 1 - smoothness;
  10190. var minLODIndex = offset; // roughness = 0
  10191. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  10192. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  10193. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  10194. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10195. glTextureFromLod.isCube = true;
  10196. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  10197. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10198. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10199. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10200. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10201. if (loadData.isDDS) {
  10202. var info = loadData.info;
  10203. var data = loadData.data;
  10204. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10205. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  10206. }
  10207. else {
  10208. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  10209. }
  10210. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10211. // Wrap in a base texture for easy binding.
  10212. var lodTexture = new BABYLON.BaseTexture(scene);
  10213. lodTexture.isCube = true;
  10214. lodTexture._texture = glTextureFromLod;
  10215. glTextureFromLod.isReady = true;
  10216. textures.push(lodTexture);
  10217. }
  10218. texture._lodTextureHigh = textures[2];
  10219. texture._lodTextureMid = textures[1];
  10220. texture._lodTextureLow = textures[0];
  10221. if (onLoad) {
  10222. onLoad(texture);
  10223. }
  10224. };
  10225. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  10226. };
  10227. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  10228. var _this = this;
  10229. if (onLoad === void 0) { onLoad = null; }
  10230. if (onError === void 0) { onError = null; }
  10231. if (forcedExtension === void 0) { forcedExtension = null; }
  10232. var gl = this._gl;
  10233. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  10234. texture.isCube = true;
  10235. texture.url = rootUrl;
  10236. texture.generateMipMaps = !noMipmap;
  10237. if (!this._doNotHandleContextLost) {
  10238. texture._extension = forcedExtension;
  10239. texture._files = files;
  10240. }
  10241. var isKTX = false;
  10242. var isDDS = false;
  10243. var lastDot = rootUrl.lastIndexOf('.');
  10244. var extension = forcedExtension ? forcedExtension : rootUrl.substring(lastDot).toLowerCase();
  10245. if (this._textureFormatInUse) {
  10246. extension = this._textureFormatInUse;
  10247. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  10248. isKTX = true;
  10249. }
  10250. else {
  10251. isDDS = (extension === ".dds");
  10252. }
  10253. if (isKTX) {
  10254. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10255. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  10256. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  10257. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10258. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10259. ktx.uploadLevels(_this._gl, !noMipmap);
  10260. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10261. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10262. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10263. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10264. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10265. _this.resetTextureCache();
  10266. texture.width = ktx.pixelWidth;
  10267. texture.height = ktx.pixelHeight;
  10268. texture.isReady = true;
  10269. }, null, null, true, onError);
  10270. }
  10271. else if (isDDS) {
  10272. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10273. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10274. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  10275. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10276. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10277. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  10278. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  10279. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10280. }
  10281. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10282. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10283. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10284. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10285. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10286. _this.resetTextureCache();
  10287. texture.width = info.width;
  10288. texture.height = info.height;
  10289. texture.isReady = true;
  10290. texture.type = info.textureType;
  10291. if (onLoad) {
  10292. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  10293. }
  10294. }, null, null, true, onError);
  10295. }
  10296. else {
  10297. cascadeLoad(rootUrl, scene, function (imgs) {
  10298. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  10299. var height = width;
  10300. _this._prepareWorkingCanvas();
  10301. _this._workingCanvas.width = width;
  10302. _this._workingCanvas.height = height;
  10303. var faces = [
  10304. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10305. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10306. ];
  10307. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10308. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10309. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  10310. for (var index = 0; index < faces.length; index++) {
  10311. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  10312. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  10313. }
  10314. if (!noMipmap) {
  10315. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10316. }
  10317. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10318. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10319. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10320. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10321. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10322. _this.resetTextureCache();
  10323. texture.width = width;
  10324. texture.height = height;
  10325. texture.isReady = true;
  10326. texture.format = format;
  10327. texture.onLoadedObservable.notifyObservers(texture);
  10328. texture.onLoadedObservable.clear();
  10329. if (onLoad) {
  10330. onLoad();
  10331. }
  10332. }, files, onError);
  10333. }
  10334. this._internalTexturesCache.push(texture);
  10335. return texture;
  10336. };
  10337. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  10338. if (compression === void 0) { compression = null; }
  10339. if (level === void 0) { level = 0; }
  10340. texture._bufferViewArray = data;
  10341. texture.format = format;
  10342. texture.type = type;
  10343. texture.invertY = invertY;
  10344. texture._compression = compression;
  10345. var gl = this._gl;
  10346. var textureType = this._getWebGLTextureType(type);
  10347. var internalFormat = this._getInternalFormat(format);
  10348. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10349. var needConversion = false;
  10350. if (internalFormat === gl.RGB) {
  10351. internalFormat = gl.RGBA;
  10352. needConversion = true;
  10353. }
  10354. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10355. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10356. if (texture.width % 4 !== 0) {
  10357. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  10358. }
  10359. // Data are known to be in +X +Y +Z -X -Y -Z
  10360. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10361. var faceData = data[faceIndex];
  10362. if (compression) {
  10363. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, this.getCaps().s3tc[compression], texture.width, texture.height, 0, faceData);
  10364. }
  10365. else {
  10366. if (needConversion) {
  10367. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  10368. }
  10369. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  10370. }
  10371. }
  10372. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  10373. if (isPot && texture.generateMipMaps && level === 0) {
  10374. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10375. }
  10376. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10377. this.resetTextureCache();
  10378. texture.isReady = true;
  10379. };
  10380. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  10381. if (compression === void 0) { compression = null; }
  10382. var gl = this._gl;
  10383. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  10384. texture.isCube = true;
  10385. texture.generateMipMaps = generateMipMaps;
  10386. texture.format = format;
  10387. texture.type = type;
  10388. if (!this._doNotHandleContextLost) {
  10389. texture._bufferViewArray = data;
  10390. }
  10391. var textureType = this._getWebGLTextureType(type);
  10392. var internalFormat = this._getInternalFormat(format);
  10393. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10394. var needConversion = false;
  10395. if (internalFormat === gl.RGB) {
  10396. internalFormat = gl.RGBA;
  10397. needConversion = true;
  10398. }
  10399. var width = size;
  10400. var height = width;
  10401. texture.width = width;
  10402. texture.height = height;
  10403. // Double check on POT to generate Mips.
  10404. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  10405. if (!isPot) {
  10406. generateMipMaps = false;
  10407. }
  10408. // Upload data if needed. The texture won't be ready until then.
  10409. if (data) {
  10410. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  10411. }
  10412. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10413. // Filters
  10414. if (data && generateMipMaps) {
  10415. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10416. }
  10417. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  10418. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10419. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10420. }
  10421. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  10422. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10423. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10424. }
  10425. else {
  10426. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10427. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10428. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10429. }
  10430. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10431. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10432. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10433. return texture;
  10434. };
  10435. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  10436. var _this = this;
  10437. if (onLoad === void 0) { onLoad = null; }
  10438. if (onError === void 0) { onError = null; }
  10439. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10440. if (invertY === void 0) { invertY = false; }
  10441. var gl = this._gl;
  10442. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  10443. scene._addPendingData(texture);
  10444. texture.url = url;
  10445. this._internalTexturesCache.push(texture);
  10446. var onerror = function () {
  10447. scene._removePendingData(texture);
  10448. if (onError) {
  10449. onError();
  10450. }
  10451. };
  10452. var internalCallback = function (data) {
  10453. var width = texture.width;
  10454. var height = texture.height;
  10455. var faceDataArrays = callback(data);
  10456. if (mipmmapGenerator) {
  10457. var textureType = _this._getWebGLTextureType(type);
  10458. var internalFormat = _this._getInternalFormat(format);
  10459. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  10460. var needConversion = false;
  10461. if (internalFormat === gl.RGB) {
  10462. internalFormat = gl.RGBA;
  10463. needConversion = true;
  10464. }
  10465. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10466. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10467. var mipData = mipmmapGenerator(faceDataArrays);
  10468. for (var level = 0; level < mipData.length; level++) {
  10469. var mipSize = width >> level;
  10470. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10471. var mipFaceData = mipData[level][faceIndex];
  10472. if (needConversion) {
  10473. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  10474. }
  10475. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  10476. }
  10477. }
  10478. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10479. }
  10480. else {
  10481. texture.generateMipMaps = !noMipmap;
  10482. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  10483. }
  10484. texture.isReady = true;
  10485. _this.resetTextureCache();
  10486. scene._removePendingData(texture);
  10487. if (onLoad) {
  10488. onLoad();
  10489. }
  10490. };
  10491. BABYLON.Tools.LoadFile(url, function (data) {
  10492. internalCallback(data);
  10493. }, onerror, scene.database, true);
  10494. return texture;
  10495. };
  10496. ;
  10497. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  10498. var gl = this._gl;
  10499. if (!gl) {
  10500. return;
  10501. }
  10502. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  10503. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10504. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10505. if (!noMipmap && !isCompressed) {
  10506. gl.generateMipmap(gl.TEXTURE_2D);
  10507. }
  10508. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10509. this.resetTextureCache();
  10510. if (scene) {
  10511. scene._removePendingData(texture);
  10512. }
  10513. texture.onLoadedObservable.notifyObservers(texture);
  10514. texture.onLoadedObservable.clear();
  10515. };
  10516. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  10517. var _this = this;
  10518. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10519. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  10520. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  10521. var gl = this._gl;
  10522. if (!gl) {
  10523. return;
  10524. }
  10525. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10526. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10527. texture.baseWidth = width;
  10528. texture.baseHeight = height;
  10529. texture.width = potWidth;
  10530. texture.height = potHeight;
  10531. texture.isReady = true;
  10532. if (processFunction(potWidth, potHeight, function () {
  10533. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  10534. })) {
  10535. // Returning as texture needs extra async steps
  10536. return;
  10537. }
  10538. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  10539. };
  10540. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  10541. // Create new RGBA data container.
  10542. var rgbaData;
  10543. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  10544. rgbaData = new Float32Array(width * height * 4);
  10545. }
  10546. else {
  10547. rgbaData = new Uint32Array(width * height * 4);
  10548. }
  10549. // Convert each pixel.
  10550. for (var x = 0; x < width; x++) {
  10551. for (var y = 0; y < height; y++) {
  10552. var index = (y * width + x) * 3;
  10553. var newIndex = (y * width + x) * 4;
  10554. // Map Old Value to new value.
  10555. rgbaData[newIndex + 0] = rgbData[index + 0];
  10556. rgbaData[newIndex + 1] = rgbData[index + 1];
  10557. rgbaData[newIndex + 2] = rgbData[index + 2];
  10558. // Add fully opaque alpha channel.
  10559. rgbaData[newIndex + 3] = 1;
  10560. }
  10561. }
  10562. return rgbaData;
  10563. };
  10564. Engine.prototype._releaseFramebufferObjects = function (texture) {
  10565. var gl = this._gl;
  10566. if (texture._framebuffer) {
  10567. gl.deleteFramebuffer(texture._framebuffer);
  10568. texture._framebuffer = null;
  10569. }
  10570. if (texture._depthStencilBuffer) {
  10571. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10572. texture._depthStencilBuffer = null;
  10573. }
  10574. if (texture._MSAAFramebuffer) {
  10575. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10576. texture._MSAAFramebuffer = null;
  10577. }
  10578. if (texture._MSAARenderBuffer) {
  10579. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10580. texture._MSAARenderBuffer = null;
  10581. }
  10582. };
  10583. Engine.prototype._releaseTexture = function (texture) {
  10584. var gl = this._gl;
  10585. this._releaseFramebufferObjects(texture);
  10586. gl.deleteTexture(texture._webGLTexture);
  10587. // Unbind channels
  10588. this.unbindAllTextures();
  10589. var index = this._internalTexturesCache.indexOf(texture);
  10590. if (index !== -1) {
  10591. this._internalTexturesCache.splice(index, 1);
  10592. }
  10593. // Integrated fixed lod samplers.
  10594. if (texture._lodTextureHigh) {
  10595. texture._lodTextureHigh.dispose();
  10596. }
  10597. if (texture._lodTextureMid) {
  10598. texture._lodTextureMid.dispose();
  10599. }
  10600. if (texture._lodTextureLow) {
  10601. texture._lodTextureLow.dispose();
  10602. }
  10603. };
  10604. Engine.prototype.setProgram = function (program) {
  10605. if (this._currentProgram !== program) {
  10606. this._gl.useProgram(program);
  10607. this._currentProgram = program;
  10608. }
  10609. };
  10610. Engine.prototype.bindSamplers = function (effect) {
  10611. this.setProgram(effect.getProgram());
  10612. var samplers = effect.getSamplers();
  10613. for (var index = 0; index < samplers.length; index++) {
  10614. var uniform = effect.getUniform(samplers[index]);
  10615. this._gl.uniform1i(uniform, index);
  10616. }
  10617. this._currentEffect = null;
  10618. };
  10619. Engine.prototype.activateTexture = function (texture) {
  10620. if (this._activeTexture !== texture) {
  10621. this._gl.activeTexture(texture);
  10622. this._activeTexture = texture;
  10623. }
  10624. };
  10625. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10626. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10627. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  10628. this._activeTexturesCache[this._activeTexture] = texture;
  10629. }
  10630. };
  10631. Engine.prototype._bindTexture = function (channel, texture) {
  10632. if (channel < 0) {
  10633. return;
  10634. }
  10635. this.activateTexture(this._gl.TEXTURE0 + channel);
  10636. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10637. };
  10638. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10639. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10640. };
  10641. Engine.prototype.unbindAllTextures = function () {
  10642. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10643. this.activateTexture(this._gl["TEXTURE" + channel]);
  10644. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10645. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10646. }
  10647. };
  10648. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10649. if (channel < 0) {
  10650. return;
  10651. }
  10652. this._gl.uniform1i(uniform, channel);
  10653. this._setTexture(channel, texture);
  10654. };
  10655. Engine.prototype._setTexture = function (channel, texture) {
  10656. // Not ready?
  10657. if (!texture) {
  10658. if (this._activeTexturesCache[channel] != null) {
  10659. this.activateTexture(this._gl["TEXTURE" + channel]);
  10660. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10661. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10662. }
  10663. return;
  10664. }
  10665. // Video
  10666. var alreadyActivated = false;
  10667. if (texture.video) {
  10668. this.activateTexture(this._gl["TEXTURE" + channel]);
  10669. alreadyActivated = true;
  10670. texture.update();
  10671. }
  10672. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10673. texture.delayLoad();
  10674. return;
  10675. }
  10676. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  10677. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  10678. if (this._activeTexturesCache[channel] === internalTexture) {
  10679. return;
  10680. }
  10681. if (!alreadyActivated) {
  10682. this.activateTexture(this._gl["TEXTURE" + channel]);
  10683. }
  10684. if (internalTexture.isCube) {
  10685. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10686. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10687. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10688. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10689. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10690. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10691. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10692. }
  10693. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10694. }
  10695. else {
  10696. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10697. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10698. internalTexture._cachedWrapU = texture.wrapU;
  10699. switch (texture.wrapU) {
  10700. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10701. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10702. break;
  10703. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10704. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10705. break;
  10706. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10707. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10708. break;
  10709. }
  10710. }
  10711. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10712. internalTexture._cachedWrapV = texture.wrapV;
  10713. switch (texture.wrapV) {
  10714. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10715. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10716. break;
  10717. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10718. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10719. break;
  10720. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10721. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10722. break;
  10723. }
  10724. }
  10725. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10726. }
  10727. };
  10728. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10729. if (channel < 0) {
  10730. return;
  10731. }
  10732. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10733. this._textureUnits = new Int32Array(textures.length);
  10734. }
  10735. for (var i = 0; i < textures.length; i++) {
  10736. this._textureUnits[i] = channel + i;
  10737. }
  10738. this._gl.uniform1iv(uniform, this._textureUnits);
  10739. for (var index = 0; index < textures.length; index++) {
  10740. this._setTexture(channel + index, textures[index]);
  10741. }
  10742. };
  10743. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10744. var internalTexture = texture.getInternalTexture();
  10745. if (!internalTexture) {
  10746. return;
  10747. }
  10748. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10749. var value = texture.anisotropicFilteringLevel;
  10750. if (internalTexture.samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10751. value = 1;
  10752. }
  10753. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  10754. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10755. internalTexture._cachedAnisotropicFilteringLevel = value;
  10756. }
  10757. };
  10758. Engine.prototype.readPixels = function (x, y, width, height) {
  10759. var data = new Uint8Array(height * width * 4);
  10760. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10761. return data;
  10762. };
  10763. /**
  10764. * Add an externaly attached data from its key.
  10765. * This method call will fail and return false, if such key already exists.
  10766. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10767. * @param key the unique key that identifies the data
  10768. * @param data the data object to associate to the key for this Engine instance
  10769. * @return true if no such key were already present and the data was added successfully, false otherwise
  10770. */
  10771. Engine.prototype.addExternalData = function (key, data) {
  10772. if (!this._externalData) {
  10773. this._externalData = new BABYLON.StringDictionary();
  10774. }
  10775. return this._externalData.add(key, data);
  10776. };
  10777. /**
  10778. * Get an externaly attached data from its key
  10779. * @param key the unique key that identifies the data
  10780. * @return the associated data, if present (can be null), or undefined if not present
  10781. */
  10782. Engine.prototype.getExternalData = function (key) {
  10783. if (!this._externalData) {
  10784. this._externalData = new BABYLON.StringDictionary();
  10785. }
  10786. return this._externalData.get(key);
  10787. };
  10788. /**
  10789. * Get an externaly attached data from its key, create it using a factory if it's not already present
  10790. * @param key the unique key that identifies the data
  10791. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  10792. * @return the associated data, can be null if the factory returned null.
  10793. */
  10794. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  10795. if (!this._externalData) {
  10796. this._externalData = new BABYLON.StringDictionary();
  10797. }
  10798. return this._externalData.getOrAddWithFactory(key, factory);
  10799. };
  10800. /**
  10801. * Remove an externaly attached data from the Engine instance
  10802. * @param key the unique key that identifies the data
  10803. * @return true if the data was successfully removed, false if it doesn't exist
  10804. */
  10805. Engine.prototype.removeExternalData = function (key) {
  10806. if (!this._externalData) {
  10807. this._externalData = new BABYLON.StringDictionary();
  10808. }
  10809. return this._externalData.remove(key);
  10810. };
  10811. Engine.prototype.unbindAllAttributes = function () {
  10812. if (this._mustWipeVertexAttributes) {
  10813. this._mustWipeVertexAttributes = false;
  10814. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10815. this._gl.disableVertexAttribArray(i);
  10816. this._vertexAttribArraysEnabled[i] = false;
  10817. this._currentBufferPointers[i].active = false;
  10818. }
  10819. return;
  10820. }
  10821. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  10822. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  10823. continue;
  10824. }
  10825. this._gl.disableVertexAttribArray(i);
  10826. this._vertexAttribArraysEnabled[i] = false;
  10827. this._currentBufferPointers[i].active = false;
  10828. }
  10829. };
  10830. Engine.prototype.releaseEffects = function () {
  10831. for (var name in this._compiledEffects) {
  10832. this._gl.deleteProgram(this._compiledEffects[name]._program);
  10833. }
  10834. this._compiledEffects = {};
  10835. };
  10836. // Dispose
  10837. Engine.prototype.dispose = function () {
  10838. this.hideLoadingUI();
  10839. this.stopRenderLoop();
  10840. // Release postProcesses
  10841. while (this.postProcesses.length) {
  10842. this.postProcesses[0].dispose();
  10843. }
  10844. // Empty texture
  10845. if (this._emptyTexture) {
  10846. this._releaseTexture(this._emptyTexture);
  10847. this._emptyTexture = null;
  10848. }
  10849. if (this._emptyCubeTexture) {
  10850. this._releaseTexture(this._emptyCubeTexture);
  10851. this._emptyCubeTexture = null;
  10852. }
  10853. // Rescale PP
  10854. if (this._rescalePostProcess) {
  10855. this._rescalePostProcess.dispose();
  10856. }
  10857. // Release scenes
  10858. while (this.scenes.length) {
  10859. this.scenes[0].dispose();
  10860. }
  10861. // Release audio engine
  10862. if (Engine.audioEngine) {
  10863. Engine.audioEngine.dispose();
  10864. }
  10865. // Release effects
  10866. this.releaseEffects();
  10867. // Unbind
  10868. this.unbindAllAttributes();
  10869. if (this._dummyFramebuffer) {
  10870. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  10871. }
  10872. this._gl = null;
  10873. //WebVR
  10874. this.disableVR();
  10875. // Events
  10876. window.removeEventListener("blur", this._onBlur);
  10877. window.removeEventListener("focus", this._onFocus);
  10878. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  10879. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  10880. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  10881. if (!this._doNotHandleContextLost) {
  10882. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  10883. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  10884. }
  10885. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  10886. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  10887. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  10888. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  10889. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  10890. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  10891. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  10892. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  10893. // Remove from Instances
  10894. var index = Engine.Instances.indexOf(this);
  10895. if (index >= 0) {
  10896. Engine.Instances.splice(index, 1);
  10897. }
  10898. this._workingCanvas = null;
  10899. this._workingContext = null;
  10900. this._currentBufferPointers = null;
  10901. this._renderingCanvas = null;
  10902. this._currentProgram = null;
  10903. this.onResizeObservable.clear();
  10904. this.onCanvasBlurObservable.clear();
  10905. BABYLON.Effect.ResetCache();
  10906. };
  10907. // Loading screen
  10908. Engine.prototype.displayLoadingUI = function () {
  10909. var loadingScreen = this.loadingScreen;
  10910. if (loadingScreen) {
  10911. loadingScreen.displayLoadingUI();
  10912. }
  10913. };
  10914. Engine.prototype.hideLoadingUI = function () {
  10915. var loadingScreen = this.loadingScreen;
  10916. if (loadingScreen) {
  10917. loadingScreen.hideLoadingUI();
  10918. }
  10919. };
  10920. Object.defineProperty(Engine.prototype, "loadingScreen", {
  10921. get: function () {
  10922. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen)
  10923. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  10924. return this._loadingScreen;
  10925. },
  10926. set: function (loadingScreen) {
  10927. this._loadingScreen = loadingScreen;
  10928. },
  10929. enumerable: true,
  10930. configurable: true
  10931. });
  10932. Object.defineProperty(Engine.prototype, "loadingUIText", {
  10933. set: function (text) {
  10934. this.loadingScreen.loadingUIText = text;
  10935. },
  10936. enumerable: true,
  10937. configurable: true
  10938. });
  10939. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  10940. set: function (color) {
  10941. this.loadingScreen.loadingUIBackgroundColor = color;
  10942. },
  10943. enumerable: true,
  10944. configurable: true
  10945. });
  10946. Engine.prototype.attachContextLostEvent = function (callback) {
  10947. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  10948. };
  10949. Engine.prototype.attachContextRestoredEvent = function (callback) {
  10950. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  10951. };
  10952. Engine.prototype.getVertexShaderSource = function (program) {
  10953. var shaders = this._gl.getAttachedShaders(program);
  10954. return this._gl.getShaderSource(shaders[0]);
  10955. };
  10956. Engine.prototype.getFragmentShaderSource = function (program) {
  10957. var shaders = this._gl.getAttachedShaders(program);
  10958. return this._gl.getShaderSource(shaders[1]);
  10959. };
  10960. Engine.prototype.getError = function () {
  10961. return this._gl.getError();
  10962. };
  10963. // FPS
  10964. Engine.prototype.getFps = function () {
  10965. return this._fps;
  10966. };
  10967. Engine.prototype.getDeltaTime = function () {
  10968. return this._deltaTime;
  10969. };
  10970. Engine.prototype._measureFps = function () {
  10971. this._performanceMonitor.sampleFrame();
  10972. this._fps = this._performanceMonitor.averageFPS;
  10973. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  10974. };
  10975. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  10976. if (faceIndex === void 0) { faceIndex = -1; }
  10977. var gl = this._gl;
  10978. if (!this._dummyFramebuffer) {
  10979. this._dummyFramebuffer = gl.createFramebuffer();
  10980. }
  10981. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  10982. if (faceIndex > -1) {
  10983. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  10984. }
  10985. else {
  10986. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10987. }
  10988. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  10989. var buffer;
  10990. switch (readType) {
  10991. case gl.UNSIGNED_BYTE:
  10992. buffer = new Uint8Array(4 * width * height);
  10993. readType = gl.UNSIGNED_BYTE;
  10994. break;
  10995. default:
  10996. buffer = new Float32Array(4 * width * height);
  10997. readType = gl.FLOAT;
  10998. break;
  10999. }
  11000. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  11001. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  11002. return buffer;
  11003. };
  11004. Engine.prototype._canRenderToFloatFramebuffer = function () {
  11005. if (this._webGLVersion > 1) {
  11006. return this._caps.colorBufferFloat;
  11007. }
  11008. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  11009. };
  11010. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  11011. if (this._webGLVersion > 1) {
  11012. return this._caps.colorBufferFloat;
  11013. }
  11014. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  11015. };
  11016. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  11017. Engine.prototype._canRenderToFramebuffer = function (type) {
  11018. var gl = this._gl;
  11019. //clear existing errors
  11020. while (gl.getError() !== gl.NO_ERROR) { }
  11021. var successful = true;
  11022. var texture = gl.createTexture();
  11023. gl.bindTexture(gl.TEXTURE_2D, texture);
  11024. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11025. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11026. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11027. var fb = gl.createFramebuffer();
  11028. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  11029. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  11030. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  11031. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  11032. successful = successful && (gl.getError() === gl.NO_ERROR);
  11033. //try render by clearing frame buffer's color buffer
  11034. if (successful) {
  11035. gl.clear(gl.COLOR_BUFFER_BIT);
  11036. successful = successful && (gl.getError() === gl.NO_ERROR);
  11037. }
  11038. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  11039. if (successful) {
  11040. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  11041. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11042. var readFormat = gl.RGBA;
  11043. var readType = gl.UNSIGNED_BYTE;
  11044. var buffer = new Uint8Array(4);
  11045. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  11046. successful = successful && (gl.getError() === gl.NO_ERROR);
  11047. }
  11048. //clean up
  11049. gl.deleteTexture(texture);
  11050. gl.deleteFramebuffer(fb);
  11051. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11052. //clear accumulated errors
  11053. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  11054. return successful;
  11055. };
  11056. Engine.prototype._getWebGLTextureType = function (type) {
  11057. if (type === Engine.TEXTURETYPE_FLOAT) {
  11058. return this._gl.FLOAT;
  11059. }
  11060. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11061. // Add Half Float Constant.
  11062. return this._gl.HALF_FLOAT_OES;
  11063. }
  11064. return this._gl.UNSIGNED_BYTE;
  11065. };
  11066. ;
  11067. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  11068. if (this._webGLVersion === 1) {
  11069. return this._gl.RGBA;
  11070. }
  11071. if (type === Engine.TEXTURETYPE_FLOAT) {
  11072. return this._gl.RGBA32F;
  11073. }
  11074. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11075. return this._gl.RGBA16F;
  11076. }
  11077. return this._gl.RGBA;
  11078. };
  11079. ;
  11080. Engine.prototype.createQuery = function () {
  11081. return this._gl.createQuery();
  11082. };
  11083. Engine.prototype.deleteQuery = function (query) {
  11084. this._gl.deleteQuery(query);
  11085. return this;
  11086. };
  11087. Engine.prototype.isQueryResultAvailable = function (query) {
  11088. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  11089. };
  11090. Engine.prototype.getQueryResult = function (query) {
  11091. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  11092. };
  11093. Engine.prototype.beginQuery = function (algorithmType, query) {
  11094. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11095. this._gl.beginQuery(glAlgorithm, query);
  11096. };
  11097. Engine.prototype.endQuery = function (algorithmType) {
  11098. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11099. this._gl.endQuery(glAlgorithm);
  11100. return this;
  11101. };
  11102. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  11103. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  11104. };
  11105. // Statics
  11106. Engine.isSupported = function () {
  11107. try {
  11108. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  11109. if (navigator.isCocoonJS) {
  11110. return true;
  11111. }
  11112. var tempcanvas = document.createElement("canvas");
  11113. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  11114. return gl != null && !!window.WebGLRenderingContext;
  11115. }
  11116. catch (e) {
  11117. return false;
  11118. }
  11119. };
  11120. Engine.Instances = new Array();
  11121. // Const statics
  11122. Engine._ALPHA_DISABLE = 0;
  11123. Engine._ALPHA_ADD = 1;
  11124. Engine._ALPHA_COMBINE = 2;
  11125. Engine._ALPHA_SUBTRACT = 3;
  11126. Engine._ALPHA_MULTIPLY = 4;
  11127. Engine._ALPHA_MAXIMIZED = 5;
  11128. Engine._ALPHA_ONEONE = 6;
  11129. Engine._ALPHA_PREMULTIPLIED = 7;
  11130. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  11131. Engine._ALPHA_INTERPOLATE = 9;
  11132. Engine._ALPHA_SCREENMODE = 10;
  11133. Engine._DELAYLOADSTATE_NONE = 0;
  11134. Engine._DELAYLOADSTATE_LOADED = 1;
  11135. Engine._DELAYLOADSTATE_LOADING = 2;
  11136. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  11137. Engine._TEXTUREFORMAT_ALPHA = 0;
  11138. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  11139. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  11140. Engine._TEXTUREFORMAT_RGB = 4;
  11141. Engine._TEXTUREFORMAT_RGBA = 5;
  11142. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  11143. Engine._TEXTURETYPE_FLOAT = 1;
  11144. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  11145. // Depht or Stencil test Constants.
  11146. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  11147. 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.
  11148. 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.
  11149. 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.
  11150. 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.
  11151. 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.
  11152. 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.
  11153. 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.
  11154. // Stencil Actions Constants.
  11155. Engine._KEEP = 0x1E00;
  11156. Engine._REPLACE = 0x1E01;
  11157. Engine._INCR = 0x1E02;
  11158. Engine._DECR = 0x1E03;
  11159. Engine._INVERT = 0x150A;
  11160. Engine._INCR_WRAP = 0x8507;
  11161. Engine._DECR_WRAP = 0x8508;
  11162. // Texture rescaling mode
  11163. Engine._SCALEMODE_FLOOR = 1;
  11164. Engine._SCALEMODE_NEAREST = 2;
  11165. Engine._SCALEMODE_CEILING = 3;
  11166. // Updatable statics so stick with vars here
  11167. Engine.CollisionsEpsilon = 0.001;
  11168. Engine.CodeRepository = "src/";
  11169. Engine.ShadersRepository = "src/Shaders/";
  11170. return Engine;
  11171. }());
  11172. BABYLON.Engine = Engine;
  11173. })(BABYLON || (BABYLON = {}));
  11174. //# sourceMappingURL=babylon.engine.js.map
  11175. /// <reference path="Tools\babylon.decorators.ts" />
  11176. var BABYLON;
  11177. (function (BABYLON) {
  11178. /**
  11179. * Node is the basic class for all scene objects (Mesh, Light Camera).
  11180. */
  11181. var Node = (function () {
  11182. /**
  11183. * @constructor
  11184. * @param {string} name - the name and id to be given to this node
  11185. * @param {BABYLON.Scene} the scene this node will be added to
  11186. */
  11187. function Node(name, scene) {
  11188. this.state = "";
  11189. this.metadata = null;
  11190. this.doNotSerialize = false;
  11191. this.animations = new Array();
  11192. this._ranges = {};
  11193. this._childrenFlag = -1;
  11194. this._isEnabled = true;
  11195. this._isReady = true;
  11196. this._currentRenderId = -1;
  11197. this._parentRenderId = -1;
  11198. /**
  11199. * An event triggered when the mesh is disposed.
  11200. * @type {BABYLON.Observable}
  11201. */
  11202. this.onDisposeObservable = new BABYLON.Observable();
  11203. // Behaviors
  11204. this._behaviors = new Array();
  11205. this.name = name;
  11206. this.id = name;
  11207. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  11208. this._initCache();
  11209. }
  11210. Object.defineProperty(Node.prototype, "parent", {
  11211. get: function () {
  11212. return this._parentNode;
  11213. },
  11214. set: function (parent) {
  11215. if (this._parentNode === parent) {
  11216. return;
  11217. }
  11218. if (this._parentNode) {
  11219. var index = this._parentNode._children.indexOf(this);
  11220. if (index !== -1) {
  11221. this._parentNode._children.splice(index, 1);
  11222. }
  11223. }
  11224. this._parentNode = parent;
  11225. if (this._parentNode) {
  11226. if (!this._parentNode._children) {
  11227. this._parentNode._children = new Array();
  11228. }
  11229. this._parentNode._children.push(this);
  11230. }
  11231. },
  11232. enumerable: true,
  11233. configurable: true
  11234. });
  11235. Node.prototype.getClassName = function () {
  11236. return "Node";
  11237. };
  11238. Object.defineProperty(Node.prototype, "onDispose", {
  11239. set: function (callback) {
  11240. if (this._onDisposeObserver) {
  11241. this.onDisposeObservable.remove(this._onDisposeObserver);
  11242. }
  11243. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  11244. },
  11245. enumerable: true,
  11246. configurable: true
  11247. });
  11248. Node.prototype.getScene = function () {
  11249. return this._scene;
  11250. };
  11251. Node.prototype.getEngine = function () {
  11252. return this._scene.getEngine();
  11253. };
  11254. Node.prototype.addBehavior = function (behavior) {
  11255. var index = this._behaviors.indexOf(behavior);
  11256. if (index !== -1) {
  11257. return;
  11258. }
  11259. behavior.attach(this);
  11260. this._behaviors.push(behavior);
  11261. return this;
  11262. };
  11263. Node.prototype.removeBehavior = function (behavior) {
  11264. var index = this._behaviors.indexOf(behavior);
  11265. if (index === -1) {
  11266. return;
  11267. }
  11268. this._behaviors[index].detach();
  11269. this._behaviors.splice(index, 1);
  11270. return this;
  11271. };
  11272. Object.defineProperty(Node.prototype, "behaviors", {
  11273. get: function () {
  11274. return this._behaviors;
  11275. },
  11276. enumerable: true,
  11277. configurable: true
  11278. });
  11279. Node.prototype.getBehaviorByName = function (name) {
  11280. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  11281. var behavior = _a[_i];
  11282. if (behavior.name === name) {
  11283. return behavior;
  11284. }
  11285. }
  11286. return null;
  11287. };
  11288. // override it in derived class
  11289. Node.prototype.getWorldMatrix = function () {
  11290. return BABYLON.Matrix.Identity();
  11291. };
  11292. // override it in derived class if you add new variables to the cache
  11293. // and call the parent class method
  11294. Node.prototype._initCache = function () {
  11295. this._cache = {};
  11296. this._cache.parent = undefined;
  11297. };
  11298. Node.prototype.updateCache = function (force) {
  11299. if (!force && this.isSynchronized())
  11300. return;
  11301. this._cache.parent = this.parent;
  11302. this._updateCache();
  11303. };
  11304. // override it in derived class if you add new variables to the cache
  11305. // and call the parent class method if !ignoreParentClass
  11306. Node.prototype._updateCache = function (ignoreParentClass) {
  11307. };
  11308. // override it in derived class if you add new variables to the cache
  11309. Node.prototype._isSynchronized = function () {
  11310. return true;
  11311. };
  11312. Node.prototype._markSyncedWithParent = function () {
  11313. this._parentRenderId = this.parent._currentRenderId;
  11314. };
  11315. Node.prototype.isSynchronizedWithParent = function () {
  11316. if (!this.parent) {
  11317. return true;
  11318. }
  11319. if (this._parentRenderId !== this.parent._currentRenderId) {
  11320. return false;
  11321. }
  11322. return this.parent.isSynchronized();
  11323. };
  11324. Node.prototype.isSynchronized = function (updateCache) {
  11325. var check = this.hasNewParent();
  11326. check = check || !this.isSynchronizedWithParent();
  11327. check = check || !this._isSynchronized();
  11328. if (updateCache)
  11329. this.updateCache(true);
  11330. return !check;
  11331. };
  11332. Node.prototype.hasNewParent = function (update) {
  11333. if (this._cache.parent === this.parent)
  11334. return false;
  11335. if (update)
  11336. this._cache.parent = this.parent;
  11337. return true;
  11338. };
  11339. /**
  11340. * Is this node ready to be used/rendered
  11341. * @return {boolean} is it ready
  11342. */
  11343. Node.prototype.isReady = function () {
  11344. return this._isReady;
  11345. };
  11346. /**
  11347. * Is this node enabled.
  11348. * If the node has a parent and is enabled, the parent will be inspected as well.
  11349. * @return {boolean} whether this node (and its parent) is enabled.
  11350. * @see setEnabled
  11351. */
  11352. Node.prototype.isEnabled = function () {
  11353. if (!this._isEnabled) {
  11354. return false;
  11355. }
  11356. if (this.parent) {
  11357. return this.parent.isEnabled();
  11358. }
  11359. return true;
  11360. };
  11361. /**
  11362. * Set the enabled state of this node.
  11363. * @param {boolean} value - the new enabled state
  11364. * @see isEnabled
  11365. */
  11366. Node.prototype.setEnabled = function (value) {
  11367. this._isEnabled = value;
  11368. };
  11369. /**
  11370. * Is this node a descendant of the given node.
  11371. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  11372. * @param {BABYLON.Node} ancestor - The parent node to inspect
  11373. * @see parent
  11374. */
  11375. Node.prototype.isDescendantOf = function (ancestor) {
  11376. if (this.parent) {
  11377. if (this.parent === ancestor) {
  11378. return true;
  11379. }
  11380. return this.parent.isDescendantOf(ancestor);
  11381. }
  11382. return false;
  11383. };
  11384. /**
  11385. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  11386. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  11387. * @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.
  11388. * @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.
  11389. */
  11390. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  11391. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  11392. if (!this._children) {
  11393. return;
  11394. }
  11395. for (var index = 0; index < this._children.length; index++) {
  11396. var item = this._children[index];
  11397. if (!predicate || predicate(item)) {
  11398. results.push(item);
  11399. }
  11400. if (!directDescendantsOnly) {
  11401. item._getDescendants(results, false, predicate);
  11402. }
  11403. }
  11404. };
  11405. /**
  11406. * Will return all nodes that have this node as ascendant.
  11407. * @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.
  11408. * @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.
  11409. * @return {BABYLON.Node[]} all children nodes of all types.
  11410. */
  11411. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  11412. var results = [];
  11413. this._getDescendants(results, directDescendantsOnly, predicate);
  11414. return results;
  11415. };
  11416. /**
  11417. * Get all child-meshes of this node.
  11418. */
  11419. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  11420. var results = [];
  11421. this._getDescendants(results, directDecendantsOnly, function (node) {
  11422. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  11423. });
  11424. return results;
  11425. };
  11426. /**
  11427. * Get all direct children of this node.
  11428. */
  11429. Node.prototype.getChildren = function (predicate) {
  11430. return this.getDescendants(true, predicate);
  11431. };
  11432. Node.prototype._setReady = function (state) {
  11433. if (state === this._isReady) {
  11434. return;
  11435. }
  11436. if (!state) {
  11437. this._isReady = false;
  11438. return;
  11439. }
  11440. this._isReady = true;
  11441. if (this.onReady) {
  11442. this.onReady(this);
  11443. }
  11444. };
  11445. Node.prototype.getAnimationByName = function (name) {
  11446. for (var i = 0; i < this.animations.length; i++) {
  11447. var animation = this.animations[i];
  11448. if (animation.name === name) {
  11449. return animation;
  11450. }
  11451. }
  11452. return null;
  11453. };
  11454. Node.prototype.createAnimationRange = function (name, from, to) {
  11455. // check name not already in use
  11456. if (!this._ranges[name]) {
  11457. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  11458. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11459. if (this.animations[i]) {
  11460. this.animations[i].createRange(name, from, to);
  11461. }
  11462. }
  11463. }
  11464. };
  11465. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  11466. if (deleteFrames === void 0) { deleteFrames = true; }
  11467. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11468. if (this.animations[i]) {
  11469. this.animations[i].deleteRange(name, deleteFrames);
  11470. }
  11471. }
  11472. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  11473. };
  11474. Node.prototype.getAnimationRange = function (name) {
  11475. return this._ranges[name];
  11476. };
  11477. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  11478. var range = this.getAnimationRange(name);
  11479. if (!range) {
  11480. return null;
  11481. }
  11482. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  11483. };
  11484. Node.prototype.serializeAnimationRanges = function () {
  11485. var serializationRanges = [];
  11486. for (var name in this._ranges) {
  11487. var range = {};
  11488. range.name = name;
  11489. range.from = this._ranges[name].from;
  11490. range.to = this._ranges[name].to;
  11491. serializationRanges.push(range);
  11492. }
  11493. return serializationRanges;
  11494. };
  11495. Node.prototype.dispose = function () {
  11496. this.parent = null;
  11497. // Callback
  11498. this.onDisposeObservable.notifyObservers(this);
  11499. this.onDisposeObservable.clear();
  11500. // Behaviors
  11501. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  11502. var behavior = _a[_i];
  11503. behavior.detach();
  11504. }
  11505. this._behaviors = [];
  11506. };
  11507. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  11508. if (parsedNode.ranges) {
  11509. for (var index = 0; index < parsedNode.ranges.length; index++) {
  11510. var data = parsedNode.ranges[index];
  11511. node.createAnimationRange(data.name, data.from, data.to);
  11512. }
  11513. }
  11514. };
  11515. __decorate([
  11516. BABYLON.serialize()
  11517. ], Node.prototype, "name", void 0);
  11518. __decorate([
  11519. BABYLON.serialize()
  11520. ], Node.prototype, "id", void 0);
  11521. __decorate([
  11522. BABYLON.serialize()
  11523. ], Node.prototype, "uniqueId", void 0);
  11524. __decorate([
  11525. BABYLON.serialize()
  11526. ], Node.prototype, "state", void 0);
  11527. __decorate([
  11528. BABYLON.serialize()
  11529. ], Node.prototype, "metadata", void 0);
  11530. return Node;
  11531. }());
  11532. BABYLON.Node = Node;
  11533. })(BABYLON || (BABYLON = {}));
  11534. //# sourceMappingURL=babylon.node.js.map
  11535. var BABYLON;
  11536. (function (BABYLON) {
  11537. var BoundingSphere = (function () {
  11538. function BoundingSphere(minimum, maximum) {
  11539. this.minimum = minimum;
  11540. this.maximum = maximum;
  11541. this._tempRadiusVector = BABYLON.Vector3.Zero();
  11542. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  11543. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  11544. this.radius = distance * 0.5;
  11545. this.centerWorld = BABYLON.Vector3.Zero();
  11546. this._update(BABYLON.Matrix.Identity());
  11547. }
  11548. // Methods
  11549. BoundingSphere.prototype._update = function (world) {
  11550. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  11551. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  11552. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  11553. };
  11554. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  11555. for (var i = 0; i < 6; i++) {
  11556. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  11557. return false;
  11558. }
  11559. return true;
  11560. };
  11561. BoundingSphere.prototype.intersectsPoint = function (point) {
  11562. var x = this.centerWorld.x - point.x;
  11563. var y = this.centerWorld.y - point.y;
  11564. var z = this.centerWorld.z - point.z;
  11565. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11566. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  11567. return false;
  11568. return true;
  11569. };
  11570. // Statics
  11571. BoundingSphere.Intersects = function (sphere0, sphere1) {
  11572. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  11573. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  11574. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  11575. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11576. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  11577. return false;
  11578. return true;
  11579. };
  11580. return BoundingSphere;
  11581. }());
  11582. BABYLON.BoundingSphere = BoundingSphere;
  11583. })(BABYLON || (BABYLON = {}));
  11584. //# sourceMappingURL=babylon.boundingSphere.js.map
  11585. var BABYLON;
  11586. (function (BABYLON) {
  11587. var BoundingBox = (function () {
  11588. function BoundingBox(minimum, maximum) {
  11589. this.minimum = minimum;
  11590. this.maximum = maximum;
  11591. this.vectors = new Array();
  11592. this.vectorsWorld = new Array();
  11593. // Bounding vectors
  11594. this.vectors.push(this.minimum.clone());
  11595. this.vectors.push(this.maximum.clone());
  11596. this.vectors.push(this.minimum.clone());
  11597. this.vectors[2].x = this.maximum.x;
  11598. this.vectors.push(this.minimum.clone());
  11599. this.vectors[3].y = this.maximum.y;
  11600. this.vectors.push(this.minimum.clone());
  11601. this.vectors[4].z = this.maximum.z;
  11602. this.vectors.push(this.maximum.clone());
  11603. this.vectors[5].z = this.minimum.z;
  11604. this.vectors.push(this.maximum.clone());
  11605. this.vectors[6].x = this.minimum.x;
  11606. this.vectors.push(this.maximum.clone());
  11607. this.vectors[7].y = this.minimum.y;
  11608. // OBB
  11609. this.center = this.maximum.add(this.minimum).scale(0.5);
  11610. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  11611. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  11612. // World
  11613. for (var index = 0; index < this.vectors.length; index++) {
  11614. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  11615. }
  11616. this.minimumWorld = BABYLON.Vector3.Zero();
  11617. this.maximumWorld = BABYLON.Vector3.Zero();
  11618. this.centerWorld = BABYLON.Vector3.Zero();
  11619. this.extendSizeWorld = BABYLON.Vector3.Zero();
  11620. this._update(BABYLON.Matrix.Identity());
  11621. }
  11622. // Methods
  11623. BoundingBox.prototype.getWorldMatrix = function () {
  11624. return this._worldMatrix;
  11625. };
  11626. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  11627. this._worldMatrix.copyFrom(matrix);
  11628. return this;
  11629. };
  11630. BoundingBox.prototype._update = function (world) {
  11631. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  11632. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  11633. for (var index = 0; index < this.vectors.length; index++) {
  11634. var v = this.vectorsWorld[index];
  11635. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  11636. if (v.x < this.minimumWorld.x)
  11637. this.minimumWorld.x = v.x;
  11638. if (v.y < this.minimumWorld.y)
  11639. this.minimumWorld.y = v.y;
  11640. if (v.z < this.minimumWorld.z)
  11641. this.minimumWorld.z = v.z;
  11642. if (v.x > this.maximumWorld.x)
  11643. this.maximumWorld.x = v.x;
  11644. if (v.y > this.maximumWorld.y)
  11645. this.maximumWorld.y = v.y;
  11646. if (v.z > this.maximumWorld.z)
  11647. this.maximumWorld.z = v.z;
  11648. }
  11649. // Extend
  11650. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  11651. this.extendSizeWorld.scaleInPlace(0.5);
  11652. // OBB
  11653. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  11654. this.centerWorld.scaleInPlace(0.5);
  11655. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  11656. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  11657. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  11658. this._worldMatrix = world;
  11659. };
  11660. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  11661. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  11662. };
  11663. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11664. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  11665. };
  11666. BoundingBox.prototype.intersectsPoint = function (point) {
  11667. var delta = -BABYLON.Epsilon;
  11668. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  11669. return false;
  11670. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  11671. return false;
  11672. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  11673. return false;
  11674. return true;
  11675. };
  11676. BoundingBox.prototype.intersectsSphere = function (sphere) {
  11677. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  11678. };
  11679. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  11680. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  11681. return false;
  11682. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  11683. return false;
  11684. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  11685. return false;
  11686. return true;
  11687. };
  11688. // Statics
  11689. BoundingBox.Intersects = function (box0, box1) {
  11690. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  11691. return false;
  11692. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  11693. return false;
  11694. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  11695. return false;
  11696. return true;
  11697. };
  11698. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  11699. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  11700. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  11701. return (num <= (sphereRadius * sphereRadius));
  11702. };
  11703. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  11704. for (var p = 0; p < 6; p++) {
  11705. for (var i = 0; i < 8; i++) {
  11706. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11707. return false;
  11708. }
  11709. }
  11710. }
  11711. return true;
  11712. };
  11713. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  11714. for (var p = 0; p < 6; p++) {
  11715. var inCount = 8;
  11716. for (var i = 0; i < 8; i++) {
  11717. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11718. --inCount;
  11719. }
  11720. else {
  11721. break;
  11722. }
  11723. }
  11724. if (inCount === 0)
  11725. return false;
  11726. }
  11727. return true;
  11728. };
  11729. return BoundingBox;
  11730. }());
  11731. BABYLON.BoundingBox = BoundingBox;
  11732. })(BABYLON || (BABYLON = {}));
  11733. //# sourceMappingURL=babylon.boundingBox.js.map
  11734. var BABYLON;
  11735. (function (BABYLON) {
  11736. var computeBoxExtents = function (axis, box) {
  11737. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  11738. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11739. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  11740. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11741. var r = r0 + r1 + r2;
  11742. return {
  11743. min: p - r,
  11744. max: p + r
  11745. };
  11746. };
  11747. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11748. var axisOverlap = function (axis, box0, box1) {
  11749. var result0 = computeBoxExtents(axis, box0);
  11750. var result1 = computeBoxExtents(axis, box1);
  11751. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11752. };
  11753. var BoundingInfo = (function () {
  11754. function BoundingInfo(minimum, maximum) {
  11755. this.minimum = minimum;
  11756. this.maximum = maximum;
  11757. this._isLocked = false;
  11758. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  11759. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  11760. }
  11761. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  11762. get: function () {
  11763. return this._isLocked;
  11764. },
  11765. set: function (value) {
  11766. this._isLocked = value;
  11767. },
  11768. enumerable: true,
  11769. configurable: true
  11770. });
  11771. // Methods
  11772. BoundingInfo.prototype.update = function (world) {
  11773. if (this._isLocked) {
  11774. return;
  11775. }
  11776. this.boundingBox._update(world);
  11777. this.boundingSphere._update(world);
  11778. };
  11779. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  11780. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  11781. return false;
  11782. return this.boundingBox.isInFrustum(frustumPlanes);
  11783. };
  11784. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  11785. /**
  11786. * Gets the world distance between the min and max points of the bounding box
  11787. */
  11788. get: function () {
  11789. var boundingBox = this.boundingBox;
  11790. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  11791. return size.length();
  11792. },
  11793. enumerable: true,
  11794. configurable: true
  11795. });
  11796. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11797. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  11798. };
  11799. BoundingInfo.prototype._checkCollision = function (collider) {
  11800. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  11801. };
  11802. BoundingInfo.prototype.intersectsPoint = function (point) {
  11803. if (!this.boundingSphere.centerWorld) {
  11804. return false;
  11805. }
  11806. if (!this.boundingSphere.intersectsPoint(point)) {
  11807. return false;
  11808. }
  11809. if (!this.boundingBox.intersectsPoint(point)) {
  11810. return false;
  11811. }
  11812. return true;
  11813. };
  11814. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  11815. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  11816. return false;
  11817. }
  11818. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  11819. return false;
  11820. }
  11821. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  11822. return false;
  11823. }
  11824. if (!precise) {
  11825. return true;
  11826. }
  11827. var box0 = this.boundingBox;
  11828. var box1 = boundingInfo.boundingBox;
  11829. if (!axisOverlap(box0.directions[0], box0, box1))
  11830. return false;
  11831. if (!axisOverlap(box0.directions[1], box0, box1))
  11832. return false;
  11833. if (!axisOverlap(box0.directions[2], box0, box1))
  11834. return false;
  11835. if (!axisOverlap(box1.directions[0], box0, box1))
  11836. return false;
  11837. if (!axisOverlap(box1.directions[1], box0, box1))
  11838. return false;
  11839. if (!axisOverlap(box1.directions[2], box0, box1))
  11840. return false;
  11841. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  11842. return false;
  11843. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  11844. return false;
  11845. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  11846. return false;
  11847. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  11848. return false;
  11849. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  11850. return false;
  11851. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  11852. return false;
  11853. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  11854. return false;
  11855. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  11856. return false;
  11857. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  11858. return false;
  11859. return true;
  11860. };
  11861. return BoundingInfo;
  11862. }());
  11863. BABYLON.BoundingInfo = BoundingInfo;
  11864. })(BABYLON || (BABYLON = {}));
  11865. //# sourceMappingURL=babylon.boundingInfo.js.map
  11866. var BABYLON;
  11867. (function (BABYLON) {
  11868. var AbstractMesh = (function (_super) {
  11869. __extends(AbstractMesh, _super);
  11870. // Constructor
  11871. function AbstractMesh(name, scene) {
  11872. var _this = _super.call(this, name, scene) || this;
  11873. _this._facetNb = 0; // facet number
  11874. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  11875. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  11876. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  11877. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  11878. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  11879. _this._subDiv = {
  11880. max: 1,
  11881. X: 1,
  11882. Y: 1,
  11883. Z: 1
  11884. };
  11885. // Events
  11886. /**
  11887. * An event triggered when this mesh collides with another one
  11888. * @type {BABYLON.Observable}
  11889. */
  11890. _this.onCollideObservable = new BABYLON.Observable();
  11891. /**
  11892. * An event triggered when the collision's position changes
  11893. * @type {BABYLON.Observable}
  11894. */
  11895. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  11896. /**
  11897. * An event triggered after the world matrix is updated
  11898. * @type {BABYLON.Observable}
  11899. */
  11900. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  11901. /**
  11902. * An event triggered when material is changed
  11903. * @type {BABYLON.Observable}
  11904. */
  11905. _this.onMaterialChangedObservable = new BABYLON.Observable();
  11906. // Properties
  11907. _this.definedFacingForward = true; // orientation for POV movement & rotation
  11908. _this.position = BABYLON.Vector3.Zero();
  11909. /**
  11910. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  11911. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  11912. * or
  11913. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE (Default Value) which is mapped to GL_ANY_SAMPLES_PASSED_CONSERVATIVE which is a false positive algorithm that is faster than GL_ANY_SAMPLES_PASSED but less accurate.
  11914. * for more info check WebGl documentations
  11915. */
  11916. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  11917. /**
  11918. * This property is responsible for starting the occlusion query within the Mesh or not, this property is also used to determine what should happen when the occlusionRetryCount is reached. It has supports 3 values:
  11919. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  11920. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  11921. * OCCLUSION_TYPE_STRICT: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken restore the last state of the mesh occlusion if the mesh was visible then show the mesh if was hidden then hide don't show.
  11922. */
  11923. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  11924. /**
  11925. * This number indicates the number of allowed retries before stop the occlusion query, this is useful if the occlusion query is taking long time before to the query result is retireved, the query result indicates if the object is visible within the scene or not and based on that Babylon.Js engine decideds to show or hide the object.
  11926. * The default value is -1 which means don't break the query and wait till the result.
  11927. */
  11928. _this.occlusionRetryCount = -1;
  11929. _this._occlusionInternalRetryCounter = 0;
  11930. _this._isOccluded = false;
  11931. _this._isOcclusionQueryInProgress = false;
  11932. _this._rotation = BABYLON.Vector3.Zero();
  11933. _this._scaling = BABYLON.Vector3.One();
  11934. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  11935. _this.visibility = 1.0;
  11936. _this.alphaIndex = Number.MAX_VALUE;
  11937. _this.infiniteDistance = false;
  11938. _this.isVisible = true;
  11939. _this.isPickable = true;
  11940. _this.showBoundingBox = false;
  11941. _this.showSubMeshesBoundingBox = false;
  11942. _this.isBlocker = false;
  11943. _this.enablePointerMoveEvents = false;
  11944. _this.renderingGroupId = 0;
  11945. _this._receiveShadows = false;
  11946. _this.renderOutline = false;
  11947. _this.outlineColor = BABYLON.Color3.Red();
  11948. _this.outlineWidth = 0.02;
  11949. _this.renderOverlay = false;
  11950. _this.overlayColor = BABYLON.Color3.Red();
  11951. _this.overlayAlpha = 0.5;
  11952. _this._hasVertexAlpha = false;
  11953. _this._useVertexColors = true;
  11954. _this._computeBonesUsingShaders = true;
  11955. _this._numBoneInfluencers = 4;
  11956. _this._applyFog = true;
  11957. _this.scalingDeterminant = 1;
  11958. _this.useOctreeForRenderingSelection = true;
  11959. _this.useOctreeForPicking = true;
  11960. _this.useOctreeForCollisions = true;
  11961. _this._layerMask = 0x0FFFFFFF;
  11962. /**
  11963. * True if the mesh must be rendered in any case.
  11964. */
  11965. _this.alwaysSelectAsActiveMesh = false;
  11966. // Collisions
  11967. _this._checkCollisions = false;
  11968. _this._collisionMask = -1;
  11969. _this._collisionGroup = -1;
  11970. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11971. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  11972. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11973. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11974. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11975. // Edges
  11976. _this.edgesWidth = 1;
  11977. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  11978. // Cache
  11979. _this._localWorld = BABYLON.Matrix.Zero();
  11980. _this._worldMatrix = BABYLON.Matrix.Zero();
  11981. _this._absolutePosition = BABYLON.Vector3.Zero();
  11982. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  11983. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  11984. _this._isDirty = false;
  11985. _this._pivotMatrix = BABYLON.Matrix.Identity();
  11986. _this._isDisposed = false;
  11987. _this._renderId = 0;
  11988. _this._intersectionsInProgress = new Array();
  11989. _this._isWorldMatrixFrozen = false;
  11990. _this._unIndexed = false;
  11991. _this._lightSources = new Array();
  11992. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11993. if (collidedMesh === void 0) { collidedMesh = null; }
  11994. //TODO move this to the collision coordinator!
  11995. if (_this.getScene().workerCollisions)
  11996. newPosition.multiplyInPlace(_this._collider.radius);
  11997. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  11998. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  11999. _this.position.addInPlace(_this._diffPositionForCollisions);
  12000. }
  12001. if (collidedMesh) {
  12002. _this.onCollideObservable.notifyObservers(collidedMesh);
  12003. }
  12004. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  12005. };
  12006. _this.getScene().addMesh(_this);
  12007. _this._resyncLightSources();
  12008. return _this;
  12009. }
  12010. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  12011. get: function () {
  12012. return AbstractMesh._BILLBOARDMODE_NONE;
  12013. },
  12014. enumerable: true,
  12015. configurable: true
  12016. });
  12017. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  12018. get: function () {
  12019. return AbstractMesh._BILLBOARDMODE_X;
  12020. },
  12021. enumerable: true,
  12022. configurable: true
  12023. });
  12024. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  12025. get: function () {
  12026. return AbstractMesh._BILLBOARDMODE_Y;
  12027. },
  12028. enumerable: true,
  12029. configurable: true
  12030. });
  12031. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  12032. get: function () {
  12033. return AbstractMesh._BILLBOARDMODE_Z;
  12034. },
  12035. enumerable: true,
  12036. configurable: true
  12037. });
  12038. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  12039. get: function () {
  12040. return AbstractMesh._BILLBOARDMODE_ALL;
  12041. },
  12042. enumerable: true,
  12043. configurable: true
  12044. });
  12045. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  12046. /**
  12047. * Read-only : the number of facets in the mesh
  12048. */
  12049. get: function () {
  12050. return this._facetNb;
  12051. },
  12052. enumerable: true,
  12053. configurable: true
  12054. });
  12055. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  12056. /**
  12057. * The number (integer) of subdivisions per axis in the partioning space
  12058. */
  12059. get: function () {
  12060. return this._partitioningSubdivisions;
  12061. },
  12062. set: function (nb) {
  12063. this._partitioningSubdivisions = nb;
  12064. },
  12065. enumerable: true,
  12066. configurable: true
  12067. });
  12068. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  12069. /**
  12070. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  12071. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  12072. */
  12073. get: function () {
  12074. return this._partitioningBBoxRatio;
  12075. },
  12076. set: function (ratio) {
  12077. this._partitioningBBoxRatio = ratio;
  12078. },
  12079. enumerable: true,
  12080. configurable: true
  12081. });
  12082. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  12083. /**
  12084. * Read-only boolean : is the feature facetData enabled ?
  12085. */
  12086. get: function () {
  12087. return this._facetDataEnabled;
  12088. },
  12089. enumerable: true,
  12090. configurable: true
  12091. });
  12092. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  12093. set: function (callback) {
  12094. if (this._onCollideObserver) {
  12095. this.onCollideObservable.remove(this._onCollideObserver);
  12096. }
  12097. this._onCollideObserver = this.onCollideObservable.add(callback);
  12098. },
  12099. enumerable: true,
  12100. configurable: true
  12101. });
  12102. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  12103. set: function (callback) {
  12104. if (this._onCollisionPositionChangeObserver) {
  12105. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  12106. }
  12107. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  12108. },
  12109. enumerable: true,
  12110. configurable: true
  12111. });
  12112. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  12113. /**
  12114. * Property isOccluded : Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not.
  12115. */
  12116. get: function () {
  12117. return this._isOccluded;
  12118. },
  12119. set: function (value) {
  12120. this._isOccluded = value;
  12121. },
  12122. enumerable: true,
  12123. configurable: true
  12124. });
  12125. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  12126. /**
  12127. * Flag to check the progress status of the query
  12128. */
  12129. get: function () {
  12130. return this._isOcclusionQueryInProgress;
  12131. },
  12132. enumerable: true,
  12133. configurable: true
  12134. });
  12135. Object.defineProperty(AbstractMesh.prototype, "material", {
  12136. get: function () {
  12137. return this._material;
  12138. },
  12139. set: function (value) {
  12140. if (this._material === value) {
  12141. return;
  12142. }
  12143. this._material = value;
  12144. if (this.onMaterialChangedObservable.hasObservers) {
  12145. this.onMaterialChangedObservable.notifyObservers(this);
  12146. }
  12147. if (!this.subMeshes) {
  12148. return;
  12149. }
  12150. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12151. var subMesh = _a[_i];
  12152. subMesh.setEffect(null);
  12153. }
  12154. },
  12155. enumerable: true,
  12156. configurable: true
  12157. });
  12158. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  12159. get: function () {
  12160. return this._receiveShadows;
  12161. },
  12162. set: function (value) {
  12163. if (this._receiveShadows === value) {
  12164. return;
  12165. }
  12166. this._receiveShadows = value;
  12167. this._markSubMeshesAsLightDirty();
  12168. },
  12169. enumerable: true,
  12170. configurable: true
  12171. });
  12172. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  12173. get: function () {
  12174. return this._hasVertexAlpha;
  12175. },
  12176. set: function (value) {
  12177. if (this._hasVertexAlpha === value) {
  12178. return;
  12179. }
  12180. this._hasVertexAlpha = value;
  12181. this._markSubMeshesAsAttributesDirty();
  12182. },
  12183. enumerable: true,
  12184. configurable: true
  12185. });
  12186. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  12187. get: function () {
  12188. return this._useVertexColors;
  12189. },
  12190. set: function (value) {
  12191. if (this._useVertexColors === value) {
  12192. return;
  12193. }
  12194. this._useVertexColors = value;
  12195. this._markSubMeshesAsAttributesDirty();
  12196. },
  12197. enumerable: true,
  12198. configurable: true
  12199. });
  12200. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  12201. get: function () {
  12202. return this._computeBonesUsingShaders;
  12203. },
  12204. set: function (value) {
  12205. if (this._computeBonesUsingShaders === value) {
  12206. return;
  12207. }
  12208. this._computeBonesUsingShaders = value;
  12209. this._markSubMeshesAsAttributesDirty();
  12210. },
  12211. enumerable: true,
  12212. configurable: true
  12213. });
  12214. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  12215. get: function () {
  12216. return this._numBoneInfluencers;
  12217. },
  12218. set: function (value) {
  12219. if (this._numBoneInfluencers === value) {
  12220. return;
  12221. }
  12222. this._numBoneInfluencers = value;
  12223. this._markSubMeshesAsAttributesDirty();
  12224. },
  12225. enumerable: true,
  12226. configurable: true
  12227. });
  12228. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  12229. get: function () {
  12230. return this._applyFog;
  12231. },
  12232. set: function (value) {
  12233. if (this._applyFog === value) {
  12234. return;
  12235. }
  12236. this._applyFog = value;
  12237. this._markSubMeshesAsMiscDirty();
  12238. },
  12239. enumerable: true,
  12240. configurable: true
  12241. });
  12242. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  12243. get: function () {
  12244. return this._layerMask;
  12245. },
  12246. set: function (value) {
  12247. if (value === this._layerMask) {
  12248. return;
  12249. }
  12250. this._layerMask = value;
  12251. this._resyncLightSources();
  12252. },
  12253. enumerable: true,
  12254. configurable: true
  12255. });
  12256. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  12257. get: function () {
  12258. return this._collisionMask;
  12259. },
  12260. set: function (mask) {
  12261. this._collisionMask = !isNaN(mask) ? mask : -1;
  12262. },
  12263. enumerable: true,
  12264. configurable: true
  12265. });
  12266. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  12267. get: function () {
  12268. return this._collisionGroup;
  12269. },
  12270. set: function (mask) {
  12271. this._collisionGroup = !isNaN(mask) ? mask : -1;
  12272. },
  12273. enumerable: true,
  12274. configurable: true
  12275. });
  12276. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  12277. get: function () {
  12278. return null;
  12279. },
  12280. enumerable: true,
  12281. configurable: true
  12282. });
  12283. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  12284. get: function () {
  12285. return this._skeleton;
  12286. },
  12287. set: function (value) {
  12288. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  12289. this._skeleton._unregisterMeshWithPoseMatrix(this);
  12290. }
  12291. if (value && value.needInitialSkinMatrix) {
  12292. value._registerMeshWithPoseMatrix(this);
  12293. }
  12294. this._skeleton = value;
  12295. if (!this._skeleton) {
  12296. this._bonesTransformMatrices = null;
  12297. }
  12298. this._markSubMeshesAsAttributesDirty();
  12299. },
  12300. enumerable: true,
  12301. configurable: true
  12302. });
  12303. /**
  12304. * Boolean : true if the mesh has been disposed.
  12305. */
  12306. AbstractMesh.prototype.isDisposed = function () {
  12307. return this._isDisposed;
  12308. };
  12309. /**
  12310. * Returns the string "AbstractMesh"
  12311. */
  12312. AbstractMesh.prototype.getClassName = function () {
  12313. return "AbstractMesh";
  12314. };
  12315. /**
  12316. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12317. */
  12318. AbstractMesh.prototype.toString = function (fullDetails) {
  12319. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  12320. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  12321. if (this._skeleton) {
  12322. ret += ", skeleton: " + this._skeleton.name;
  12323. }
  12324. if (fullDetails) {
  12325. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  12326. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  12327. }
  12328. return ret;
  12329. };
  12330. AbstractMesh.prototype._rebuild = function () {
  12331. if (this._occlusionQuery) {
  12332. this._occlusionQuery = null;
  12333. }
  12334. if (!this.subMeshes) {
  12335. return;
  12336. }
  12337. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12338. var subMesh = _a[_i];
  12339. subMesh._rebuild();
  12340. }
  12341. };
  12342. AbstractMesh.prototype._resyncLightSources = function () {
  12343. this._lightSources.length = 0;
  12344. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  12345. var light = _a[_i];
  12346. if (!light.isEnabled()) {
  12347. continue;
  12348. }
  12349. if (light.canAffectMesh(this)) {
  12350. this._lightSources.push(light);
  12351. }
  12352. }
  12353. this._markSubMeshesAsLightDirty();
  12354. };
  12355. AbstractMesh.prototype._resyncLighSource = function (light) {
  12356. var isIn = light.isEnabled() && light.canAffectMesh(this);
  12357. var index = this._lightSources.indexOf(light);
  12358. if (index === -1) {
  12359. if (!isIn) {
  12360. return;
  12361. }
  12362. this._lightSources.push(light);
  12363. }
  12364. else {
  12365. if (isIn) {
  12366. return;
  12367. }
  12368. this._lightSources.splice(index, 1);
  12369. }
  12370. this._markSubMeshesAsLightDirty();
  12371. };
  12372. AbstractMesh.prototype._removeLightSource = function (light) {
  12373. var index = this._lightSources.indexOf(light);
  12374. if (index === -1) {
  12375. return;
  12376. }
  12377. this._lightSources.splice(index, 1);
  12378. };
  12379. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  12380. if (!this.subMeshes) {
  12381. return;
  12382. }
  12383. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12384. var subMesh = _a[_i];
  12385. if (subMesh._materialDefines) {
  12386. func(subMesh._materialDefines);
  12387. }
  12388. }
  12389. };
  12390. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  12391. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  12392. };
  12393. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  12394. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  12395. };
  12396. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  12397. if (!this.subMeshes) {
  12398. return;
  12399. }
  12400. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12401. var subMesh = _a[_i];
  12402. var material = subMesh.getMaterial();
  12403. if (material) {
  12404. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  12405. }
  12406. }
  12407. };
  12408. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  12409. /**
  12410. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  12411. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  12412. * Default : (0.0, 0.0, 0.0)
  12413. */
  12414. get: function () {
  12415. return this._rotation;
  12416. },
  12417. set: function (newRotation) {
  12418. this._rotation = newRotation;
  12419. },
  12420. enumerable: true,
  12421. configurable: true
  12422. });
  12423. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  12424. /**
  12425. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  12426. * Default : (1.0, 1.0, 1.0)
  12427. */
  12428. get: function () {
  12429. return this._scaling;
  12430. },
  12431. set: function (newScaling) {
  12432. this._scaling = newScaling;
  12433. if (this.physicsImpostor) {
  12434. this.physicsImpostor.forceUpdate();
  12435. }
  12436. },
  12437. enumerable: true,
  12438. configurable: true
  12439. });
  12440. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  12441. /**
  12442. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  12443. * It's null by default.
  12444. * 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)
  12445. */
  12446. get: function () {
  12447. return this._rotationQuaternion;
  12448. },
  12449. set: function (quaternion) {
  12450. this._rotationQuaternion = quaternion;
  12451. //reset the rotation vector.
  12452. if (quaternion && this.rotation.length()) {
  12453. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  12454. }
  12455. },
  12456. enumerable: true,
  12457. configurable: true
  12458. });
  12459. // Methods
  12460. /**
  12461. * Copies the paramater passed Matrix into the mesh Pose matrix.
  12462. * Returns the AbstractMesh.
  12463. */
  12464. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  12465. this._poseMatrix.copyFrom(matrix);
  12466. return this;
  12467. };
  12468. /**
  12469. * Returns the mesh Pose matrix.
  12470. * Returned object : Matrix
  12471. */
  12472. AbstractMesh.prototype.getPoseMatrix = function () {
  12473. return this._poseMatrix;
  12474. };
  12475. /**
  12476. * Disables the mesh edger rendering mode.
  12477. * Returns the AbstractMesh.
  12478. */
  12479. AbstractMesh.prototype.disableEdgesRendering = function () {
  12480. if (this._edgesRenderer !== undefined) {
  12481. this._edgesRenderer.dispose();
  12482. this._edgesRenderer = undefined;
  12483. }
  12484. return this;
  12485. };
  12486. /**
  12487. * Enables the edge rendering mode on the mesh.
  12488. * This mode makes the mesh edges visible.
  12489. * Returns the AbstractMesh.
  12490. */
  12491. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  12492. if (epsilon === void 0) { epsilon = 0.95; }
  12493. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  12494. this.disableEdgesRendering();
  12495. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  12496. return this;
  12497. };
  12498. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  12499. /**
  12500. * Returns true if the mesh is blocked. Used by the class Mesh.
  12501. * Returns the boolean `false` by default.
  12502. */
  12503. get: function () {
  12504. return false;
  12505. },
  12506. enumerable: true,
  12507. configurable: true
  12508. });
  12509. /**
  12510. * Returns the mesh itself by default, used by the class Mesh.
  12511. * Returned type : AbstractMesh
  12512. */
  12513. AbstractMesh.prototype.getLOD = function (camera) {
  12514. return this;
  12515. };
  12516. /**
  12517. * Returns 0 by default, used by the class Mesh.
  12518. * Returns an integer.
  12519. */
  12520. AbstractMesh.prototype.getTotalVertices = function () {
  12521. return 0;
  12522. };
  12523. /**
  12524. * Returns null by default, used by the class Mesh.
  12525. * Returned type : integer array
  12526. */
  12527. AbstractMesh.prototype.getIndices = function () {
  12528. return null;
  12529. };
  12530. /**
  12531. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  12532. * Returned type : float array or Float32Array
  12533. */
  12534. AbstractMesh.prototype.getVerticesData = function (kind) {
  12535. return null;
  12536. };
  12537. /**
  12538. * Sets the vertex data of the mesh geometry for the requested `kind`.
  12539. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  12540. * The `data` are either a numeric array either a Float32Array.
  12541. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  12542. * 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).
  12543. * Note that a new underlying VertexBuffer object is created each call.
  12544. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  12545. *
  12546. * Possible `kind` values :
  12547. * - BABYLON.VertexBuffer.PositionKind
  12548. * - BABYLON.VertexBuffer.UVKind
  12549. * - BABYLON.VertexBuffer.UV2Kind
  12550. * - BABYLON.VertexBuffer.UV3Kind
  12551. * - BABYLON.VertexBuffer.UV4Kind
  12552. * - BABYLON.VertexBuffer.UV5Kind
  12553. * - BABYLON.VertexBuffer.UV6Kind
  12554. * - BABYLON.VertexBuffer.ColorKind
  12555. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12556. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12557. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12558. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12559. *
  12560. * Returns the Mesh.
  12561. */
  12562. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  12563. return null;
  12564. };
  12565. /**
  12566. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  12567. * If the mesh has no geometry, it is simply returned as it is.
  12568. * The `data` are either a numeric array either a Float32Array.
  12569. * No new underlying VertexBuffer object is created.
  12570. * 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.
  12571. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  12572. *
  12573. * Possible `kind` values :
  12574. * - BABYLON.VertexBuffer.PositionKind
  12575. * - BABYLON.VertexBuffer.UVKind
  12576. * - BABYLON.VertexBuffer.UV2Kind
  12577. * - BABYLON.VertexBuffer.UV3Kind
  12578. * - BABYLON.VertexBuffer.UV4Kind
  12579. * - BABYLON.VertexBuffer.UV5Kind
  12580. * - BABYLON.VertexBuffer.UV6Kind
  12581. * - BABYLON.VertexBuffer.ColorKind
  12582. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12583. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12584. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12585. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12586. *
  12587. * Returns the Mesh.
  12588. */
  12589. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  12590. return null;
  12591. };
  12592. /**
  12593. * Sets the mesh indices.
  12594. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  12595. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  12596. * This method creates a new index buffer each call.
  12597. * Returns the Mesh.
  12598. */
  12599. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  12600. return null;
  12601. };
  12602. /** Returns false by default, used by the class Mesh.
  12603. * Returns a boolean
  12604. */
  12605. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  12606. return false;
  12607. };
  12608. /**
  12609. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  12610. * Returns a BoundingInfo
  12611. */
  12612. AbstractMesh.prototype.getBoundingInfo = function () {
  12613. if (this._masterMesh) {
  12614. return this._masterMesh.getBoundingInfo();
  12615. }
  12616. if (!this._boundingInfo) {
  12617. this._updateBoundingInfo();
  12618. }
  12619. return this._boundingInfo;
  12620. };
  12621. /**
  12622. * Sets a mesh new object BoundingInfo.
  12623. * Returns the AbstractMesh.
  12624. */
  12625. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  12626. this._boundingInfo = boundingInfo;
  12627. return this;
  12628. };
  12629. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  12630. get: function () {
  12631. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  12632. },
  12633. enumerable: true,
  12634. configurable: true
  12635. });
  12636. AbstractMesh.prototype._preActivate = function () {
  12637. };
  12638. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  12639. };
  12640. AbstractMesh.prototype._activate = function (renderId) {
  12641. this._renderId = renderId;
  12642. };
  12643. /**
  12644. * Returns the last update of the World matrix
  12645. * Returns a Matrix.
  12646. */
  12647. AbstractMesh.prototype.getWorldMatrix = function () {
  12648. if (this._masterMesh) {
  12649. return this._masterMesh.getWorldMatrix();
  12650. }
  12651. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  12652. this.computeWorldMatrix();
  12653. }
  12654. return this._worldMatrix;
  12655. };
  12656. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  12657. /**
  12658. * Returns directly the last state of the mesh World matrix.
  12659. * A Matrix is returned.
  12660. */
  12661. get: function () {
  12662. return this._worldMatrix;
  12663. },
  12664. enumerable: true,
  12665. configurable: true
  12666. });
  12667. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  12668. /**
  12669. * Returns the current mesh absolute position.
  12670. * Retuns a Vector3.
  12671. */
  12672. get: function () {
  12673. return this._absolutePosition;
  12674. },
  12675. enumerable: true,
  12676. configurable: true
  12677. });
  12678. /**
  12679. * Prevents the World matrix to be computed any longer.
  12680. * Returns the AbstractMesh.
  12681. */
  12682. AbstractMesh.prototype.freezeWorldMatrix = function () {
  12683. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  12684. this.computeWorldMatrix(true);
  12685. this._isWorldMatrixFrozen = true;
  12686. return this;
  12687. };
  12688. /**
  12689. * Allows back the World matrix computation.
  12690. * Returns the AbstractMesh.
  12691. */
  12692. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  12693. this._isWorldMatrixFrozen = false;
  12694. this.computeWorldMatrix(true);
  12695. return this;
  12696. };
  12697. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  12698. /**
  12699. * True if the World matrix has been frozen.
  12700. * Returns a boolean.
  12701. */
  12702. get: function () {
  12703. return this._isWorldMatrixFrozen;
  12704. },
  12705. enumerable: true,
  12706. configurable: true
  12707. });
  12708. /**
  12709. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  12710. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12711. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12712. * The passed axis is also normalized.
  12713. * Returns the AbstractMesh.
  12714. */
  12715. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  12716. axis.normalize();
  12717. if (!this.rotationQuaternion) {
  12718. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12719. this.rotation = BABYLON.Vector3.Zero();
  12720. }
  12721. var rotationQuaternion;
  12722. if (!space || space === BABYLON.Space.LOCAL) {
  12723. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12724. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  12725. }
  12726. else {
  12727. if (this.parent) {
  12728. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12729. invertParentWorldMatrix.invert();
  12730. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  12731. }
  12732. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12733. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  12734. }
  12735. return this;
  12736. };
  12737. /**
  12738. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  12739. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12740. * The passed axis is also normalized.
  12741. * Returns the AbstractMesh.
  12742. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  12743. */
  12744. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  12745. axis.normalize();
  12746. if (!this.rotationQuaternion) {
  12747. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12748. this.rotation.copyFromFloats(0, 0, 0);
  12749. }
  12750. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  12751. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  12752. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  12753. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  12754. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  12755. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  12756. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  12757. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  12758. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  12759. return this;
  12760. };
  12761. /**
  12762. * Translates the mesh along the axis vector for the passed distance in the given space.
  12763. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12764. * Returns the AbstractMesh.
  12765. */
  12766. AbstractMesh.prototype.translate = function (axis, distance, space) {
  12767. var displacementVector = axis.scale(distance);
  12768. if (!space || space === BABYLON.Space.LOCAL) {
  12769. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  12770. this.setPositionWithLocalVector(tempV3);
  12771. }
  12772. else {
  12773. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  12774. }
  12775. return this;
  12776. };
  12777. /**
  12778. * Adds a rotation step to the mesh current rotation.
  12779. * x, y, z are Euler angles expressed in radians.
  12780. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  12781. * This means this rotation is made in the mesh local space only.
  12782. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  12783. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  12784. * ```javascript
  12785. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  12786. * ```
  12787. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  12788. * 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.
  12789. * Returns the AbstractMesh.
  12790. */
  12791. AbstractMesh.prototype.addRotation = function (x, y, z) {
  12792. var rotationQuaternion;
  12793. if (this.rotationQuaternion) {
  12794. rotationQuaternion = this.rotationQuaternion;
  12795. }
  12796. else {
  12797. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  12798. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  12799. }
  12800. var accumulation = BABYLON.Tmp.Quaternion[0];
  12801. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  12802. rotationQuaternion.multiplyInPlace(accumulation);
  12803. if (!this.rotationQuaternion) {
  12804. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  12805. }
  12806. return this;
  12807. };
  12808. /**
  12809. * Retuns the mesh absolute position in the World.
  12810. * Returns a Vector3.
  12811. */
  12812. AbstractMesh.prototype.getAbsolutePosition = function () {
  12813. this.computeWorldMatrix();
  12814. return this._absolutePosition;
  12815. };
  12816. /**
  12817. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  12818. * Returns the AbstractMesh.
  12819. */
  12820. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  12821. if (!absolutePosition) {
  12822. return;
  12823. }
  12824. var absolutePositionX;
  12825. var absolutePositionY;
  12826. var absolutePositionZ;
  12827. if (absolutePosition.x === undefined) {
  12828. if (arguments.length < 3) {
  12829. return;
  12830. }
  12831. absolutePositionX = arguments[0];
  12832. absolutePositionY = arguments[1];
  12833. absolutePositionZ = arguments[2];
  12834. }
  12835. else {
  12836. absolutePositionX = absolutePosition.x;
  12837. absolutePositionY = absolutePosition.y;
  12838. absolutePositionZ = absolutePosition.z;
  12839. }
  12840. if (this.parent) {
  12841. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12842. invertParentWorldMatrix.invert();
  12843. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  12844. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  12845. }
  12846. else {
  12847. this.position.x = absolutePositionX;
  12848. this.position.y = absolutePositionY;
  12849. this.position.z = absolutePositionZ;
  12850. }
  12851. return this;
  12852. };
  12853. // ================================== Point of View Movement =================================
  12854. /**
  12855. * Perform relative position change from the point of view of behind the front of the mesh.
  12856. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12857. * Supports definition of mesh facing forward or backward.
  12858. * @param {number} amountRight
  12859. * @param {number} amountUp
  12860. * @param {number} amountForward
  12861. *
  12862. * Returns the AbstractMesh.
  12863. */
  12864. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  12865. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  12866. return this;
  12867. };
  12868. /**
  12869. * Calculate relative position change from the point of view of behind the front of the mesh.
  12870. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12871. * Supports definition of mesh facing forward or backward.
  12872. * @param {number} amountRight
  12873. * @param {number} amountUp
  12874. * @param {number} amountForward
  12875. *
  12876. * Returns a new Vector3.
  12877. */
  12878. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  12879. var rotMatrix = new BABYLON.Matrix();
  12880. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12881. rotQuaternion.toRotationMatrix(rotMatrix);
  12882. var translationDelta = BABYLON.Vector3.Zero();
  12883. var defForwardMult = this.definedFacingForward ? -1 : 1;
  12884. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  12885. return translationDelta;
  12886. };
  12887. // ================================== Point of View Rotation =================================
  12888. /**
  12889. * Perform relative rotation change from the point of view of behind the front of the mesh.
  12890. * Supports definition of mesh facing forward or backward.
  12891. * @param {number} flipBack
  12892. * @param {number} twirlClockwise
  12893. * @param {number} tiltRight
  12894. *
  12895. * Returns the AbstractMesh.
  12896. */
  12897. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12898. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  12899. return this;
  12900. };
  12901. /**
  12902. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  12903. * Supports definition of mesh facing forward or backward.
  12904. * @param {number} flipBack
  12905. * @param {number} twirlClockwise
  12906. * @param {number} tiltRight
  12907. *
  12908. * Returns a new Vector3.
  12909. */
  12910. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12911. var defForwardMult = this.definedFacingForward ? 1 : -1;
  12912. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  12913. };
  12914. /**
  12915. * Sets a new pivot matrix to the mesh.
  12916. * Returns the AbstractMesh.
  12917. */
  12918. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  12919. this._pivotMatrix = matrix;
  12920. this._cache.pivotMatrixUpdated = true;
  12921. return this;
  12922. };
  12923. /**
  12924. * Returns the mesh pivot matrix.
  12925. * Default : Identity.
  12926. * A Matrix is returned.
  12927. */
  12928. AbstractMesh.prototype.getPivotMatrix = function () {
  12929. return this._pivotMatrix;
  12930. };
  12931. AbstractMesh.prototype._isSynchronized = function () {
  12932. if (this._isDirty) {
  12933. return false;
  12934. }
  12935. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  12936. return false;
  12937. if (this._cache.pivotMatrixUpdated) {
  12938. return false;
  12939. }
  12940. if (this.infiniteDistance) {
  12941. return false;
  12942. }
  12943. if (!this._cache.position.equals(this.position))
  12944. return false;
  12945. if (this.rotationQuaternion) {
  12946. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  12947. return false;
  12948. }
  12949. if (!this._cache.rotation.equals(this.rotation))
  12950. return false;
  12951. if (!this._cache.scaling.equals(this.scaling))
  12952. return false;
  12953. return true;
  12954. };
  12955. AbstractMesh.prototype._initCache = function () {
  12956. _super.prototype._initCache.call(this);
  12957. this._cache.localMatrixUpdated = false;
  12958. this._cache.position = BABYLON.Vector3.Zero();
  12959. this._cache.scaling = BABYLON.Vector3.Zero();
  12960. this._cache.rotation = BABYLON.Vector3.Zero();
  12961. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  12962. this._cache.billboardMode = -1;
  12963. };
  12964. AbstractMesh.prototype.markAsDirty = function (property) {
  12965. if (property === "rotation") {
  12966. this.rotationQuaternion = null;
  12967. }
  12968. this._currentRenderId = Number.MAX_VALUE;
  12969. this._isDirty = true;
  12970. return this;
  12971. };
  12972. /**
  12973. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  12974. * Returns the AbstractMesh.
  12975. */
  12976. AbstractMesh.prototype._updateBoundingInfo = function () {
  12977. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  12978. this._boundingInfo.update(this.worldMatrixFromCache);
  12979. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  12980. return this;
  12981. };
  12982. /**
  12983. * Update a mesh's children BoundingInfo objects only.
  12984. * Returns the AbstractMesh.
  12985. */
  12986. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  12987. if (!this.subMeshes) {
  12988. return;
  12989. }
  12990. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  12991. var subMesh = this.subMeshes[subIndex];
  12992. if (!subMesh.IsGlobal) {
  12993. subMesh.updateBoundingInfo(matrix);
  12994. }
  12995. }
  12996. return this;
  12997. };
  12998. /**
  12999. * Computes the mesh World matrix and returns it.
  13000. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  13001. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  13002. * If the parameter `force`is set to `true`, the actual computation is done.
  13003. * Returns the mesh World Matrix.
  13004. */
  13005. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  13006. if (this._isWorldMatrixFrozen) {
  13007. return this._worldMatrix;
  13008. }
  13009. if (!force && this.isSynchronized(true)) {
  13010. this._currentRenderId = this.getScene().getRenderId();
  13011. return this._worldMatrix;
  13012. }
  13013. this._cache.position.copyFrom(this.position);
  13014. this._cache.scaling.copyFrom(this.scaling);
  13015. this._cache.pivotMatrixUpdated = false;
  13016. this._cache.billboardMode = this.billboardMode;
  13017. this._currentRenderId = this.getScene().getRenderId();
  13018. this._isDirty = false;
  13019. // Scaling
  13020. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  13021. // Rotation
  13022. //rotate, if quaternion is set and rotation was used
  13023. if (this.rotationQuaternion) {
  13024. var len = this.rotation.length();
  13025. if (len) {
  13026. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  13027. this.rotation.copyFromFloats(0, 0, 0);
  13028. }
  13029. }
  13030. if (this.rotationQuaternion) {
  13031. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  13032. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13033. }
  13034. else {
  13035. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  13036. this._cache.rotation.copyFrom(this.rotation);
  13037. }
  13038. // Translation
  13039. if (this.infiniteDistance && !this.parent) {
  13040. var camera = this.getScene().activeCamera;
  13041. if (camera) {
  13042. var cameraWorldMatrix = camera.getWorldMatrix();
  13043. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  13044. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  13045. }
  13046. }
  13047. else {
  13048. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  13049. }
  13050. // Composing transformations
  13051. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  13052. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13053. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  13054. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  13055. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  13056. // Need to decompose each rotation here
  13057. var currentPosition = BABYLON.Tmp.Vector3[3];
  13058. if (this.parent && this.parent.getWorldMatrix) {
  13059. if (this._meshToBoneReferal) {
  13060. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13061. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  13062. }
  13063. else {
  13064. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  13065. }
  13066. }
  13067. else {
  13068. currentPosition.copyFrom(this.position);
  13069. }
  13070. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  13071. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  13072. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  13073. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  13074. }
  13075. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  13076. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  13077. }
  13078. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  13079. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  13080. }
  13081. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  13082. }
  13083. else {
  13084. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  13085. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  13086. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  13087. }
  13088. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  13089. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13090. }
  13091. // Local world
  13092. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  13093. // Parent
  13094. if (this.parent && this.parent.getWorldMatrix) {
  13095. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  13096. if (this._meshToBoneReferal) {
  13097. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13098. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  13099. }
  13100. else {
  13101. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  13102. }
  13103. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  13104. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  13105. this._worldMatrix.copyFrom(this._localWorld);
  13106. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  13107. }
  13108. else {
  13109. if (this._meshToBoneReferal) {
  13110. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13111. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  13112. }
  13113. else {
  13114. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  13115. }
  13116. }
  13117. this._markSyncedWithParent();
  13118. }
  13119. else {
  13120. this._worldMatrix.copyFrom(this._localWorld);
  13121. }
  13122. // Bounding info
  13123. this._updateBoundingInfo();
  13124. // Absolute position
  13125. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  13126. // Callbacks
  13127. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  13128. if (!this._poseMatrix) {
  13129. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  13130. }
  13131. return this._worldMatrix;
  13132. };
  13133. /**
  13134. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  13135. * @param func: callback function to add
  13136. *
  13137. * Returns the AbstractMesh.
  13138. */
  13139. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  13140. this.onAfterWorldMatrixUpdateObservable.add(func);
  13141. return this;
  13142. };
  13143. /**
  13144. * Removes a registered callback function.
  13145. * Returns the AbstractMesh.
  13146. */
  13147. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  13148. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  13149. return this;
  13150. };
  13151. /**
  13152. * Sets the mesh position in its local space.
  13153. * Returns the AbstractMesh.
  13154. */
  13155. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  13156. this.computeWorldMatrix();
  13157. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  13158. return this;
  13159. };
  13160. /**
  13161. * Returns the mesh position in the local space from the current World matrix values.
  13162. * Returns a new Vector3.
  13163. */
  13164. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  13165. this.computeWorldMatrix();
  13166. var invLocalWorldMatrix = this._localWorld.clone();
  13167. invLocalWorldMatrix.invert();
  13168. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  13169. };
  13170. /**
  13171. * Translates the mesh along the passed Vector3 in its local space.
  13172. * Returns the AbstractMesh.
  13173. */
  13174. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  13175. this.computeWorldMatrix(true);
  13176. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  13177. return this;
  13178. };
  13179. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  13180. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  13181. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  13182. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  13183. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  13184. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  13185. /// <returns>Mesh oriented towards targetMesh</returns>
  13186. if (yawCor === void 0) { yawCor = 0; }
  13187. if (pitchCor === void 0) { pitchCor = 0; }
  13188. if (rollCor === void 0) { rollCor = 0; }
  13189. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13190. var dv = AbstractMesh._lookAtVectorCache;
  13191. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  13192. targetPoint.subtractToRef(pos, dv);
  13193. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  13194. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  13195. var pitch = Math.atan2(dv.y, len);
  13196. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  13197. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  13198. return this;
  13199. };
  13200. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  13201. this._meshToBoneReferal = affectedMesh;
  13202. this.parent = bone;
  13203. if (bone.getWorldMatrix().determinant() < 0) {
  13204. this.scalingDeterminant *= -1;
  13205. }
  13206. return this;
  13207. };
  13208. AbstractMesh.prototype.detachFromBone = function () {
  13209. if (this.parent.getWorldMatrix().determinant() < 0) {
  13210. this.scalingDeterminant *= -1;
  13211. }
  13212. this._meshToBoneReferal = null;
  13213. this.parent = null;
  13214. return this;
  13215. };
  13216. /**
  13217. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  13218. * A mesh is in the frustum if its bounding box intersects the frustum.
  13219. * Boolean returned.
  13220. */
  13221. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  13222. return this._boundingInfo.isInFrustum(frustumPlanes);
  13223. };
  13224. /**
  13225. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  13226. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  13227. * Boolean returned.
  13228. */
  13229. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  13230. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  13231. ;
  13232. };
  13233. /**
  13234. * True if the mesh intersects another mesh or a SolidParticle object.
  13235. * 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)
  13236. * Returns a boolean.
  13237. */
  13238. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  13239. if (!this._boundingInfo || !mesh._boundingInfo) {
  13240. return false;
  13241. }
  13242. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  13243. };
  13244. /**
  13245. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  13246. * Returns a boolean.
  13247. */
  13248. AbstractMesh.prototype.intersectsPoint = function (point) {
  13249. if (!this._boundingInfo) {
  13250. return false;
  13251. }
  13252. return this._boundingInfo.intersectsPoint(point);
  13253. };
  13254. AbstractMesh.prototype.getPhysicsImpostor = function () {
  13255. return this.physicsImpostor;
  13256. };
  13257. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  13258. if (!camera) {
  13259. camera = this.getScene().activeCamera;
  13260. }
  13261. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  13262. };
  13263. /**
  13264. * Returns the distance from the mesh to the active camera.
  13265. * Returns a float.
  13266. */
  13267. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  13268. if (!camera) {
  13269. camera = this.getScene().activeCamera;
  13270. }
  13271. return this.absolutePosition.subtract(camera.position).length();
  13272. };
  13273. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  13274. if (!this.physicsImpostor) {
  13275. return;
  13276. }
  13277. this.physicsImpostor.applyImpulse(force, contactPoint);
  13278. return this;
  13279. };
  13280. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  13281. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  13282. return;
  13283. }
  13284. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  13285. mainPivot: pivot1,
  13286. connectedPivot: pivot2,
  13287. nativeParams: options
  13288. });
  13289. return this;
  13290. };
  13291. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  13292. // Collisions
  13293. /**
  13294. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  13295. * Default `false`.
  13296. */
  13297. get: function () {
  13298. return this._checkCollisions;
  13299. },
  13300. set: function (collisionEnabled) {
  13301. this._checkCollisions = collisionEnabled;
  13302. if (this.getScene().workerCollisions) {
  13303. this.getScene().collisionCoordinator.onMeshUpdated(this);
  13304. }
  13305. },
  13306. enumerable: true,
  13307. configurable: true
  13308. });
  13309. AbstractMesh.prototype.moveWithCollisions = function (direction) {
  13310. var globalPosition = this.getAbsolutePosition();
  13311. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  13312. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  13313. if (!this._collider) {
  13314. this._collider = new BABYLON.Collider();
  13315. }
  13316. this._collider.radius = this.ellipsoid;
  13317. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, direction, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  13318. return this;
  13319. };
  13320. // Submeshes octree
  13321. /**
  13322. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  13323. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  13324. * Returns an Octree of submeshes.
  13325. */
  13326. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  13327. if (maxCapacity === void 0) { maxCapacity = 64; }
  13328. if (maxDepth === void 0) { maxDepth = 2; }
  13329. if (!this._submeshesOctree) {
  13330. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  13331. }
  13332. this.computeWorldMatrix(true);
  13333. // Update octree
  13334. var bbox = this.getBoundingInfo().boundingBox;
  13335. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  13336. return this._submeshesOctree;
  13337. };
  13338. // Collisions
  13339. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  13340. this._generatePointsArray();
  13341. // Transformation
  13342. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  13343. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  13344. subMesh._lastColliderWorldVertices = [];
  13345. subMesh._trianglePlanes = [];
  13346. var start = subMesh.verticesStart;
  13347. var end = (subMesh.verticesStart + subMesh.verticesCount);
  13348. for (var i = start; i < end; i++) {
  13349. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  13350. }
  13351. }
  13352. // Collide
  13353. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  13354. if (collider.collisionFound) {
  13355. collider.collidedMesh = this;
  13356. }
  13357. return this;
  13358. };
  13359. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  13360. var subMeshes;
  13361. var len;
  13362. // Octrees
  13363. if (this._submeshesOctree && this.useOctreeForCollisions) {
  13364. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  13365. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  13366. len = intersections.length;
  13367. subMeshes = intersections.data;
  13368. }
  13369. else {
  13370. subMeshes = this.subMeshes;
  13371. len = subMeshes.length;
  13372. }
  13373. for (var index = 0; index < len; index++) {
  13374. var subMesh = subMeshes[index];
  13375. // Bounding test
  13376. if (len > 1 && !subMesh._checkCollision(collider))
  13377. continue;
  13378. this._collideForSubMesh(subMesh, transformMatrix, collider);
  13379. }
  13380. return this;
  13381. };
  13382. AbstractMesh.prototype._checkCollision = function (collider) {
  13383. // Bounding box test
  13384. if (!this._boundingInfo._checkCollision(collider))
  13385. return this;
  13386. // Transformation matrix
  13387. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  13388. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  13389. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  13390. return this;
  13391. };
  13392. // Picking
  13393. AbstractMesh.prototype._generatePointsArray = function () {
  13394. return false;
  13395. };
  13396. /**
  13397. * Checks if the passed Ray intersects with the mesh.
  13398. * Returns an object PickingInfo.
  13399. */
  13400. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  13401. var pickingInfo = new BABYLON.PickingInfo();
  13402. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  13403. return pickingInfo;
  13404. }
  13405. if (!this._generatePointsArray()) {
  13406. return pickingInfo;
  13407. }
  13408. var intersectInfo = null;
  13409. // Octrees
  13410. var subMeshes;
  13411. var len;
  13412. if (this._submeshesOctree && this.useOctreeForPicking) {
  13413. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  13414. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  13415. len = intersections.length;
  13416. subMeshes = intersections.data;
  13417. }
  13418. else {
  13419. subMeshes = this.subMeshes;
  13420. len = subMeshes.length;
  13421. }
  13422. for (var index = 0; index < len; index++) {
  13423. var subMesh = subMeshes[index];
  13424. // Bounding test
  13425. if (len > 1 && !subMesh.canIntersects(ray))
  13426. continue;
  13427. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  13428. if (currentIntersectInfo) {
  13429. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  13430. intersectInfo = currentIntersectInfo;
  13431. intersectInfo.subMeshId = index;
  13432. if (fastCheck) {
  13433. break;
  13434. }
  13435. }
  13436. }
  13437. }
  13438. if (intersectInfo) {
  13439. // Get picked point
  13440. var world = this.getWorldMatrix();
  13441. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  13442. var direction = ray.direction.clone();
  13443. direction = direction.scale(intersectInfo.distance);
  13444. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  13445. var pickedPoint = worldOrigin.add(worldDirection);
  13446. // Return result
  13447. pickingInfo.hit = true;
  13448. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  13449. pickingInfo.pickedPoint = pickedPoint;
  13450. pickingInfo.pickedMesh = this;
  13451. pickingInfo.bu = intersectInfo.bu;
  13452. pickingInfo.bv = intersectInfo.bv;
  13453. pickingInfo.faceId = intersectInfo.faceId;
  13454. pickingInfo.subMeshId = intersectInfo.subMeshId;
  13455. return pickingInfo;
  13456. }
  13457. return pickingInfo;
  13458. };
  13459. /**
  13460. * Clones the mesh, used by the class Mesh.
  13461. * Just returns `null` for an AbstractMesh.
  13462. */
  13463. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13464. return null;
  13465. };
  13466. /**
  13467. * Disposes all the mesh submeshes.
  13468. * Returns the AbstractMesh.
  13469. */
  13470. AbstractMesh.prototype.releaseSubMeshes = function () {
  13471. if (this.subMeshes) {
  13472. while (this.subMeshes.length) {
  13473. this.subMeshes[0].dispose();
  13474. }
  13475. }
  13476. else {
  13477. this.subMeshes = new Array();
  13478. }
  13479. return this;
  13480. };
  13481. /**
  13482. * Disposes the AbstractMesh.
  13483. * Some internal references are kept for further use.
  13484. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  13485. * Returns nothing.
  13486. */
  13487. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  13488. var _this = this;
  13489. var index;
  13490. // Action manager
  13491. if (this.actionManager) {
  13492. this.actionManager.dispose();
  13493. this.actionManager = null;
  13494. }
  13495. // Skeleton
  13496. this.skeleton = null;
  13497. // Animations
  13498. this.getScene().stopAnimation(this);
  13499. // Physics
  13500. if (this.physicsImpostor) {
  13501. this.physicsImpostor.dispose();
  13502. }
  13503. // Intersections in progress
  13504. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  13505. var other = this._intersectionsInProgress[index];
  13506. var pos = other._intersectionsInProgress.indexOf(this);
  13507. other._intersectionsInProgress.splice(pos, 1);
  13508. }
  13509. this._intersectionsInProgress = [];
  13510. // Lights
  13511. var lights = this.getScene().lights;
  13512. lights.forEach(function (light) {
  13513. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  13514. if (meshIndex !== -1) {
  13515. light.includedOnlyMeshes.splice(meshIndex, 1);
  13516. }
  13517. meshIndex = light.excludedMeshes.indexOf(_this);
  13518. if (meshIndex !== -1) {
  13519. light.excludedMeshes.splice(meshIndex, 1);
  13520. }
  13521. // Shadow generators
  13522. var generator = light.getShadowGenerator();
  13523. if (generator) {
  13524. var shadowMap = generator.getShadowMap();
  13525. meshIndex = shadowMap.renderList.indexOf(_this);
  13526. if (meshIndex !== -1) {
  13527. shadowMap.renderList.splice(meshIndex, 1);
  13528. }
  13529. }
  13530. });
  13531. // Edges
  13532. if (this._edgesRenderer) {
  13533. this._edgesRenderer.dispose();
  13534. this._edgesRenderer = null;
  13535. }
  13536. // SubMeshes
  13537. if (this.getClassName() !== "InstancedMesh") {
  13538. this.releaseSubMeshes();
  13539. }
  13540. // Octree
  13541. var sceneOctree = this.getScene().selectionOctree;
  13542. if (sceneOctree) {
  13543. var index = sceneOctree.dynamicContent.indexOf(this);
  13544. if (index !== -1) {
  13545. sceneOctree.dynamicContent.splice(index, 1);
  13546. }
  13547. }
  13548. // Query
  13549. var engine = this.getScene().getEngine();
  13550. if (this._occlusionQuery) {
  13551. this._isOcclusionQueryInProgress = false;
  13552. engine.deleteQuery(this._occlusionQuery);
  13553. this._occlusionQuery = null;
  13554. }
  13555. // Engine
  13556. engine.wipeCaches();
  13557. // Remove from scene
  13558. this.getScene().removeMesh(this);
  13559. if (!doNotRecurse) {
  13560. // Particles
  13561. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  13562. if (this.getScene().particleSystems[index].emitter === this) {
  13563. this.getScene().particleSystems[index].dispose();
  13564. index--;
  13565. }
  13566. }
  13567. // Children
  13568. var objects = this.getDescendants(true);
  13569. for (index = 0; index < objects.length; index++) {
  13570. objects[index].dispose();
  13571. }
  13572. }
  13573. else {
  13574. var childMeshes = this.getChildMeshes(true);
  13575. for (index = 0; index < childMeshes.length; index++) {
  13576. var child = childMeshes[index];
  13577. child.parent = null;
  13578. child.computeWorldMatrix(true);
  13579. }
  13580. }
  13581. // facet data
  13582. if (this._facetDataEnabled) {
  13583. this.disableFacetData();
  13584. }
  13585. this.onAfterWorldMatrixUpdateObservable.clear();
  13586. this.onCollideObservable.clear();
  13587. this.onCollisionPositionChangeObservable.clear();
  13588. this._isDisposed = true;
  13589. _super.prototype.dispose.call(this);
  13590. };
  13591. /**
  13592. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13593. * This Vector3 is expressed in the World space.
  13594. */
  13595. AbstractMesh.prototype.getDirection = function (localAxis) {
  13596. var result = BABYLON.Vector3.Zero();
  13597. this.getDirectionToRef(localAxis, result);
  13598. return result;
  13599. };
  13600. /**
  13601. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13602. * localAxis is expressed in the mesh local space.
  13603. * result is computed in the Wordl space from the mesh World matrix.
  13604. * Returns the AbstractMesh.
  13605. */
  13606. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  13607. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13608. return this;
  13609. };
  13610. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  13611. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13612. if (this.getScene().getRenderId() == 0) {
  13613. this.computeWorldMatrix(true);
  13614. }
  13615. var wm = this.getWorldMatrix();
  13616. if (space == BABYLON.Space.WORLD) {
  13617. var tmat = BABYLON.Tmp.Matrix[0];
  13618. wm.invertToRef(tmat);
  13619. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13620. }
  13621. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13622. this._pivotMatrix.m[12] = -point.x;
  13623. this._pivotMatrix.m[13] = -point.y;
  13624. this._pivotMatrix.m[14] = -point.z;
  13625. this._cache.pivotMatrixUpdated = true;
  13626. return this;
  13627. };
  13628. /**
  13629. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13630. */
  13631. AbstractMesh.prototype.getPivotPoint = function () {
  13632. var point = BABYLON.Vector3.Zero();
  13633. this.getPivotPointToRef(point);
  13634. return point;
  13635. };
  13636. /**
  13637. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13638. * Returns the AbstractMesh.
  13639. */
  13640. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  13641. result.x = -this._pivotMatrix.m[12];
  13642. result.y = -this._pivotMatrix.m[13];
  13643. result.z = -this._pivotMatrix.m[14];
  13644. return this;
  13645. };
  13646. /**
  13647. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13648. */
  13649. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  13650. var point = BABYLON.Vector3.Zero();
  13651. this.getAbsolutePivotPointToRef(point);
  13652. return point;
  13653. };
  13654. /**
  13655. * Defines the passed mesh as the parent of the current mesh.
  13656. * Returns the AbstractMesh.
  13657. */
  13658. AbstractMesh.prototype.setParent = function (mesh) {
  13659. var child = this;
  13660. var parent = mesh;
  13661. if (mesh == null) {
  13662. var rotation = BABYLON.Tmp.Quaternion[0];
  13663. var position = BABYLON.Tmp.Vector3[0];
  13664. var scale = BABYLON.Tmp.Vector3[1];
  13665. child.getWorldMatrix().decompose(scale, rotation, position);
  13666. if (child.rotationQuaternion) {
  13667. child.rotationQuaternion.copyFrom(rotation);
  13668. }
  13669. else {
  13670. rotation.toEulerAnglesToRef(child.rotation);
  13671. }
  13672. child.position.x = position.x;
  13673. child.position.y = position.y;
  13674. child.position.z = position.z;
  13675. }
  13676. else {
  13677. var rotation = BABYLON.Tmp.Quaternion[0];
  13678. var position = BABYLON.Tmp.Vector3[0];
  13679. var scale = BABYLON.Tmp.Vector3[1];
  13680. var m1 = BABYLON.Tmp.Matrix[0];
  13681. var m2 = BABYLON.Tmp.Matrix[1];
  13682. parent.getWorldMatrix().decompose(scale, rotation, position);
  13683. rotation.toRotationMatrix(m1);
  13684. m2.setTranslation(position);
  13685. m2.multiplyToRef(m1, m1);
  13686. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  13687. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13688. m.decompose(scale, rotation, position);
  13689. if (child.rotationQuaternion) {
  13690. child.rotationQuaternion.copyFrom(rotation);
  13691. }
  13692. else {
  13693. rotation.toEulerAnglesToRef(child.rotation);
  13694. }
  13695. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  13696. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13697. m.decompose(scale, rotation, position);
  13698. child.position.x = position.x;
  13699. child.position.y = position.y;
  13700. child.position.z = position.z;
  13701. }
  13702. child.parent = parent;
  13703. return this;
  13704. };
  13705. /**
  13706. * Adds the passed mesh as a child to the current mesh.
  13707. * Returns the AbstractMesh.
  13708. */
  13709. AbstractMesh.prototype.addChild = function (mesh) {
  13710. mesh.setParent(this);
  13711. return this;
  13712. };
  13713. /**
  13714. * Removes the passed mesh from the current mesh children list.
  13715. * Returns the AbstractMesh.
  13716. */
  13717. AbstractMesh.prototype.removeChild = function (mesh) {
  13718. mesh.setParent(null);
  13719. return this;
  13720. };
  13721. /**
  13722. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  13723. * Returns the AbstractMesh.
  13724. */
  13725. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  13726. result.x = this._pivotMatrix.m[12];
  13727. result.y = this._pivotMatrix.m[13];
  13728. result.z = this._pivotMatrix.m[14];
  13729. this.getPivotPointToRef(result);
  13730. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  13731. return this;
  13732. };
  13733. // Facet data
  13734. /**
  13735. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  13736. * Returns the AbstractMesh.
  13737. */
  13738. AbstractMesh.prototype._initFacetData = function () {
  13739. if (!this._facetNormals) {
  13740. this._facetNormals = new Array();
  13741. }
  13742. if (!this._facetPositions) {
  13743. this._facetPositions = new Array();
  13744. }
  13745. if (!this._facetPartitioning) {
  13746. this._facetPartitioning = new Array();
  13747. }
  13748. this._facetNb = this.getIndices().length / 3;
  13749. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  13750. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  13751. for (var f = 0; f < this._facetNb; f++) {
  13752. this._facetNormals[f] = BABYLON.Vector3.Zero();
  13753. this._facetPositions[f] = BABYLON.Vector3.Zero();
  13754. }
  13755. this._facetDataEnabled = true;
  13756. return this;
  13757. };
  13758. /**
  13759. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  13760. * This method can be called within the render loop.
  13761. * 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.
  13762. * Returns the AbstractMesh.
  13763. */
  13764. AbstractMesh.prototype.updateFacetData = function () {
  13765. if (!this._facetDataEnabled) {
  13766. this._initFacetData();
  13767. }
  13768. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13769. var indices = this.getIndices();
  13770. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13771. var bInfo = this.getBoundingInfo();
  13772. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  13773. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  13774. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  13775. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  13776. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  13777. this._subDiv.max = this._partitioningSubdivisions;
  13778. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  13779. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  13780. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  13781. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  13782. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  13783. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  13784. // set the parameters for ComputeNormals()
  13785. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  13786. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  13787. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  13788. this._facetParameters.bInfo = bInfo;
  13789. this._facetParameters.bbSize = this._bbSize;
  13790. this._facetParameters.subDiv = this._subDiv;
  13791. this._facetParameters.ratio = this.partitioningBBoxRatio;
  13792. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  13793. return this;
  13794. };
  13795. /**
  13796. * Returns the facetLocalNormals array.
  13797. * The normals are expressed in the mesh local space.
  13798. */
  13799. AbstractMesh.prototype.getFacetLocalNormals = function () {
  13800. if (!this._facetNormals) {
  13801. this.updateFacetData();
  13802. }
  13803. return this._facetNormals;
  13804. };
  13805. /**
  13806. * Returns the facetLocalPositions array.
  13807. * The facet positions are expressed in the mesh local space.
  13808. */
  13809. AbstractMesh.prototype.getFacetLocalPositions = function () {
  13810. if (!this._facetPositions) {
  13811. this.updateFacetData();
  13812. }
  13813. return this._facetPositions;
  13814. };
  13815. /**
  13816. * Returns the facetLocalPartioning array.
  13817. */
  13818. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  13819. if (!this._facetPartitioning) {
  13820. this.updateFacetData();
  13821. }
  13822. return this._facetPartitioning;
  13823. };
  13824. /**
  13825. * Returns the i-th facet position in the world system.
  13826. * This method allocates a new Vector3 per call.
  13827. */
  13828. AbstractMesh.prototype.getFacetPosition = function (i) {
  13829. var pos = BABYLON.Vector3.Zero();
  13830. this.getFacetPositionToRef(i, pos);
  13831. return pos;
  13832. };
  13833. /**
  13834. * Sets the reference Vector3 with the i-th facet position in the world system.
  13835. * Returns the AbstractMesh.
  13836. */
  13837. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  13838. var localPos = (this.getFacetLocalPositions())[i];
  13839. var world = this.getWorldMatrix();
  13840. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  13841. return this;
  13842. };
  13843. /**
  13844. * Returns the i-th facet normal in the world system.
  13845. * This method allocates a new Vector3 per call.
  13846. */
  13847. AbstractMesh.prototype.getFacetNormal = function (i) {
  13848. var norm = BABYLON.Vector3.Zero();
  13849. this.getFacetNormalToRef(i, norm);
  13850. return norm;
  13851. };
  13852. /**
  13853. * Sets the reference Vector3 with the i-th facet normal in the world system.
  13854. * Returns the AbstractMesh.
  13855. */
  13856. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  13857. var localNorm = (this.getFacetLocalNormals())[i];
  13858. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  13859. return this;
  13860. };
  13861. /**
  13862. * 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).
  13863. */
  13864. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  13865. var bInfo = this.getBoundingInfo();
  13866. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  13867. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  13868. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  13869. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  13870. return null;
  13871. }
  13872. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  13873. };
  13874. /**
  13875. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  13876. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  13877. * 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.
  13878. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13879. * 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.
  13880. */
  13881. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  13882. if (checkFace === void 0) { checkFace = false; }
  13883. if (facing === void 0) { facing = true; }
  13884. var world = this.getWorldMatrix();
  13885. var invMat = BABYLON.Tmp.Matrix[5];
  13886. world.invertToRef(invMat);
  13887. var invVect = BABYLON.Tmp.Vector3[8];
  13888. var closest = null;
  13889. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  13890. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  13891. if (projected) {
  13892. // tranform the local computed projected vector to world coordinates
  13893. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  13894. }
  13895. return closest;
  13896. };
  13897. /**
  13898. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  13899. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  13900. * 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.
  13901. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13902. * 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.
  13903. */
  13904. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  13905. if (checkFace === void 0) { checkFace = false; }
  13906. if (facing === void 0) { facing = true; }
  13907. var closest = null;
  13908. var tmpx = 0.0;
  13909. var tmpy = 0.0;
  13910. var tmpz = 0.0;
  13911. var d = 0.0; // tmp dot facet normal * facet position
  13912. var t0 = 0.0;
  13913. var projx = 0.0;
  13914. var projy = 0.0;
  13915. var projz = 0.0;
  13916. // Get all the facets in the same partitioning block than (x, y, z)
  13917. var facetPositions = this.getFacetLocalPositions();
  13918. var facetNormals = this.getFacetLocalNormals();
  13919. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  13920. if (!facetsInBlock) {
  13921. return null;
  13922. }
  13923. // Get the closest facet to (x, y, z)
  13924. var shortest = Number.MAX_VALUE; // init distance vars
  13925. var tmpDistance = shortest;
  13926. var fib; // current facet in the block
  13927. var norm; // current facet normal
  13928. var p0; // current facet barycenter position
  13929. // loop on all the facets in the current partitioning block
  13930. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  13931. fib = facetsInBlock[idx];
  13932. norm = facetNormals[fib];
  13933. p0 = facetPositions[fib];
  13934. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  13935. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  13936. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  13937. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  13938. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  13939. projx = x + norm.x * t0;
  13940. projy = y + norm.y * t0;
  13941. projz = z + norm.z * t0;
  13942. tmpx = projx - x;
  13943. tmpy = projy - y;
  13944. tmpz = projz - z;
  13945. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  13946. if (tmpDistance < shortest) {
  13947. shortest = tmpDistance;
  13948. closest = fib;
  13949. if (projected) {
  13950. projected.x = projx;
  13951. projected.y = projy;
  13952. projected.z = projz;
  13953. }
  13954. }
  13955. }
  13956. }
  13957. return closest;
  13958. };
  13959. /**
  13960. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  13961. */
  13962. AbstractMesh.prototype.getFacetDataParameters = function () {
  13963. return this._facetParameters;
  13964. };
  13965. /**
  13966. * Disables the feature FacetData and frees the related memory.
  13967. * Returns the AbstractMesh.
  13968. */
  13969. AbstractMesh.prototype.disableFacetData = function () {
  13970. if (this._facetDataEnabled) {
  13971. this._facetDataEnabled = false;
  13972. this._facetPositions = null;
  13973. this._facetNormals = null;
  13974. this._facetPartitioning = null;
  13975. this._facetParameters = null;
  13976. }
  13977. return this;
  13978. };
  13979. /**
  13980. * Creates new normals data for the mesh.
  13981. * @param updatable.
  13982. */
  13983. AbstractMesh.prototype.createNormals = function (updatable) {
  13984. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13985. var indices = this.getIndices();
  13986. var normals;
  13987. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13988. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13989. }
  13990. else {
  13991. normals = [];
  13992. }
  13993. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  13994. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  13995. };
  13996. AbstractMesh.prototype.checkOcclusionQuery = function () {
  13997. var engine = this.getEngine();
  13998. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  13999. this._isOccluded = false;
  14000. return;
  14001. }
  14002. if (this.isOcclusionQueryInProgress) {
  14003. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  14004. if (isOcclusionQueryAvailable) {
  14005. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  14006. this._isOcclusionQueryInProgress = false;
  14007. this._occlusionInternalRetryCounter = 0;
  14008. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  14009. }
  14010. else {
  14011. this._occlusionInternalRetryCounter++;
  14012. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  14013. this._isOcclusionQueryInProgress = false;
  14014. this._occlusionInternalRetryCounter = 0;
  14015. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  14016. // if strict continue the last state of the object.
  14017. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  14018. }
  14019. else {
  14020. return;
  14021. }
  14022. }
  14023. }
  14024. var scene = this.getScene();
  14025. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  14026. if (!this._occlusionQuery) {
  14027. this._occlusionQuery = engine.createQuery();
  14028. }
  14029. engine.beginQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  14030. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  14031. engine.endQuery(this.occlusionQueryAlgorithmType);
  14032. this._isOcclusionQueryInProgress = true;
  14033. };
  14034. // Statics
  14035. AbstractMesh._BILLBOARDMODE_NONE = 0;
  14036. AbstractMesh._BILLBOARDMODE_X = 1;
  14037. AbstractMesh._BILLBOARDMODE_Y = 2;
  14038. AbstractMesh._BILLBOARDMODE_Z = 4;
  14039. AbstractMesh._BILLBOARDMODE_ALL = 7;
  14040. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  14041. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  14042. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  14043. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  14044. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  14045. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  14046. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  14047. return AbstractMesh;
  14048. }(BABYLON.Node));
  14049. BABYLON.AbstractMesh = AbstractMesh;
  14050. })(BABYLON || (BABYLON = {}));
  14051. //# sourceMappingURL=babylon.abstractMesh.js.map
  14052. var BABYLON;
  14053. (function (BABYLON) {
  14054. var Light = (function (_super) {
  14055. __extends(Light, _super);
  14056. /**
  14057. * Creates a Light object in the scene.
  14058. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14059. */
  14060. function Light(name, scene) {
  14061. var _this = _super.call(this, name, scene) || this;
  14062. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  14063. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  14064. _this.intensity = 1.0;
  14065. _this.range = Number.MAX_VALUE;
  14066. /**
  14067. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  14068. * of light.
  14069. */
  14070. _this._photometricScale = 1.0;
  14071. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  14072. _this._radius = 0.00001;
  14073. _this.renderPriority = 0;
  14074. /**
  14075. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  14076. * the current shadow generator.
  14077. */
  14078. _this.shadowEnabled = true;
  14079. _this._excludeWithLayerMask = 0;
  14080. _this._includeOnlyWithLayerMask = 0;
  14081. _this._lightmapMode = 0;
  14082. _this._excludedMeshesIds = new Array();
  14083. _this._includedOnlyMeshesIds = new Array();
  14084. _this.getScene().addLight(_this);
  14085. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  14086. _this._buildUniformLayout();
  14087. _this.includedOnlyMeshes = new Array();
  14088. _this.excludedMeshes = new Array();
  14089. _this._resyncMeshes();
  14090. return _this;
  14091. }
  14092. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  14093. /**
  14094. * If every light affecting the material is in this lightmapMode,
  14095. * material.lightmapTexture adds or multiplies
  14096. * (depends on material.useLightmapAsShadowmap)
  14097. * after every other light calculations.
  14098. */
  14099. get: function () {
  14100. return Light._LIGHTMAP_DEFAULT;
  14101. },
  14102. enumerable: true,
  14103. configurable: true
  14104. });
  14105. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  14106. /**
  14107. * material.lightmapTexture as only diffuse lighting from this light
  14108. * adds pnly specular lighting from this light
  14109. * adds dynamic shadows
  14110. */
  14111. get: function () {
  14112. return Light._LIGHTMAP_SPECULAR;
  14113. },
  14114. enumerable: true,
  14115. configurable: true
  14116. });
  14117. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  14118. /**
  14119. * material.lightmapTexture as only lighting
  14120. * no light calculation from this light
  14121. * only adds dynamic shadows from this light
  14122. */
  14123. get: function () {
  14124. return Light._LIGHTMAP_SHADOWSONLY;
  14125. },
  14126. enumerable: true,
  14127. configurable: true
  14128. });
  14129. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  14130. /**
  14131. * Each light type uses the default quantity according to its type:
  14132. * point/spot lights use luminous intensity
  14133. * directional lights use illuminance
  14134. */
  14135. get: function () {
  14136. return Light._INTENSITYMODE_AUTOMATIC;
  14137. },
  14138. enumerable: true,
  14139. configurable: true
  14140. });
  14141. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  14142. /**
  14143. * lumen (lm)
  14144. */
  14145. get: function () {
  14146. return Light._INTENSITYMODE_LUMINOUSPOWER;
  14147. },
  14148. enumerable: true,
  14149. configurable: true
  14150. });
  14151. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  14152. /**
  14153. * candela (lm/sr)
  14154. */
  14155. get: function () {
  14156. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  14157. },
  14158. enumerable: true,
  14159. configurable: true
  14160. });
  14161. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  14162. /**
  14163. * lux (lm/m^2)
  14164. */
  14165. get: function () {
  14166. return Light._INTENSITYMODE_ILLUMINANCE;
  14167. },
  14168. enumerable: true,
  14169. configurable: true
  14170. });
  14171. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  14172. /**
  14173. * nit (cd/m^2)
  14174. */
  14175. get: function () {
  14176. return Light._INTENSITYMODE_LUMINANCE;
  14177. },
  14178. enumerable: true,
  14179. configurable: true
  14180. });
  14181. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  14182. /**
  14183. * Light type const id of the point light.
  14184. */
  14185. get: function () {
  14186. return Light._LIGHTTYPEID_POINTLIGHT;
  14187. },
  14188. enumerable: true,
  14189. configurable: true
  14190. });
  14191. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  14192. /**
  14193. * Light type const id of the directional light.
  14194. */
  14195. get: function () {
  14196. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  14197. },
  14198. enumerable: true,
  14199. configurable: true
  14200. });
  14201. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  14202. /**
  14203. * Light type const id of the spot light.
  14204. */
  14205. get: function () {
  14206. return Light._LIGHTTYPEID_SPOTLIGHT;
  14207. },
  14208. enumerable: true,
  14209. configurable: true
  14210. });
  14211. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  14212. /**
  14213. * Light type const id of the hemispheric light.
  14214. */
  14215. get: function () {
  14216. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  14217. },
  14218. enumerable: true,
  14219. configurable: true
  14220. });
  14221. Object.defineProperty(Light.prototype, "intensityMode", {
  14222. /**
  14223. * Gets the photometric scale used to interpret the intensity.
  14224. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  14225. */
  14226. get: function () {
  14227. return this._intensityMode;
  14228. },
  14229. /**
  14230. * Sets the photometric scale used to interpret the intensity.
  14231. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  14232. */
  14233. set: function (value) {
  14234. this._intensityMode = value;
  14235. this._computePhotometricScale();
  14236. },
  14237. enumerable: true,
  14238. configurable: true
  14239. });
  14240. ;
  14241. ;
  14242. Object.defineProperty(Light.prototype, "radius", {
  14243. /**
  14244. * Gets the light radius used by PBR Materials to simulate soft area lights.
  14245. */
  14246. get: function () {
  14247. return this._radius;
  14248. },
  14249. /**
  14250. * sets the light radius used by PBR Materials to simulate soft area lights.
  14251. */
  14252. set: function (value) {
  14253. this._radius = value;
  14254. this._computePhotometricScale();
  14255. },
  14256. enumerable: true,
  14257. configurable: true
  14258. });
  14259. ;
  14260. ;
  14261. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  14262. get: function () {
  14263. return this._includedOnlyMeshes;
  14264. },
  14265. set: function (value) {
  14266. this._includedOnlyMeshes = value;
  14267. this._hookArrayForIncludedOnly(value);
  14268. },
  14269. enumerable: true,
  14270. configurable: true
  14271. });
  14272. Object.defineProperty(Light.prototype, "excludedMeshes", {
  14273. get: function () {
  14274. return this._excludedMeshes;
  14275. },
  14276. set: function (value) {
  14277. this._excludedMeshes = value;
  14278. this._hookArrayForExcluded(value);
  14279. },
  14280. enumerable: true,
  14281. configurable: true
  14282. });
  14283. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  14284. get: function () {
  14285. return this._excludeWithLayerMask;
  14286. },
  14287. set: function (value) {
  14288. this._excludeWithLayerMask = value;
  14289. this._resyncMeshes();
  14290. },
  14291. enumerable: true,
  14292. configurable: true
  14293. });
  14294. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  14295. get: function () {
  14296. return this._includeOnlyWithLayerMask;
  14297. },
  14298. set: function (value) {
  14299. this._includeOnlyWithLayerMask = value;
  14300. this._resyncMeshes();
  14301. },
  14302. enumerable: true,
  14303. configurable: true
  14304. });
  14305. Object.defineProperty(Light.prototype, "lightmapMode", {
  14306. get: function () {
  14307. return this._lightmapMode;
  14308. },
  14309. set: function (value) {
  14310. if (this._lightmapMode === value) {
  14311. return;
  14312. }
  14313. this._lightmapMode = value;
  14314. this._markMeshesAsLightDirty();
  14315. },
  14316. enumerable: true,
  14317. configurable: true
  14318. });
  14319. Light.prototype._buildUniformLayout = function () {
  14320. // Overridden
  14321. };
  14322. /**
  14323. * Returns the string "Light".
  14324. */
  14325. Light.prototype.getClassName = function () {
  14326. return "Light";
  14327. };
  14328. /**
  14329. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14330. */
  14331. Light.prototype.toString = function (fullDetails) {
  14332. var ret = "Name: " + this.name;
  14333. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  14334. if (this.animations) {
  14335. for (var i = 0; i < this.animations.length; i++) {
  14336. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14337. }
  14338. }
  14339. if (fullDetails) {
  14340. }
  14341. return ret;
  14342. };
  14343. /**
  14344. * Set the enabled state of this node.
  14345. * @param {boolean} value - the new enabled state
  14346. * @see isEnabled
  14347. */
  14348. Light.prototype.setEnabled = function (value) {
  14349. _super.prototype.setEnabled.call(this, value);
  14350. this._resyncMeshes();
  14351. };
  14352. /**
  14353. * Returns the Light associated shadow generator.
  14354. */
  14355. Light.prototype.getShadowGenerator = function () {
  14356. return this._shadowGenerator;
  14357. };
  14358. /**
  14359. * Returns a Vector3, the absolute light position in the World.
  14360. */
  14361. Light.prototype.getAbsolutePosition = function () {
  14362. return BABYLON.Vector3.Zero();
  14363. };
  14364. Light.prototype.transferToEffect = function (effect, lightIndex) {
  14365. };
  14366. Light.prototype._getWorldMatrix = function () {
  14367. return BABYLON.Matrix.Identity();
  14368. };
  14369. /**
  14370. * Boolean : True if the light will affect the passed mesh.
  14371. */
  14372. Light.prototype.canAffectMesh = function (mesh) {
  14373. if (!mesh) {
  14374. return true;
  14375. }
  14376. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  14377. return false;
  14378. }
  14379. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  14380. return false;
  14381. }
  14382. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  14383. return false;
  14384. }
  14385. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  14386. return false;
  14387. }
  14388. return true;
  14389. };
  14390. /**
  14391. * Returns the light World matrix.
  14392. */
  14393. Light.prototype.getWorldMatrix = function () {
  14394. this._currentRenderId = this.getScene().getRenderId();
  14395. var worldMatrix = this._getWorldMatrix();
  14396. if (this.parent && this.parent.getWorldMatrix) {
  14397. if (!this._parentedWorldMatrix) {
  14398. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  14399. }
  14400. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  14401. this._markSyncedWithParent();
  14402. return this._parentedWorldMatrix;
  14403. }
  14404. return worldMatrix;
  14405. };
  14406. /**
  14407. * Sort function to order lights for rendering.
  14408. * @param a First Light object to compare to second.
  14409. * @param b Second Light object to compare first.
  14410. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  14411. */
  14412. Light.compareLightsPriority = function (a, b) {
  14413. //shadow-casting lights have priority over non-shadow-casting lights
  14414. //the renderPrioirty is a secondary sort criterion
  14415. if (a.shadowEnabled !== b.shadowEnabled) {
  14416. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  14417. }
  14418. return b.renderPriority - a.renderPriority;
  14419. };
  14420. /**
  14421. * Disposes the light.
  14422. */
  14423. Light.prototype.dispose = function () {
  14424. if (this._shadowGenerator) {
  14425. this._shadowGenerator.dispose();
  14426. this._shadowGenerator = null;
  14427. }
  14428. // Animations
  14429. this.getScene().stopAnimation(this);
  14430. // Remove from meshes
  14431. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14432. var mesh = _a[_i];
  14433. mesh._removeLightSource(this);
  14434. }
  14435. this._uniformBuffer.dispose();
  14436. // Remove from scene
  14437. this.getScene().removeLight(this);
  14438. _super.prototype.dispose.call(this);
  14439. };
  14440. /**
  14441. * Returns the light type ID (integer).
  14442. */
  14443. Light.prototype.getTypeID = function () {
  14444. return 0;
  14445. };
  14446. /**
  14447. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  14448. */
  14449. Light.prototype.getScaledIntensity = function () {
  14450. return this._photometricScale * this.intensity;
  14451. };
  14452. /**
  14453. * Returns a new Light object, named "name", from the current one.
  14454. */
  14455. Light.prototype.clone = function (name) {
  14456. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  14457. };
  14458. /**
  14459. * Serializes the current light into a Serialization object.
  14460. * Returns the serialized object.
  14461. */
  14462. Light.prototype.serialize = function () {
  14463. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14464. // Type
  14465. serializationObject.type = this.getTypeID();
  14466. // Parent
  14467. if (this.parent) {
  14468. serializationObject.parentId = this.parent.id;
  14469. }
  14470. // Inclusion / exclusions
  14471. if (this.excludedMeshes.length > 0) {
  14472. serializationObject.excludedMeshesIds = [];
  14473. this.excludedMeshes.forEach(function (mesh) {
  14474. serializationObject.excludedMeshesIds.push(mesh.id);
  14475. });
  14476. }
  14477. if (this.includedOnlyMeshes.length > 0) {
  14478. serializationObject.includedOnlyMeshesIds = [];
  14479. this.includedOnlyMeshes.forEach(function (mesh) {
  14480. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  14481. });
  14482. }
  14483. // Animations
  14484. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14485. serializationObject.ranges = this.serializeAnimationRanges();
  14486. return serializationObject;
  14487. };
  14488. /**
  14489. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  14490. * This new light is named "name" and added to the passed scene.
  14491. */
  14492. Light.GetConstructorFromName = function (type, name, scene) {
  14493. switch (type) {
  14494. case 0:
  14495. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  14496. case 1:
  14497. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  14498. case 2:
  14499. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  14500. case 3:
  14501. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  14502. }
  14503. };
  14504. /**
  14505. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  14506. */
  14507. Light.Parse = function (parsedLight, scene) {
  14508. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  14509. // Inclusion / exclusions
  14510. if (parsedLight.excludedMeshesIds) {
  14511. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  14512. }
  14513. if (parsedLight.includedOnlyMeshesIds) {
  14514. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  14515. }
  14516. // Parent
  14517. if (parsedLight.parentId) {
  14518. light._waitingParentId = parsedLight.parentId;
  14519. }
  14520. // Animations
  14521. if (parsedLight.animations) {
  14522. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  14523. var parsedAnimation = parsedLight.animations[animationIndex];
  14524. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14525. }
  14526. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  14527. }
  14528. if (parsedLight.autoAnimate) {
  14529. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  14530. }
  14531. return light;
  14532. };
  14533. Light.prototype._hookArrayForExcluded = function (array) {
  14534. var _this = this;
  14535. var oldPush = array.push;
  14536. array.push = function () {
  14537. var items = [];
  14538. for (var _i = 0; _i < arguments.length; _i++) {
  14539. items[_i] = arguments[_i];
  14540. }
  14541. var result = oldPush.apply(array, items);
  14542. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  14543. var item = items_1[_a];
  14544. item._resyncLighSource(_this);
  14545. }
  14546. return result;
  14547. };
  14548. var oldSplice = array.splice;
  14549. array.splice = function (index, deleteCount) {
  14550. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14551. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  14552. var item = deleted_1[_i];
  14553. item._resyncLighSource(_this);
  14554. }
  14555. return deleted;
  14556. };
  14557. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  14558. var item = array_1[_i];
  14559. item._resyncLighSource(this);
  14560. }
  14561. };
  14562. Light.prototype._hookArrayForIncludedOnly = function (array) {
  14563. var _this = this;
  14564. var oldPush = array.push;
  14565. array.push = function () {
  14566. var items = [];
  14567. for (var _i = 0; _i < arguments.length; _i++) {
  14568. items[_i] = arguments[_i];
  14569. }
  14570. var result = oldPush.apply(array, items);
  14571. _this._resyncMeshes();
  14572. return result;
  14573. };
  14574. var oldSplice = array.splice;
  14575. array.splice = function (index, deleteCount) {
  14576. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14577. _this._resyncMeshes();
  14578. return deleted;
  14579. };
  14580. this._resyncMeshes();
  14581. };
  14582. Light.prototype._resyncMeshes = function () {
  14583. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14584. var mesh = _a[_i];
  14585. mesh._resyncLighSource(this);
  14586. }
  14587. };
  14588. Light.prototype._markMeshesAsLightDirty = function () {
  14589. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14590. var mesh = _a[_i];
  14591. if (mesh._lightSources.indexOf(this) !== -1) {
  14592. mesh._markSubMeshesAsLightDirty();
  14593. }
  14594. }
  14595. };
  14596. /**
  14597. * Recomputes the cached photometric scale if needed.
  14598. */
  14599. Light.prototype._computePhotometricScale = function () {
  14600. this._photometricScale = this._getPhotometricScale();
  14601. this.getScene().resetCachedMaterial();
  14602. };
  14603. /**
  14604. * Returns the Photometric Scale according to the light type and intensity mode.
  14605. */
  14606. Light.prototype._getPhotometricScale = function () {
  14607. var photometricScale = 0.0;
  14608. var lightTypeID = this.getTypeID();
  14609. //get photometric mode
  14610. var photometricMode = this.intensityMode;
  14611. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  14612. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  14613. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  14614. }
  14615. else {
  14616. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  14617. }
  14618. }
  14619. //compute photometric scale
  14620. switch (lightTypeID) {
  14621. case Light.LIGHTTYPEID_POINTLIGHT:
  14622. case Light.LIGHTTYPEID_SPOTLIGHT:
  14623. switch (photometricMode) {
  14624. case Light.INTENSITYMODE_LUMINOUSPOWER:
  14625. photometricScale = 1.0 / (4.0 * Math.PI);
  14626. break;
  14627. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  14628. photometricScale = 1.0;
  14629. break;
  14630. case Light.INTENSITYMODE_LUMINANCE:
  14631. photometricScale = this.radius * this.radius;
  14632. break;
  14633. }
  14634. break;
  14635. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  14636. switch (photometricMode) {
  14637. case Light.INTENSITYMODE_ILLUMINANCE:
  14638. photometricScale = 1.0;
  14639. break;
  14640. case Light.INTENSITYMODE_LUMINANCE:
  14641. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  14642. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  14643. var apexAngleRadians = this.radius;
  14644. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  14645. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  14646. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  14647. photometricScale = solidAngle;
  14648. break;
  14649. }
  14650. break;
  14651. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  14652. // No fall off in hemisperic light.
  14653. photometricScale = 1.0;
  14654. break;
  14655. }
  14656. return photometricScale;
  14657. };
  14658. Light.prototype._reorderLightsInScene = function () {
  14659. var scene = this.getScene();
  14660. if (this.renderPriority != 0) {
  14661. scene.requireLightSorting = true;
  14662. }
  14663. this.getScene().sortLightsByPriority();
  14664. };
  14665. //lightmapMode Consts
  14666. Light._LIGHTMAP_DEFAULT = 0;
  14667. Light._LIGHTMAP_SPECULAR = 1;
  14668. Light._LIGHTMAP_SHADOWSONLY = 2;
  14669. // Intensity Mode Consts
  14670. Light._INTENSITYMODE_AUTOMATIC = 0;
  14671. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  14672. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  14673. Light._INTENSITYMODE_ILLUMINANCE = 3;
  14674. Light._INTENSITYMODE_LUMINANCE = 4;
  14675. // Light types ids const.
  14676. Light._LIGHTTYPEID_POINTLIGHT = 0;
  14677. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  14678. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  14679. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  14680. __decorate([
  14681. BABYLON.serializeAsColor3()
  14682. ], Light.prototype, "diffuse", void 0);
  14683. __decorate([
  14684. BABYLON.serializeAsColor3()
  14685. ], Light.prototype, "specular", void 0);
  14686. __decorate([
  14687. BABYLON.serialize()
  14688. ], Light.prototype, "intensity", void 0);
  14689. __decorate([
  14690. BABYLON.serialize()
  14691. ], Light.prototype, "range", void 0);
  14692. __decorate([
  14693. BABYLON.serialize()
  14694. ], Light.prototype, "intensityMode", null);
  14695. __decorate([
  14696. BABYLON.serialize()
  14697. ], Light.prototype, "radius", null);
  14698. __decorate([
  14699. BABYLON.serialize()
  14700. ], Light.prototype, "_renderPriority", void 0);
  14701. __decorate([
  14702. BABYLON.expandToProperty("_reorderLightsInScene")
  14703. ], Light.prototype, "renderPriority", void 0);
  14704. __decorate([
  14705. BABYLON.serialize()
  14706. ], Light.prototype, "shadowEnabled", void 0);
  14707. __decorate([
  14708. BABYLON.serialize("excludeWithLayerMask")
  14709. ], Light.prototype, "_excludeWithLayerMask", void 0);
  14710. __decorate([
  14711. BABYLON.serialize("includeOnlyWithLayerMask")
  14712. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  14713. __decorate([
  14714. BABYLON.serialize("lightmapMode")
  14715. ], Light.prototype, "_lightmapMode", void 0);
  14716. return Light;
  14717. }(BABYLON.Node));
  14718. BABYLON.Light = Light;
  14719. })(BABYLON || (BABYLON = {}));
  14720. //# sourceMappingURL=babylon.light.js.map
  14721. var BABYLON;
  14722. (function (BABYLON) {
  14723. var Camera = (function (_super) {
  14724. __extends(Camera, _super);
  14725. function Camera(name, position, scene) {
  14726. var _this = _super.call(this, name, scene) || this;
  14727. _this.upVector = BABYLON.Vector3.Up();
  14728. _this.orthoLeft = null;
  14729. _this.orthoRight = null;
  14730. _this.orthoBottom = null;
  14731. _this.orthoTop = null;
  14732. _this.fov = 0.8;
  14733. _this.minZ = 1;
  14734. _this.maxZ = 10000.0;
  14735. _this.inertia = 0.9;
  14736. _this.mode = Camera.PERSPECTIVE_CAMERA;
  14737. _this.isIntermediate = false;
  14738. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  14739. _this.layerMask = 0x0FFFFFFF;
  14740. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  14741. // Camera rig members
  14742. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  14743. _this._rigCameras = new Array();
  14744. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  14745. _this.customRenderTargets = new Array();
  14746. // Observables
  14747. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  14748. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  14749. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  14750. // Cache
  14751. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  14752. _this._projectionMatrix = new BABYLON.Matrix();
  14753. _this._doNotComputeProjectionMatrix = false;
  14754. _this._postProcesses = new Array();
  14755. _this._transformMatrix = BABYLON.Matrix.Zero();
  14756. _this._activeMeshes = new BABYLON.SmartArray(256);
  14757. _this._globalPosition = BABYLON.Vector3.Zero();
  14758. _this._refreshFrustumPlanes = true;
  14759. _this.getScene().addCamera(_this);
  14760. if (!_this.getScene().activeCamera) {
  14761. _this.getScene().activeCamera = _this;
  14762. }
  14763. _this.position = position;
  14764. return _this;
  14765. }
  14766. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  14767. get: function () {
  14768. return Camera._PERSPECTIVE_CAMERA;
  14769. },
  14770. enumerable: true,
  14771. configurable: true
  14772. });
  14773. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  14774. get: function () {
  14775. return Camera._ORTHOGRAPHIC_CAMERA;
  14776. },
  14777. enumerable: true,
  14778. configurable: true
  14779. });
  14780. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  14781. get: function () {
  14782. return Camera._FOVMODE_VERTICAL_FIXED;
  14783. },
  14784. enumerable: true,
  14785. configurable: true
  14786. });
  14787. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  14788. get: function () {
  14789. return Camera._FOVMODE_HORIZONTAL_FIXED;
  14790. },
  14791. enumerable: true,
  14792. configurable: true
  14793. });
  14794. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  14795. get: function () {
  14796. return Camera._RIG_MODE_NONE;
  14797. },
  14798. enumerable: true,
  14799. configurable: true
  14800. });
  14801. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  14802. get: function () {
  14803. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  14804. },
  14805. enumerable: true,
  14806. configurable: true
  14807. });
  14808. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  14809. get: function () {
  14810. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  14811. },
  14812. enumerable: true,
  14813. configurable: true
  14814. });
  14815. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  14816. get: function () {
  14817. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  14818. },
  14819. enumerable: true,
  14820. configurable: true
  14821. });
  14822. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  14823. get: function () {
  14824. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  14825. },
  14826. enumerable: true,
  14827. configurable: true
  14828. });
  14829. Object.defineProperty(Camera, "RIG_MODE_VR", {
  14830. get: function () {
  14831. return Camera._RIG_MODE_VR;
  14832. },
  14833. enumerable: true,
  14834. configurable: true
  14835. });
  14836. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  14837. get: function () {
  14838. return Camera._RIG_MODE_WEBVR;
  14839. },
  14840. enumerable: true,
  14841. configurable: true
  14842. });
  14843. /**
  14844. * Store current camera state (fov, position, etc..)
  14845. */
  14846. Camera.prototype.storeState = function () {
  14847. this._stateStored = true;
  14848. this._storedFov = this.fov;
  14849. return this;
  14850. };
  14851. /**
  14852. * Restored camera state. You must call storeState() first
  14853. */
  14854. Camera.prototype.restoreState = function () {
  14855. if (!this._stateStored) {
  14856. return false;
  14857. }
  14858. this.fov = this._storedFov;
  14859. return true;
  14860. };
  14861. Camera.prototype.getClassName = function () {
  14862. return "Camera";
  14863. };
  14864. /**
  14865. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14866. */
  14867. Camera.prototype.toString = function (fullDetails) {
  14868. var ret = "Name: " + this.name;
  14869. ret += ", type: " + this.getClassName();
  14870. if (this.animations) {
  14871. for (var i = 0; i < this.animations.length; i++) {
  14872. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14873. }
  14874. }
  14875. if (fullDetails) {
  14876. }
  14877. return ret;
  14878. };
  14879. Object.defineProperty(Camera.prototype, "globalPosition", {
  14880. get: function () {
  14881. return this._globalPosition;
  14882. },
  14883. enumerable: true,
  14884. configurable: true
  14885. });
  14886. Camera.prototype.getActiveMeshes = function () {
  14887. return this._activeMeshes;
  14888. };
  14889. Camera.prototype.isActiveMesh = function (mesh) {
  14890. return (this._activeMeshes.indexOf(mesh) !== -1);
  14891. };
  14892. //Cache
  14893. Camera.prototype._initCache = function () {
  14894. _super.prototype._initCache.call(this);
  14895. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14896. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14897. this._cache.mode = undefined;
  14898. this._cache.minZ = undefined;
  14899. this._cache.maxZ = undefined;
  14900. this._cache.fov = undefined;
  14901. this._cache.fovMode = undefined;
  14902. this._cache.aspectRatio = undefined;
  14903. this._cache.orthoLeft = undefined;
  14904. this._cache.orthoRight = undefined;
  14905. this._cache.orthoBottom = undefined;
  14906. this._cache.orthoTop = undefined;
  14907. this._cache.renderWidth = undefined;
  14908. this._cache.renderHeight = undefined;
  14909. };
  14910. Camera.prototype._updateCache = function (ignoreParentClass) {
  14911. if (!ignoreParentClass) {
  14912. _super.prototype._updateCache.call(this);
  14913. }
  14914. var engine = this.getEngine();
  14915. this._cache.position.copyFrom(this.position);
  14916. this._cache.upVector.copyFrom(this.upVector);
  14917. this._cache.mode = this.mode;
  14918. this._cache.minZ = this.minZ;
  14919. this._cache.maxZ = this.maxZ;
  14920. this._cache.fov = this.fov;
  14921. this._cache.fovMode = this.fovMode;
  14922. this._cache.aspectRatio = engine.getAspectRatio(this);
  14923. this._cache.orthoLeft = this.orthoLeft;
  14924. this._cache.orthoRight = this.orthoRight;
  14925. this._cache.orthoBottom = this.orthoBottom;
  14926. this._cache.orthoTop = this.orthoTop;
  14927. this._cache.renderWidth = engine.getRenderWidth();
  14928. this._cache.renderHeight = engine.getRenderHeight();
  14929. };
  14930. Camera.prototype._updateFromScene = function () {
  14931. this.updateCache();
  14932. this.update();
  14933. };
  14934. // Synchronized
  14935. Camera.prototype._isSynchronized = function () {
  14936. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  14937. };
  14938. Camera.prototype._isSynchronizedViewMatrix = function () {
  14939. if (!_super.prototype._isSynchronized.call(this))
  14940. return false;
  14941. return this._cache.position.equals(this.position)
  14942. && this._cache.upVector.equals(this.upVector)
  14943. && this.isSynchronizedWithParent();
  14944. };
  14945. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  14946. var check = this._cache.mode === this.mode
  14947. && this._cache.minZ === this.minZ
  14948. && this._cache.maxZ === this.maxZ;
  14949. if (!check) {
  14950. return false;
  14951. }
  14952. var engine = this.getEngine();
  14953. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14954. check = this._cache.fov === this.fov
  14955. && this._cache.fovMode === this.fovMode
  14956. && this._cache.aspectRatio === engine.getAspectRatio(this);
  14957. }
  14958. else {
  14959. check = this._cache.orthoLeft === this.orthoLeft
  14960. && this._cache.orthoRight === this.orthoRight
  14961. && this._cache.orthoBottom === this.orthoBottom
  14962. && this._cache.orthoTop === this.orthoTop
  14963. && this._cache.renderWidth === engine.getRenderWidth()
  14964. && this._cache.renderHeight === engine.getRenderHeight();
  14965. }
  14966. return check;
  14967. };
  14968. // Controls
  14969. Camera.prototype.attachControl = function (element, noPreventDefault) {
  14970. };
  14971. Camera.prototype.detachControl = function (element) {
  14972. };
  14973. Camera.prototype.update = function () {
  14974. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14975. this._updateRigCameras();
  14976. }
  14977. this._checkInputs();
  14978. };
  14979. Camera.prototype._checkInputs = function () {
  14980. this.onAfterCheckInputsObservable.notifyObservers(this);
  14981. };
  14982. Object.defineProperty(Camera.prototype, "rigCameras", {
  14983. get: function () {
  14984. return this._rigCameras;
  14985. },
  14986. enumerable: true,
  14987. configurable: true
  14988. });
  14989. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  14990. get: function () {
  14991. return this._rigPostProcess;
  14992. },
  14993. enumerable: true,
  14994. configurable: true
  14995. });
  14996. Camera.prototype._cascadePostProcessesToRigCams = function () {
  14997. // invalidate framebuffer
  14998. if (this._postProcesses.length > 0) {
  14999. this._postProcesses[0].markTextureDirty();
  15000. }
  15001. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  15002. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  15003. var cam = this._rigCameras[i];
  15004. var rigPostProcess = cam._rigPostProcess;
  15005. // for VR rig, there does not have to be a post process
  15006. if (rigPostProcess) {
  15007. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  15008. if (isPass) {
  15009. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  15010. cam.isIntermediate = this._postProcesses.length === 0;
  15011. }
  15012. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  15013. rigPostProcess.markTextureDirty();
  15014. }
  15015. else {
  15016. cam._postProcesses = this._postProcesses.slice(0);
  15017. }
  15018. }
  15019. };
  15020. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  15021. if (insertAt === void 0) { insertAt = null; }
  15022. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  15023. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  15024. return 0;
  15025. }
  15026. if (insertAt == null || insertAt < 0) {
  15027. this._postProcesses.push(postProcess);
  15028. }
  15029. else {
  15030. this._postProcesses.splice(insertAt, 0, postProcess);
  15031. }
  15032. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15033. return this._postProcesses.indexOf(postProcess);
  15034. };
  15035. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  15036. if (atIndices === void 0) { atIndices = null; }
  15037. var result = [];
  15038. var i;
  15039. var index;
  15040. if (!atIndices) {
  15041. var idx = this._postProcesses.indexOf(postProcess);
  15042. if (idx !== -1) {
  15043. this._postProcesses.splice(idx, 1);
  15044. }
  15045. }
  15046. else {
  15047. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  15048. // iterate descending, so can just splice as we go
  15049. for (i = atIndices.length - 1; i >= 0; i--) {
  15050. if (this._postProcesses[atIndices[i]] !== postProcess) {
  15051. result.push(i);
  15052. continue;
  15053. }
  15054. index = atIndices[i];
  15055. this._postProcesses.splice(index, 1);
  15056. }
  15057. }
  15058. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15059. return result;
  15060. };
  15061. Camera.prototype.getWorldMatrix = function () {
  15062. if (!this._worldMatrix) {
  15063. this._worldMatrix = BABYLON.Matrix.Identity();
  15064. }
  15065. var viewMatrix = this.getViewMatrix();
  15066. viewMatrix.invertToRef(this._worldMatrix);
  15067. return this._worldMatrix;
  15068. };
  15069. Camera.prototype._getViewMatrix = function () {
  15070. return BABYLON.Matrix.Identity();
  15071. };
  15072. Camera.prototype.getViewMatrix = function (force) {
  15073. if (!force && this._isSynchronizedViewMatrix()) {
  15074. return this._computedViewMatrix;
  15075. }
  15076. this._computedViewMatrix = this._getViewMatrix();
  15077. this._currentRenderId = this.getScene().getRenderId();
  15078. this._refreshFrustumPlanes = true;
  15079. if (!this.parent || !this.parent.getWorldMatrix) {
  15080. this._globalPosition.copyFrom(this.position);
  15081. }
  15082. else {
  15083. if (!this._worldMatrix) {
  15084. this._worldMatrix = BABYLON.Matrix.Identity();
  15085. }
  15086. this._computedViewMatrix.invertToRef(this._worldMatrix);
  15087. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  15088. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  15089. this._computedViewMatrix.invert();
  15090. this._markSyncedWithParent();
  15091. }
  15092. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  15093. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  15094. }
  15095. this.onViewMatrixChangedObservable.notifyObservers(this);
  15096. return this._computedViewMatrix;
  15097. };
  15098. Camera.prototype.freezeProjectionMatrix = function (projection) {
  15099. this._doNotComputeProjectionMatrix = true;
  15100. if (projection !== undefined) {
  15101. this._projectionMatrix = projection;
  15102. }
  15103. };
  15104. ;
  15105. Camera.prototype.unfreezeProjectionMatrix = function () {
  15106. this._doNotComputeProjectionMatrix = false;
  15107. };
  15108. ;
  15109. Camera.prototype.getProjectionMatrix = function (force) {
  15110. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  15111. return this._projectionMatrix;
  15112. }
  15113. this._refreshFrustumPlanes = true;
  15114. var engine = this.getEngine();
  15115. var scene = this.getScene();
  15116. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15117. if (this.minZ <= 0) {
  15118. this.minZ = 0.1;
  15119. }
  15120. if (scene.useRightHandedSystem) {
  15121. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15122. }
  15123. else {
  15124. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15125. }
  15126. }
  15127. else {
  15128. var halfWidth = engine.getRenderWidth() / 2.0;
  15129. var halfHeight = engine.getRenderHeight() / 2.0;
  15130. if (scene.useRightHandedSystem) {
  15131. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15132. }
  15133. else {
  15134. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15135. }
  15136. }
  15137. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  15138. return this._projectionMatrix;
  15139. };
  15140. Camera.prototype.getTranformationMatrix = function () {
  15141. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15142. return this._transformMatrix;
  15143. };
  15144. Camera.prototype.updateFrustumPlanes = function () {
  15145. if (!this._refreshFrustumPlanes) {
  15146. return;
  15147. }
  15148. this.getTranformationMatrix();
  15149. if (!this._frustumPlanes) {
  15150. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15151. }
  15152. else {
  15153. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15154. }
  15155. this._refreshFrustumPlanes = false;
  15156. };
  15157. Camera.prototype.isInFrustum = function (target) {
  15158. this.updateFrustumPlanes();
  15159. return target.isInFrustum(this._frustumPlanes);
  15160. };
  15161. Camera.prototype.isCompletelyInFrustum = function (target) {
  15162. this.updateFrustumPlanes();
  15163. return target.isCompletelyInFrustum(this._frustumPlanes);
  15164. };
  15165. Camera.prototype.getForwardRay = function (length, transform, origin) {
  15166. if (length === void 0) { length = 100; }
  15167. if (!transform) {
  15168. transform = this.getWorldMatrix();
  15169. }
  15170. if (!origin) {
  15171. origin = this.position;
  15172. }
  15173. var forward = new BABYLON.Vector3(0, 0, 1);
  15174. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  15175. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  15176. return new BABYLON.Ray(origin, direction, length);
  15177. };
  15178. Camera.prototype.dispose = function () {
  15179. // Observables
  15180. this.onViewMatrixChangedObservable.clear();
  15181. this.onProjectionMatrixChangedObservable.clear();
  15182. this.onAfterCheckInputsObservable.clear();
  15183. // Inputs
  15184. if (this.inputs) {
  15185. this.inputs.clear();
  15186. }
  15187. // Animations
  15188. this.getScene().stopAnimation(this);
  15189. // Remove from scene
  15190. this.getScene().removeCamera(this);
  15191. while (this._rigCameras.length > 0) {
  15192. this._rigCameras.pop().dispose();
  15193. }
  15194. // Postprocesses
  15195. var i = this._postProcesses.length;
  15196. while (--i >= 0) {
  15197. this._postProcesses[i].dispose(this);
  15198. }
  15199. // Render targets
  15200. var i = this.customRenderTargets.length;
  15201. while (--i >= 0) {
  15202. this.customRenderTargets[i].dispose();
  15203. }
  15204. this.customRenderTargets = [];
  15205. // Active Meshes
  15206. this._activeMeshes.dispose();
  15207. _super.prototype.dispose.call(this);
  15208. };
  15209. Object.defineProperty(Camera.prototype, "leftCamera", {
  15210. // ---- Camera rigs section ----
  15211. get: function () {
  15212. if (this._rigCameras.length < 1) {
  15213. return undefined;
  15214. }
  15215. return this._rigCameras[0];
  15216. },
  15217. enumerable: true,
  15218. configurable: true
  15219. });
  15220. Object.defineProperty(Camera.prototype, "rightCamera", {
  15221. get: function () {
  15222. if (this._rigCameras.length < 2) {
  15223. return undefined;
  15224. }
  15225. return this._rigCameras[1];
  15226. },
  15227. enumerable: true,
  15228. configurable: true
  15229. });
  15230. Camera.prototype.getLeftTarget = function () {
  15231. if (this._rigCameras.length < 1) {
  15232. return undefined;
  15233. }
  15234. return this._rigCameras[0].getTarget();
  15235. };
  15236. Camera.prototype.getRightTarget = function () {
  15237. if (this._rigCameras.length < 2) {
  15238. return undefined;
  15239. }
  15240. return this._rigCameras[1].getTarget();
  15241. };
  15242. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  15243. while (this._rigCameras.length > 0) {
  15244. this._rigCameras.pop().dispose();
  15245. }
  15246. this.cameraRigMode = mode;
  15247. this._cameraRigParams = {};
  15248. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  15249. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  15250. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  15251. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  15252. // create the rig cameras, unless none
  15253. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15254. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  15255. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  15256. }
  15257. switch (this.cameraRigMode) {
  15258. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15259. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15260. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  15261. break;
  15262. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15263. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15264. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15265. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15266. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15267. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  15268. break;
  15269. case Camera.RIG_MODE_VR:
  15270. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  15271. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  15272. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15273. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15274. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  15275. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  15276. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  15277. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  15278. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15279. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15280. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  15281. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  15282. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  15283. if (metrics.compensateDistortion) {
  15284. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  15285. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  15286. }
  15287. break;
  15288. case Camera.RIG_MODE_WEBVR:
  15289. if (rigParams.vrDisplay) {
  15290. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  15291. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  15292. //Left eye
  15293. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15294. this._rigCameras[0].setCameraRigParameter("left", true);
  15295. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  15296. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  15297. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  15298. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  15299. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15300. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15301. this._rigCameras[0].parent = this;
  15302. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  15303. //Right eye
  15304. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15305. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  15306. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  15307. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  15308. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  15309. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15310. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15311. this._rigCameras[1].parent = this;
  15312. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  15313. }
  15314. break;
  15315. }
  15316. this._cascadePostProcessesToRigCams();
  15317. this.
  15318. update();
  15319. };
  15320. Camera.prototype._getVRProjectionMatrix = function () {
  15321. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  15322. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  15323. return this._projectionMatrix;
  15324. };
  15325. Camera.prototype._updateCameraRotationMatrix = function () {
  15326. //Here for WebVR
  15327. };
  15328. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  15329. //Here for WebVR
  15330. };
  15331. /**
  15332. * This function MUST be overwritten by the different WebVR cameras available.
  15333. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  15334. */
  15335. Camera.prototype._getWebVRProjectionMatrix = function () {
  15336. return BABYLON.Matrix.Identity();
  15337. };
  15338. /**
  15339. * This function MUST be overwritten by the different WebVR cameras available.
  15340. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  15341. */
  15342. Camera.prototype._getWebVRViewMatrix = function () {
  15343. return BABYLON.Matrix.Identity();
  15344. };
  15345. Camera.prototype.setCameraRigParameter = function (name, value) {
  15346. if (!this._cameraRigParams) {
  15347. this._cameraRigParams = {};
  15348. }
  15349. this._cameraRigParams[name] = value;
  15350. //provisionnally:
  15351. if (name === "interaxialDistance") {
  15352. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  15353. }
  15354. };
  15355. /**
  15356. * needs to be overridden by children so sub has required properties to be copied
  15357. */
  15358. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  15359. return null;
  15360. };
  15361. /**
  15362. * May need to be overridden by children
  15363. */
  15364. Camera.prototype._updateRigCameras = function () {
  15365. for (var i = 0; i < this._rigCameras.length; i++) {
  15366. this._rigCameras[i].minZ = this.minZ;
  15367. this._rigCameras[i].maxZ = this.maxZ;
  15368. this._rigCameras[i].fov = this.fov;
  15369. }
  15370. // only update viewport when ANAGLYPH
  15371. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  15372. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  15373. }
  15374. };
  15375. Camera.prototype._setupInputs = function () {
  15376. };
  15377. Camera.prototype.serialize = function () {
  15378. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  15379. // Type
  15380. serializationObject.type = this.getClassName();
  15381. // Parent
  15382. if (this.parent) {
  15383. serializationObject.parentId = this.parent.id;
  15384. }
  15385. if (this.inputs) {
  15386. this.inputs.serialize(serializationObject);
  15387. }
  15388. // Animations
  15389. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  15390. serializationObject.ranges = this.serializeAnimationRanges();
  15391. return serializationObject;
  15392. };
  15393. Camera.prototype.clone = function (name) {
  15394. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  15395. };
  15396. Camera.prototype.getDirection = function (localAxis) {
  15397. var result = BABYLON.Vector3.Zero();
  15398. this.getDirectionToRef(localAxis, result);
  15399. return result;
  15400. };
  15401. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  15402. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  15403. };
  15404. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  15405. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  15406. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  15407. switch (type) {
  15408. case "ArcRotateCamera":
  15409. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  15410. case "DeviceOrientationCamera":
  15411. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  15412. case "FollowCamera":
  15413. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  15414. case "ArcFollowCamera":
  15415. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  15416. case "GamepadCamera":
  15417. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15418. case "TouchCamera":
  15419. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  15420. case "VirtualJoysticksCamera":
  15421. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  15422. case "WebVRFreeCamera":
  15423. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15424. case "WebVRGamepadCamera":
  15425. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15426. case "VRDeviceOrientationFreeCamera":
  15427. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15428. case "VRDeviceOrientationGamepadCamera":
  15429. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15430. case "AnaglyphArcRotateCamera":
  15431. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15432. case "AnaglyphFreeCamera":
  15433. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15434. case "AnaglyphGamepadCamera":
  15435. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15436. case "AnaglyphUniversalCamera":
  15437. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15438. case "StereoscopicArcRotateCamera":
  15439. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15440. case "StereoscopicFreeCamera":
  15441. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15442. case "StereoscopicGamepadCamera":
  15443. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15444. case "StereoscopicUniversalCamera":
  15445. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15446. case "FreeCamera":// Forcing Universal here
  15447. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15448. default:// Universal Camera is the default value
  15449. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15450. }
  15451. };
  15452. Camera.Parse = function (parsedCamera, scene) {
  15453. var type = parsedCamera.type;
  15454. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  15455. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  15456. // Parent
  15457. if (parsedCamera.parentId) {
  15458. camera._waitingParentId = parsedCamera.parentId;
  15459. }
  15460. //If camera has an input manager, let it parse inputs settings
  15461. if (camera.inputs) {
  15462. camera.inputs.parse(parsedCamera);
  15463. camera._setupInputs();
  15464. }
  15465. if (camera.setPosition) {
  15466. camera.position.copyFromFloats(0, 0, 0);
  15467. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  15468. }
  15469. // Target
  15470. if (parsedCamera.target) {
  15471. if (camera.setTarget) {
  15472. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  15473. }
  15474. }
  15475. // Apply 3d rig, when found
  15476. if (parsedCamera.cameraRigMode) {
  15477. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  15478. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  15479. }
  15480. // Animations
  15481. if (parsedCamera.animations) {
  15482. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  15483. var parsedAnimation = parsedCamera.animations[animationIndex];
  15484. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15485. }
  15486. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  15487. }
  15488. if (parsedCamera.autoAnimate) {
  15489. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  15490. }
  15491. return camera;
  15492. };
  15493. // Statics
  15494. Camera._PERSPECTIVE_CAMERA = 0;
  15495. Camera._ORTHOGRAPHIC_CAMERA = 1;
  15496. Camera._FOVMODE_VERTICAL_FIXED = 0;
  15497. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  15498. Camera._RIG_MODE_NONE = 0;
  15499. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  15500. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  15501. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  15502. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  15503. Camera._RIG_MODE_VR = 20;
  15504. Camera._RIG_MODE_WEBVR = 21;
  15505. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  15506. __decorate([
  15507. BABYLON.serializeAsVector3()
  15508. ], Camera.prototype, "position", void 0);
  15509. __decorate([
  15510. BABYLON.serializeAsVector3()
  15511. ], Camera.prototype, "upVector", void 0);
  15512. __decorate([
  15513. BABYLON.serialize()
  15514. ], Camera.prototype, "orthoLeft", void 0);
  15515. __decorate([
  15516. BABYLON.serialize()
  15517. ], Camera.prototype, "orthoRight", void 0);
  15518. __decorate([
  15519. BABYLON.serialize()
  15520. ], Camera.prototype, "orthoBottom", void 0);
  15521. __decorate([
  15522. BABYLON.serialize()
  15523. ], Camera.prototype, "orthoTop", void 0);
  15524. __decorate([
  15525. BABYLON.serialize()
  15526. ], Camera.prototype, "fov", void 0);
  15527. __decorate([
  15528. BABYLON.serialize()
  15529. ], Camera.prototype, "minZ", void 0);
  15530. __decorate([
  15531. BABYLON.serialize()
  15532. ], Camera.prototype, "maxZ", void 0);
  15533. __decorate([
  15534. BABYLON.serialize()
  15535. ], Camera.prototype, "inertia", void 0);
  15536. __decorate([
  15537. BABYLON.serialize()
  15538. ], Camera.prototype, "mode", void 0);
  15539. __decorate([
  15540. BABYLON.serialize()
  15541. ], Camera.prototype, "layerMask", void 0);
  15542. __decorate([
  15543. BABYLON.serialize()
  15544. ], Camera.prototype, "fovMode", void 0);
  15545. __decorate([
  15546. BABYLON.serialize()
  15547. ], Camera.prototype, "cameraRigMode", void 0);
  15548. __decorate([
  15549. BABYLON.serialize()
  15550. ], Camera.prototype, "interaxialDistance", void 0);
  15551. __decorate([
  15552. BABYLON.serialize()
  15553. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  15554. return Camera;
  15555. }(BABYLON.Node));
  15556. BABYLON.Camera = Camera;
  15557. })(BABYLON || (BABYLON = {}));
  15558. //# sourceMappingURL=babylon.camera.js.map
  15559. var BABYLON;
  15560. (function (BABYLON) {
  15561. var RenderingManager = (function () {
  15562. function RenderingManager(scene) {
  15563. this._renderingGroups = new Array();
  15564. this._autoClearDepthStencil = {};
  15565. this._customOpaqueSortCompareFn = {};
  15566. this._customAlphaTestSortCompareFn = {};
  15567. this._customTransparentSortCompareFn = {};
  15568. this._renderinGroupInfo = null;
  15569. this._scene = scene;
  15570. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  15571. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  15572. }
  15573. }
  15574. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  15575. if (depth === void 0) { depth = true; }
  15576. if (stencil === void 0) { stencil = true; }
  15577. if (this._depthStencilBufferAlreadyCleaned) {
  15578. return;
  15579. }
  15580. this._scene.getEngine().clear(null, false, depth, stencil);
  15581. this._depthStencilBufferAlreadyCleaned = true;
  15582. };
  15583. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  15584. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  15585. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  15586. var info = null;
  15587. if (observable) {
  15588. if (!this._renderinGroupInfo) {
  15589. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  15590. }
  15591. info = this._renderinGroupInfo;
  15592. info.scene = this._scene;
  15593. info.camera = this._scene.activeCamera;
  15594. }
  15595. // Dispatch sprites
  15596. if (renderSprites) {
  15597. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  15598. var manager = this._scene.spriteManagers[index];
  15599. this.dispatchSprites(manager);
  15600. }
  15601. }
  15602. // Render
  15603. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15604. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  15605. var renderingGroup = this._renderingGroups[index];
  15606. if (!renderingGroup && !observable)
  15607. continue;
  15608. this._currentIndex = index;
  15609. var renderingGroupMask = 0;
  15610. // Fire PRECLEAR stage
  15611. if (observable) {
  15612. renderingGroupMask = Math.pow(2, index);
  15613. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  15614. info.renderingGroupId = index;
  15615. observable.notifyObservers(info, renderingGroupMask);
  15616. }
  15617. // Clear depth/stencil if needed
  15618. if (RenderingManager.AUTOCLEAR) {
  15619. var autoClear = this._autoClearDepthStencil[index];
  15620. if (autoClear && autoClear.autoClear) {
  15621. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  15622. }
  15623. }
  15624. if (observable) {
  15625. // Fire PREOPAQUE stage
  15626. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  15627. observable.notifyObservers(info, renderingGroupMask);
  15628. // Fire PRETRANSPARENT stage
  15629. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  15630. observable.notifyObservers(info, renderingGroupMask);
  15631. }
  15632. if (renderingGroup)
  15633. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  15634. // Fire POSTTRANSPARENT stage
  15635. if (observable) {
  15636. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  15637. observable.notifyObservers(info, renderingGroupMask);
  15638. }
  15639. }
  15640. };
  15641. RenderingManager.prototype.reset = function () {
  15642. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15643. var renderingGroup = this._renderingGroups[index];
  15644. if (renderingGroup) {
  15645. renderingGroup.prepare();
  15646. }
  15647. }
  15648. };
  15649. RenderingManager.prototype.dispose = function () {
  15650. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15651. var renderingGroup = this._renderingGroups[index];
  15652. if (renderingGroup) {
  15653. renderingGroup.dispose();
  15654. }
  15655. }
  15656. this._renderingGroups.length = 0;
  15657. };
  15658. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  15659. if (!this._renderingGroups[renderingGroupId]) {
  15660. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  15661. }
  15662. };
  15663. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  15664. var renderingGroupId = spriteManager.renderingGroupId || 0;
  15665. this._prepareRenderingGroup(renderingGroupId);
  15666. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  15667. };
  15668. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  15669. var renderingGroupId = particleSystem.renderingGroupId || 0;
  15670. this._prepareRenderingGroup(renderingGroupId);
  15671. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  15672. };
  15673. RenderingManager.prototype.dispatch = function (subMesh) {
  15674. var mesh = subMesh.getMesh();
  15675. var renderingGroupId = mesh.renderingGroupId || 0;
  15676. this._prepareRenderingGroup(renderingGroupId);
  15677. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  15678. };
  15679. /**
  15680. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  15681. * This allowed control for front to back rendering or reversly depending of the special needs.
  15682. *
  15683. * @param renderingGroupId The rendering group id corresponding to its index
  15684. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  15685. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  15686. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  15687. */
  15688. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15689. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15690. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15691. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15692. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  15693. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  15694. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  15695. if (this._renderingGroups[renderingGroupId]) {
  15696. var group = this._renderingGroups[renderingGroupId];
  15697. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  15698. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  15699. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  15700. }
  15701. };
  15702. /**
  15703. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  15704. *
  15705. * @param renderingGroupId The rendering group id corresponding to its index
  15706. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  15707. * @param depth Automatically clears depth between groups if true and autoClear is true.
  15708. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  15709. */
  15710. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  15711. if (depth === void 0) { depth = true; }
  15712. if (stencil === void 0) { stencil = true; }
  15713. this._autoClearDepthStencil[renderingGroupId] = {
  15714. autoClear: autoClearDepthStencil,
  15715. depth: depth,
  15716. stencil: stencil
  15717. };
  15718. };
  15719. /**
  15720. * The max id used for rendering groups (not included)
  15721. */
  15722. RenderingManager.MAX_RENDERINGGROUPS = 4;
  15723. /**
  15724. * The min id used for rendering groups (included)
  15725. */
  15726. RenderingManager.MIN_RENDERINGGROUPS = 0;
  15727. /**
  15728. * Used to globally prevent autoclearing scenes.
  15729. */
  15730. RenderingManager.AUTOCLEAR = true;
  15731. return RenderingManager;
  15732. }());
  15733. BABYLON.RenderingManager = RenderingManager;
  15734. })(BABYLON || (BABYLON = {}));
  15735. //# sourceMappingURL=babylon.renderingManager.js.map
  15736. var BABYLON;
  15737. (function (BABYLON) {
  15738. var RenderingGroup = (function () {
  15739. /**
  15740. * Creates a new rendering group.
  15741. * @param index The rendering group index
  15742. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  15743. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  15744. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  15745. */
  15746. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15747. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15748. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15749. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15750. this.index = index;
  15751. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  15752. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  15753. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  15754. this._particleSystems = new BABYLON.SmartArray(256);
  15755. this._spriteManagers = new BABYLON.SmartArray(256);
  15756. this._edgesRenderers = new BABYLON.SmartArray(16);
  15757. this._scene = scene;
  15758. this.opaqueSortCompareFn = opaqueSortCompareFn;
  15759. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  15760. this.transparentSortCompareFn = transparentSortCompareFn;
  15761. }
  15762. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  15763. /**
  15764. * Set the opaque sort comparison function.
  15765. * If null the sub meshes will be render in the order they were created
  15766. */
  15767. set: function (value) {
  15768. this._opaqueSortCompareFn = value;
  15769. if (value) {
  15770. this._renderOpaque = this.renderOpaqueSorted;
  15771. }
  15772. else {
  15773. this._renderOpaque = RenderingGroup.renderUnsorted;
  15774. }
  15775. },
  15776. enumerable: true,
  15777. configurable: true
  15778. });
  15779. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  15780. /**
  15781. * Set the alpha test sort comparison function.
  15782. * If null the sub meshes will be render in the order they were created
  15783. */
  15784. set: function (value) {
  15785. this._alphaTestSortCompareFn = value;
  15786. if (value) {
  15787. this._renderAlphaTest = this.renderAlphaTestSorted;
  15788. }
  15789. else {
  15790. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  15791. }
  15792. },
  15793. enumerable: true,
  15794. configurable: true
  15795. });
  15796. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  15797. /**
  15798. * Set the transparent sort comparison function.
  15799. * If null the sub meshes will be render in the order they were created
  15800. */
  15801. set: function (value) {
  15802. if (value) {
  15803. this._transparentSortCompareFn = value;
  15804. }
  15805. else {
  15806. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  15807. }
  15808. this._renderTransparent = this.renderTransparentSorted;
  15809. },
  15810. enumerable: true,
  15811. configurable: true
  15812. });
  15813. /**
  15814. * Render all the sub meshes contained in the group.
  15815. * @param customRenderFunction Used to override the default render behaviour of the group.
  15816. * @returns true if rendered some submeshes.
  15817. */
  15818. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  15819. if (customRenderFunction) {
  15820. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  15821. return;
  15822. }
  15823. var engine = this._scene.getEngine();
  15824. // Opaque
  15825. if (this._opaqueSubMeshes.length !== 0) {
  15826. this._renderOpaque(this._opaqueSubMeshes);
  15827. }
  15828. // Alpha test
  15829. if (this._alphaTestSubMeshes.length !== 0) {
  15830. engine.setAlphaTesting(true);
  15831. this._renderAlphaTest(this._alphaTestSubMeshes);
  15832. engine.setAlphaTesting(false);
  15833. }
  15834. var stencilState = engine.getStencilBuffer();
  15835. engine.setStencilBuffer(false);
  15836. // Sprites
  15837. if (renderSprites) {
  15838. this._renderSprites();
  15839. }
  15840. // Particles
  15841. if (renderParticles) {
  15842. this._renderParticles(activeMeshes);
  15843. }
  15844. if (this.onBeforeTransparentRendering) {
  15845. this.onBeforeTransparentRendering();
  15846. }
  15847. // Transparent
  15848. if (this._transparentSubMeshes.length !== 0) {
  15849. this._renderTransparent(this._transparentSubMeshes);
  15850. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15851. }
  15852. // Set back stencil to false in case it changes before the edge renderer.
  15853. engine.setStencilBuffer(false);
  15854. // Edges
  15855. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  15856. this._edgesRenderers.data[edgesRendererIndex].render();
  15857. }
  15858. // Restore Stencil state.
  15859. engine.setStencilBuffer(stencilState);
  15860. };
  15861. /**
  15862. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  15863. * @param subMeshes The submeshes to render
  15864. */
  15865. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  15866. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15867. };
  15868. /**
  15869. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  15870. * @param subMeshes The submeshes to render
  15871. */
  15872. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  15873. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15874. };
  15875. /**
  15876. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  15877. * @param subMeshes The submeshes to render
  15878. */
  15879. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  15880. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  15881. };
  15882. /**
  15883. * Renders the submeshes in a specified order.
  15884. * @param subMeshes The submeshes to sort before render
  15885. * @param sortCompareFn The comparison function use to sort
  15886. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  15887. * @param transparent Specifies to activate blending if true
  15888. */
  15889. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  15890. var subIndex = 0;
  15891. var subMesh;
  15892. for (; subIndex < subMeshes.length; subIndex++) {
  15893. subMesh = subMeshes.data[subIndex];
  15894. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  15895. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  15896. }
  15897. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  15898. sortedArray.sort(sortCompareFn);
  15899. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  15900. subMesh = sortedArray[subIndex];
  15901. subMesh.render(transparent);
  15902. }
  15903. };
  15904. /**
  15905. * Renders the submeshes in the order they were dispatched (no sort applied).
  15906. * @param subMeshes The submeshes to render
  15907. */
  15908. RenderingGroup.renderUnsorted = function (subMeshes) {
  15909. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  15910. var submesh = subMeshes.data[subIndex];
  15911. submesh.render(false);
  15912. }
  15913. };
  15914. /**
  15915. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15916. * are rendered back to front if in the same alpha index.
  15917. *
  15918. * @param a The first submesh
  15919. * @param b The second submesh
  15920. * @returns The result of the comparison
  15921. */
  15922. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  15923. // Alpha index first
  15924. if (a._alphaIndex > b._alphaIndex) {
  15925. return 1;
  15926. }
  15927. if (a._alphaIndex < b._alphaIndex) {
  15928. return -1;
  15929. }
  15930. // Then distance to camera
  15931. return RenderingGroup.backToFrontSortCompare(a, b);
  15932. };
  15933. /**
  15934. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15935. * are rendered back to front.
  15936. *
  15937. * @param a The first submesh
  15938. * @param b The second submesh
  15939. * @returns The result of the comparison
  15940. */
  15941. RenderingGroup.backToFrontSortCompare = function (a, b) {
  15942. // Then distance to camera
  15943. if (a._distanceToCamera < b._distanceToCamera) {
  15944. return 1;
  15945. }
  15946. if (a._distanceToCamera > b._distanceToCamera) {
  15947. return -1;
  15948. }
  15949. return 0;
  15950. };
  15951. /**
  15952. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15953. * are rendered front to back (prevent overdraw).
  15954. *
  15955. * @param a The first submesh
  15956. * @param b The second submesh
  15957. * @returns The result of the comparison
  15958. */
  15959. RenderingGroup.frontToBackSortCompare = function (a, b) {
  15960. // Then distance to camera
  15961. if (a._distanceToCamera < b._distanceToCamera) {
  15962. return -1;
  15963. }
  15964. if (a._distanceToCamera > b._distanceToCamera) {
  15965. return 1;
  15966. }
  15967. return 0;
  15968. };
  15969. /**
  15970. * Resets the different lists of submeshes to prepare a new frame.
  15971. */
  15972. RenderingGroup.prototype.prepare = function () {
  15973. this._opaqueSubMeshes.reset();
  15974. this._transparentSubMeshes.reset();
  15975. this._alphaTestSubMeshes.reset();
  15976. this._particleSystems.reset();
  15977. this._spriteManagers.reset();
  15978. this._edgesRenderers.reset();
  15979. };
  15980. RenderingGroup.prototype.dispose = function () {
  15981. this._opaqueSubMeshes.dispose();
  15982. this._transparentSubMeshes.dispose();
  15983. this._alphaTestSubMeshes.dispose();
  15984. this._particleSystems.dispose();
  15985. this._spriteManagers.dispose();
  15986. this._edgesRenderers.dispose();
  15987. };
  15988. /**
  15989. * Inserts the submesh in its correct queue depending on its material.
  15990. * @param subMesh The submesh to dispatch
  15991. */
  15992. RenderingGroup.prototype.dispatch = function (subMesh) {
  15993. var material = subMesh.getMaterial();
  15994. var mesh = subMesh.getMesh();
  15995. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  15996. this._transparentSubMeshes.push(subMesh);
  15997. }
  15998. else if (material.needAlphaTesting()) {
  15999. this._alphaTestSubMeshes.push(subMesh);
  16000. }
  16001. else {
  16002. this._opaqueSubMeshes.push(subMesh); // Opaque
  16003. }
  16004. if (mesh._edgesRenderer) {
  16005. this._edgesRenderers.push(mesh._edgesRenderer);
  16006. }
  16007. };
  16008. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  16009. this._spriteManagers.push(spriteManager);
  16010. };
  16011. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  16012. this._particleSystems.push(particleSystem);
  16013. };
  16014. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  16015. if (this._particleSystems.length === 0) {
  16016. return;
  16017. }
  16018. // Particles
  16019. var activeCamera = this._scene.activeCamera;
  16020. this._scene._particlesDuration.beginMonitoring();
  16021. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  16022. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  16023. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  16024. continue;
  16025. }
  16026. var emitter = particleSystem.emitter;
  16027. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  16028. this._scene._activeParticles.addCount(particleSystem.render(), false);
  16029. }
  16030. }
  16031. this._scene._particlesDuration.endMonitoring(false);
  16032. };
  16033. RenderingGroup.prototype._renderSprites = function () {
  16034. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  16035. return;
  16036. }
  16037. // Sprites
  16038. var activeCamera = this._scene.activeCamera;
  16039. this._scene._spritesDuration.beginMonitoring();
  16040. for (var id = 0; id < this._spriteManagers.length; id++) {
  16041. var spriteManager = this._spriteManagers.data[id];
  16042. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  16043. spriteManager.render();
  16044. }
  16045. }
  16046. this._scene._spritesDuration.endMonitoring(false);
  16047. };
  16048. return RenderingGroup;
  16049. }());
  16050. BABYLON.RenderingGroup = RenderingGroup;
  16051. })(BABYLON || (BABYLON = {}));
  16052. //# sourceMappingURL=babylon.renderingGroup.js.map
  16053. var BABYLON;
  16054. (function (BABYLON) {
  16055. var ClickInfo = (function () {
  16056. function ClickInfo() {
  16057. this._singleClick = false;
  16058. this._doubleClick = false;
  16059. this._hasSwiped = false;
  16060. this._ignore = false;
  16061. }
  16062. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  16063. get: function () {
  16064. return this._singleClick;
  16065. },
  16066. set: function (b) {
  16067. this._singleClick = b;
  16068. },
  16069. enumerable: true,
  16070. configurable: true
  16071. });
  16072. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  16073. get: function () {
  16074. return this._doubleClick;
  16075. },
  16076. set: function (b) {
  16077. this._doubleClick = b;
  16078. },
  16079. enumerable: true,
  16080. configurable: true
  16081. });
  16082. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  16083. get: function () {
  16084. return this._hasSwiped;
  16085. },
  16086. set: function (b) {
  16087. this._hasSwiped = b;
  16088. },
  16089. enumerable: true,
  16090. configurable: true
  16091. });
  16092. Object.defineProperty(ClickInfo.prototype, "ignore", {
  16093. get: function () {
  16094. return this._ignore;
  16095. },
  16096. set: function (b) {
  16097. this._ignore = b;
  16098. },
  16099. enumerable: true,
  16100. configurable: true
  16101. });
  16102. return ClickInfo;
  16103. }());
  16104. var PointerEventTypes = (function () {
  16105. function PointerEventTypes() {
  16106. }
  16107. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  16108. get: function () {
  16109. return PointerEventTypes._POINTERDOWN;
  16110. },
  16111. enumerable: true,
  16112. configurable: true
  16113. });
  16114. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  16115. get: function () {
  16116. return PointerEventTypes._POINTERUP;
  16117. },
  16118. enumerable: true,
  16119. configurable: true
  16120. });
  16121. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  16122. get: function () {
  16123. return PointerEventTypes._POINTERMOVE;
  16124. },
  16125. enumerable: true,
  16126. configurable: true
  16127. });
  16128. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  16129. get: function () {
  16130. return PointerEventTypes._POINTERWHEEL;
  16131. },
  16132. enumerable: true,
  16133. configurable: true
  16134. });
  16135. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  16136. get: function () {
  16137. return PointerEventTypes._POINTERPICK;
  16138. },
  16139. enumerable: true,
  16140. configurable: true
  16141. });
  16142. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  16143. get: function () {
  16144. return PointerEventTypes._POINTERTAP;
  16145. },
  16146. enumerable: true,
  16147. configurable: true
  16148. });
  16149. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  16150. get: function () {
  16151. return PointerEventTypes._POINTERDOUBLETAP;
  16152. },
  16153. enumerable: true,
  16154. configurable: true
  16155. });
  16156. PointerEventTypes._POINTERDOWN = 0x01;
  16157. PointerEventTypes._POINTERUP = 0x02;
  16158. PointerEventTypes._POINTERMOVE = 0x04;
  16159. PointerEventTypes._POINTERWHEEL = 0x08;
  16160. PointerEventTypes._POINTERPICK = 0x10;
  16161. PointerEventTypes._POINTERTAP = 0x20;
  16162. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  16163. return PointerEventTypes;
  16164. }());
  16165. BABYLON.PointerEventTypes = PointerEventTypes;
  16166. var PointerInfoBase = (function () {
  16167. function PointerInfoBase(type, event) {
  16168. this.type = type;
  16169. this.event = event;
  16170. }
  16171. return PointerInfoBase;
  16172. }());
  16173. BABYLON.PointerInfoBase = PointerInfoBase;
  16174. /**
  16175. * This class is used to store pointer related info for the onPrePointerObservable event.
  16176. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  16177. */
  16178. var PointerInfoPre = (function (_super) {
  16179. __extends(PointerInfoPre, _super);
  16180. function PointerInfoPre(type, event, localX, localY) {
  16181. var _this = _super.call(this, type, event) || this;
  16182. _this.skipOnPointerObservable = false;
  16183. _this.localPosition = new BABYLON.Vector2(localX, localY);
  16184. return _this;
  16185. }
  16186. return PointerInfoPre;
  16187. }(PointerInfoBase));
  16188. BABYLON.PointerInfoPre = PointerInfoPre;
  16189. /**
  16190. * This type contains all the data related to a pointer event in Babylon.js.
  16191. * 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.
  16192. */
  16193. var PointerInfo = (function (_super) {
  16194. __extends(PointerInfo, _super);
  16195. function PointerInfo(type, event, pickInfo) {
  16196. var _this = _super.call(this, type, event) || this;
  16197. _this.pickInfo = pickInfo;
  16198. return _this;
  16199. }
  16200. return PointerInfo;
  16201. }(PointerInfoBase));
  16202. BABYLON.PointerInfo = PointerInfo;
  16203. /**
  16204. * This class is used by the onRenderingGroupObservable
  16205. */
  16206. var RenderingGroupInfo = (function () {
  16207. function RenderingGroupInfo() {
  16208. }
  16209. /**
  16210. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  16211. * This stage will be fired no matter what
  16212. */
  16213. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  16214. /**
  16215. * Called before opaque object are rendered.
  16216. * This stage will be fired only if there's 3D Opaque content to render
  16217. */
  16218. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  16219. /**
  16220. * Called after the opaque objects are rendered and before the transparent ones
  16221. * This stage will be fired only if there's 3D transparent content to render
  16222. */
  16223. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  16224. /**
  16225. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  16226. * This stage will be fired no matter what
  16227. */
  16228. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  16229. return RenderingGroupInfo;
  16230. }());
  16231. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  16232. /**
  16233. * Represents a scene to be rendered by the engine.
  16234. * @see http://doc.babylonjs.com/page.php?p=21911
  16235. */
  16236. var Scene = (function () {
  16237. /**
  16238. * @constructor
  16239. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  16240. */
  16241. function Scene(engine) {
  16242. // Members
  16243. this.autoClear = true;
  16244. this.autoClearDepthAndStencil = true;
  16245. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  16246. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  16247. this.forceWireframe = false;
  16248. this._forcePointsCloud = false;
  16249. this.forceShowBoundingBoxes = false;
  16250. this.animationsEnabled = true;
  16251. this.constantlyUpdateMeshUnderPointer = false;
  16252. this.hoverCursor = "pointer";
  16253. this.defaultCursor = "";
  16254. // Metadata
  16255. this.metadata = null;
  16256. // Events
  16257. /**
  16258. * An event triggered when the scene is disposed.
  16259. * @type {BABYLON.Observable}
  16260. */
  16261. this.onDisposeObservable = new BABYLON.Observable();
  16262. /**
  16263. * An event triggered before rendering the scene
  16264. * @type {BABYLON.Observable}
  16265. */
  16266. this.onBeforeRenderObservable = new BABYLON.Observable();
  16267. /**
  16268. * An event triggered after rendering the scene
  16269. * @type {BABYLON.Observable}
  16270. */
  16271. this.onAfterRenderObservable = new BABYLON.Observable();
  16272. /**
  16273. * An event triggered when the scene is ready
  16274. * @type {BABYLON.Observable}
  16275. */
  16276. this.onReadyObservable = new BABYLON.Observable();
  16277. /**
  16278. * An event triggered before rendering a camera
  16279. * @type {BABYLON.Observable}
  16280. */
  16281. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  16282. /**
  16283. * An event triggered after rendering a camera
  16284. * @type {BABYLON.Observable}
  16285. */
  16286. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  16287. /**
  16288. * An event triggered when a camera is created
  16289. * @type {BABYLON.Observable}
  16290. */
  16291. this.onNewCameraAddedObservable = new BABYLON.Observable();
  16292. /**
  16293. * An event triggered when a camera is removed
  16294. * @type {BABYLON.Observable}
  16295. */
  16296. this.onCameraRemovedObservable = new BABYLON.Observable();
  16297. /**
  16298. * An event triggered when a light is created
  16299. * @type {BABYLON.Observable}
  16300. */
  16301. this.onNewLightAddedObservable = new BABYLON.Observable();
  16302. /**
  16303. * An event triggered when a light is removed
  16304. * @type {BABYLON.Observable}
  16305. */
  16306. this.onLightRemovedObservable = new BABYLON.Observable();
  16307. /**
  16308. * An event triggered when a geometry is created
  16309. * @type {BABYLON.Observable}
  16310. */
  16311. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  16312. /**
  16313. * An event triggered when a geometry is removed
  16314. * @type {BABYLON.Observable}
  16315. */
  16316. this.onGeometryRemovedObservable = new BABYLON.Observable();
  16317. /**
  16318. * An event triggered when a mesh is created
  16319. * @type {BABYLON.Observable}
  16320. */
  16321. this.onNewMeshAddedObservable = new BABYLON.Observable();
  16322. /**
  16323. * An event triggered when a mesh is removed
  16324. * @type {BABYLON.Observable}
  16325. */
  16326. this.onMeshRemovedObservable = new BABYLON.Observable();
  16327. /**
  16328. * An event triggered before calculating deterministic simulation step
  16329. * @type {BABYLON.Observable}
  16330. */
  16331. this.onBeforeStepObservable = new BABYLON.Observable();
  16332. /**
  16333. * An event triggered after calculating deterministic simulation step
  16334. * @type {BABYLON.Observable}
  16335. */
  16336. this.onAfterStepObservable = new BABYLON.Observable();
  16337. /**
  16338. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  16339. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  16340. * 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)
  16341. */
  16342. this.onRenderingGroupObservable = new BABYLON.Observable();
  16343. // Animations
  16344. this.animations = [];
  16345. /**
  16346. * 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).
  16347. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  16348. */
  16349. this.onPrePointerObservable = new BABYLON.Observable();
  16350. /**
  16351. * Observable event triggered each time an input event is received from the rendering canvas
  16352. */
  16353. this.onPointerObservable = new BABYLON.Observable();
  16354. this._meshPickProceed = false;
  16355. this._previousHasSwiped = false;
  16356. this._currentPickResult = null;
  16357. this._previousPickResult = null;
  16358. this._isButtonPressed = false;
  16359. this._doubleClickOccured = false;
  16360. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  16361. this.cameraToUseForPointers = null;
  16362. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  16363. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  16364. this._startingPointerTime = 0;
  16365. this._previousStartingPointerTime = 0;
  16366. // Deterministic lockstep
  16367. this._timeAccumulator = 0;
  16368. this._currentStepId = 0;
  16369. this._currentInternalStep = 0;
  16370. // Coordinate system
  16371. /**
  16372. * use right-handed coordinate system on this scene.
  16373. * @type {boolean}
  16374. */
  16375. this._useRightHandedSystem = false;
  16376. // Fog
  16377. this._fogEnabled = true;
  16378. this._fogMode = Scene.FOGMODE_NONE;
  16379. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16380. this.fogDensity = 0.1;
  16381. this.fogStart = 0;
  16382. this.fogEnd = 1000.0;
  16383. // Lights
  16384. /**
  16385. * is shadow enabled on this scene.
  16386. * @type {boolean}
  16387. */
  16388. this._shadowsEnabled = true;
  16389. /**
  16390. * is light enabled on this scene.
  16391. * @type {boolean}
  16392. */
  16393. this._lightsEnabled = true;
  16394. /**
  16395. * All of the lights added to this scene.
  16396. * @see BABYLON.Light
  16397. * @type {BABYLON.Light[]}
  16398. */
  16399. this.lights = new Array();
  16400. // Cameras
  16401. /** All of the cameras added to this scene. */
  16402. this.cameras = new Array();
  16403. /** All of the active cameras added to this scene. */
  16404. this.activeCameras = new Array();
  16405. // Meshes
  16406. /**
  16407. * All of the (abstract) meshes added to this scene.
  16408. * @see BABYLON.AbstractMesh
  16409. * @type {BABYLON.AbstractMesh[]}
  16410. */
  16411. this.meshes = new Array();
  16412. // Geometries
  16413. this._geometries = new Array();
  16414. this.materials = new Array();
  16415. this.multiMaterials = new Array();
  16416. // Textures
  16417. this._texturesEnabled = true;
  16418. this.textures = new Array();
  16419. // Particles
  16420. this.particlesEnabled = true;
  16421. this.particleSystems = new Array();
  16422. // Sprites
  16423. this.spritesEnabled = true;
  16424. this.spriteManagers = new Array();
  16425. // Layers
  16426. this.layers = new Array();
  16427. this.highlightLayers = new Array();
  16428. // Skeletons
  16429. this._skeletonsEnabled = true;
  16430. this.skeletons = new Array();
  16431. // Morph targets
  16432. this.morphTargetManagers = new Array();
  16433. // Lens flares
  16434. this.lensFlaresEnabled = true;
  16435. this.lensFlareSystems = new Array();
  16436. // Collisions
  16437. this.collisionsEnabled = true;
  16438. /** Defines the gravity applied to this scene */
  16439. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  16440. // Postprocesses
  16441. this.postProcesses = new Array();
  16442. this.postProcessesEnabled = true;
  16443. // Customs render targets
  16444. this.renderTargetsEnabled = true;
  16445. this.dumpNextRenderTargets = false;
  16446. this.customRenderTargets = new Array();
  16447. // Imported meshes
  16448. this.importedMeshesFiles = new Array();
  16449. // Probes
  16450. this.probesEnabled = true;
  16451. this.reflectionProbes = new Array();
  16452. this._actionManagers = new Array();
  16453. this._meshesForIntersections = new BABYLON.SmartArray(256);
  16454. // Procedural textures
  16455. this.proceduralTexturesEnabled = true;
  16456. this._proceduralTextures = new Array();
  16457. this.soundTracks = new Array();
  16458. this._audioEnabled = true;
  16459. this._headphone = false;
  16460. // Performance counters
  16461. this._totalMeshesCounter = new BABYLON.PerfCounter();
  16462. this._totalLightsCounter = new BABYLON.PerfCounter();
  16463. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  16464. this._totalTexturesCounter = new BABYLON.PerfCounter();
  16465. this._totalVertices = new BABYLON.PerfCounter();
  16466. this._activeIndices = new BABYLON.PerfCounter();
  16467. this._activeParticles = new BABYLON.PerfCounter();
  16468. this._lastFrameDuration = new BABYLON.PerfCounter();
  16469. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  16470. this._renderTargetsDuration = new BABYLON.PerfCounter();
  16471. this._particlesDuration = new BABYLON.PerfCounter();
  16472. this._renderDuration = new BABYLON.PerfCounter();
  16473. this._spritesDuration = new BABYLON.PerfCounter();
  16474. this._activeBones = new BABYLON.PerfCounter();
  16475. this._animationTime = 0;
  16476. this.animationTimeScale = 1;
  16477. this._renderId = 0;
  16478. this._executeWhenReadyTimeoutId = -1;
  16479. this._intermediateRendering = false;
  16480. this._viewUpdateFlag = -1;
  16481. this._projectionUpdateFlag = -1;
  16482. this._toBeDisposed = new BABYLON.SmartArray(256);
  16483. this._pendingData = []; //ANY
  16484. this._activeMeshes = new BABYLON.SmartArray(256);
  16485. this._processedMaterials = new BABYLON.SmartArray(256);
  16486. this._renderTargets = new BABYLON.SmartArray(256);
  16487. this._activeParticleSystems = new BABYLON.SmartArray(256);
  16488. this._activeSkeletons = new BABYLON.SmartArray(32);
  16489. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  16490. this._activeAnimatables = new Array();
  16491. this._transformMatrix = BABYLON.Matrix.Zero();
  16492. this.requireLightSorting = false;
  16493. this._uniqueIdCounter = 0;
  16494. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  16495. this._engine.scenes.push(this);
  16496. this._uid = null;
  16497. this._renderingManager = new BABYLON.RenderingManager(this);
  16498. this.postProcessManager = new BABYLON.PostProcessManager(this);
  16499. if (BABYLON.OutlineRenderer) {
  16500. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  16501. }
  16502. this.attachControl();
  16503. if (BABYLON.SoundTrack) {
  16504. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  16505. }
  16506. //simplification queue
  16507. if (BABYLON.SimplificationQueue) {
  16508. this.simplificationQueue = new BABYLON.SimplificationQueue();
  16509. }
  16510. //collision coordinator initialization. For now legacy per default.
  16511. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  16512. // Uniform Buffer
  16513. this._createUbo();
  16514. // Default Image processing definition.
  16515. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  16516. }
  16517. Object.defineProperty(Scene, "FOGMODE_NONE", {
  16518. /** The fog is deactivated */
  16519. get: function () {
  16520. return Scene._FOGMODE_NONE;
  16521. },
  16522. enumerable: true,
  16523. configurable: true
  16524. });
  16525. Object.defineProperty(Scene, "FOGMODE_EXP", {
  16526. /** The fog density is following an exponential function */
  16527. get: function () {
  16528. return Scene._FOGMODE_EXP;
  16529. },
  16530. enumerable: true,
  16531. configurable: true
  16532. });
  16533. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  16534. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  16535. get: function () {
  16536. return Scene._FOGMODE_EXP2;
  16537. },
  16538. enumerable: true,
  16539. configurable: true
  16540. });
  16541. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  16542. /** The fog density is following a linear function. */
  16543. get: function () {
  16544. return Scene._FOGMODE_LINEAR;
  16545. },
  16546. enumerable: true,
  16547. configurable: true
  16548. });
  16549. Object.defineProperty(Scene.prototype, "environmentTexture", {
  16550. /**
  16551. * Texture used in all pbr material as the reflection texture.
  16552. * As in the majority of the scene they are the same (exception for multi room and so on),
  16553. * this is easier to reference from here than from all the materials.
  16554. */
  16555. get: function () {
  16556. return this._environmentTexture;
  16557. },
  16558. /**
  16559. * Texture used in all pbr material as the reflection texture.
  16560. * As in the majority of the scene they are the same (exception for multi room and so on),
  16561. * this is easier to set here than in all the materials.
  16562. */
  16563. set: function (value) {
  16564. this._environmentTexture = value;
  16565. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  16566. },
  16567. enumerable: true,
  16568. configurable: true
  16569. });
  16570. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  16571. /**
  16572. * Default image processing configuration used either in the rendering
  16573. * Forward main pass or through the imageProcessingPostProcess if present.
  16574. * As in the majority of the scene they are the same (exception for multi camera),
  16575. * this is easier to reference from here than from all the materials and post process.
  16576. *
  16577. * No setter as we it is a shared configuration, you can set the values instead.
  16578. */
  16579. get: function () {
  16580. return this._imageProcessingConfiguration;
  16581. },
  16582. enumerable: true,
  16583. configurable: true
  16584. });
  16585. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  16586. get: function () {
  16587. return this._forcePointsCloud;
  16588. },
  16589. set: function (value) {
  16590. if (this._forcePointsCloud === value) {
  16591. return;
  16592. }
  16593. this._forcePointsCloud = value;
  16594. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16595. },
  16596. enumerable: true,
  16597. configurable: true
  16598. });
  16599. Object.defineProperty(Scene.prototype, "onDispose", {
  16600. /** A function to be executed when this scene is disposed. */
  16601. set: function (callback) {
  16602. if (this._onDisposeObserver) {
  16603. this.onDisposeObservable.remove(this._onDisposeObserver);
  16604. }
  16605. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  16606. },
  16607. enumerable: true,
  16608. configurable: true
  16609. });
  16610. Object.defineProperty(Scene.prototype, "beforeRender", {
  16611. /** A function to be executed before rendering this scene */
  16612. set: function (callback) {
  16613. if (this._onBeforeRenderObserver) {
  16614. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  16615. }
  16616. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  16617. },
  16618. enumerable: true,
  16619. configurable: true
  16620. });
  16621. Object.defineProperty(Scene.prototype, "afterRender", {
  16622. /** A function to be executed after rendering this scene */
  16623. set: function (callback) {
  16624. if (this._onAfterRenderObserver) {
  16625. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  16626. }
  16627. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  16628. },
  16629. enumerable: true,
  16630. configurable: true
  16631. });
  16632. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  16633. set: function (callback) {
  16634. if (this._onBeforeCameraRenderObserver) {
  16635. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  16636. }
  16637. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  16638. },
  16639. enumerable: true,
  16640. configurable: true
  16641. });
  16642. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  16643. set: function (callback) {
  16644. if (this._onAfterCameraRenderObserver) {
  16645. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  16646. }
  16647. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  16648. },
  16649. enumerable: true,
  16650. configurable: true
  16651. });
  16652. Object.defineProperty(Scene.prototype, "gamepadManager", {
  16653. get: function () {
  16654. if (!this._gamepadManager) {
  16655. this._gamepadManager = new BABYLON.GamepadManager();
  16656. }
  16657. return this._gamepadManager;
  16658. },
  16659. enumerable: true,
  16660. configurable: true
  16661. });
  16662. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  16663. get: function () {
  16664. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  16665. },
  16666. enumerable: true,
  16667. configurable: true
  16668. });
  16669. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  16670. get: function () {
  16671. return this._useRightHandedSystem;
  16672. },
  16673. set: function (value) {
  16674. if (this._useRightHandedSystem === value) {
  16675. return;
  16676. }
  16677. this._useRightHandedSystem = value;
  16678. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16679. },
  16680. enumerable: true,
  16681. configurable: true
  16682. });
  16683. Scene.prototype.setStepId = function (newStepId) {
  16684. this._currentStepId = newStepId;
  16685. };
  16686. ;
  16687. Scene.prototype.getStepId = function () {
  16688. return this._currentStepId;
  16689. };
  16690. ;
  16691. Scene.prototype.getInternalStep = function () {
  16692. return this._currentInternalStep;
  16693. };
  16694. ;
  16695. Object.defineProperty(Scene.prototype, "fogEnabled", {
  16696. get: function () {
  16697. return this._fogEnabled;
  16698. },
  16699. /**
  16700. * is fog enabled on this scene.
  16701. */
  16702. set: function (value) {
  16703. if (this._fogEnabled === value) {
  16704. return;
  16705. }
  16706. this._fogEnabled = value;
  16707. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16708. },
  16709. enumerable: true,
  16710. configurable: true
  16711. });
  16712. Object.defineProperty(Scene.prototype, "fogMode", {
  16713. get: function () {
  16714. return this._fogMode;
  16715. },
  16716. set: function (value) {
  16717. if (this._fogMode === value) {
  16718. return;
  16719. }
  16720. this._fogMode = value;
  16721. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16722. },
  16723. enumerable: true,
  16724. configurable: true
  16725. });
  16726. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  16727. get: function () {
  16728. return this._shadowsEnabled;
  16729. },
  16730. set: function (value) {
  16731. if (this._shadowsEnabled === value) {
  16732. return;
  16733. }
  16734. this._shadowsEnabled = value;
  16735. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  16736. },
  16737. enumerable: true,
  16738. configurable: true
  16739. });
  16740. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  16741. get: function () {
  16742. return this._lightsEnabled;
  16743. },
  16744. set: function (value) {
  16745. if (this._lightsEnabled === value) {
  16746. return;
  16747. }
  16748. this._lightsEnabled = value;
  16749. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  16750. },
  16751. enumerable: true,
  16752. configurable: true
  16753. });
  16754. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  16755. /** The default material used on meshes when no material is affected */
  16756. get: function () {
  16757. if (!this._defaultMaterial) {
  16758. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  16759. }
  16760. return this._defaultMaterial;
  16761. },
  16762. /** The default material used on meshes when no material is affected */
  16763. set: function (value) {
  16764. this._defaultMaterial = value;
  16765. },
  16766. enumerable: true,
  16767. configurable: true
  16768. });
  16769. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  16770. get: function () {
  16771. return this._texturesEnabled;
  16772. },
  16773. set: function (value) {
  16774. if (this._texturesEnabled === value) {
  16775. return;
  16776. }
  16777. this._texturesEnabled = value;
  16778. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  16779. },
  16780. enumerable: true,
  16781. configurable: true
  16782. });
  16783. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  16784. get: function () {
  16785. return this._skeletonsEnabled;
  16786. },
  16787. set: function (value) {
  16788. if (this._skeletonsEnabled === value) {
  16789. return;
  16790. }
  16791. this._skeletonsEnabled = value;
  16792. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  16793. },
  16794. enumerable: true,
  16795. configurable: true
  16796. });
  16797. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  16798. get: function () {
  16799. if (!this._postProcessRenderPipelineManager) {
  16800. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  16801. }
  16802. return this._postProcessRenderPipelineManager;
  16803. },
  16804. enumerable: true,
  16805. configurable: true
  16806. });
  16807. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  16808. get: function () {
  16809. return this._frustumPlanes;
  16810. },
  16811. enumerable: true,
  16812. configurable: true
  16813. });
  16814. Object.defineProperty(Scene.prototype, "debugLayer", {
  16815. // Properties
  16816. get: function () {
  16817. if (!this._debugLayer) {
  16818. this._debugLayer = new BABYLON.DebugLayer(this);
  16819. }
  16820. return this._debugLayer;
  16821. },
  16822. enumerable: true,
  16823. configurable: true
  16824. });
  16825. Object.defineProperty(Scene.prototype, "workerCollisions", {
  16826. get: function () {
  16827. return this._workerCollisions;
  16828. },
  16829. set: function (enabled) {
  16830. if (!BABYLON.CollisionCoordinatorLegacy) {
  16831. return;
  16832. }
  16833. enabled = (enabled && !!Worker);
  16834. this._workerCollisions = enabled;
  16835. if (this.collisionCoordinator) {
  16836. this.collisionCoordinator.destroy();
  16837. }
  16838. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  16839. this.collisionCoordinator.init(this);
  16840. },
  16841. enumerable: true,
  16842. configurable: true
  16843. });
  16844. Object.defineProperty(Scene.prototype, "selectionOctree", {
  16845. get: function () {
  16846. return this._selectionOctree;
  16847. },
  16848. enumerable: true,
  16849. configurable: true
  16850. });
  16851. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  16852. /**
  16853. * The mesh that is currently under the pointer.
  16854. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  16855. */
  16856. get: function () {
  16857. return this._pointerOverMesh;
  16858. },
  16859. enumerable: true,
  16860. configurable: true
  16861. });
  16862. Object.defineProperty(Scene.prototype, "pointerX", {
  16863. /**
  16864. * Current on-screen X position of the pointer
  16865. * @return {number} X position of the pointer
  16866. */
  16867. get: function () {
  16868. return this._pointerX;
  16869. },
  16870. enumerable: true,
  16871. configurable: true
  16872. });
  16873. Object.defineProperty(Scene.prototype, "pointerY", {
  16874. /**
  16875. * Current on-screen Y position of the pointer
  16876. * @return {number} Y position of the pointer
  16877. */
  16878. get: function () {
  16879. return this._pointerY;
  16880. },
  16881. enumerable: true,
  16882. configurable: true
  16883. });
  16884. Scene.prototype.getCachedMaterial = function () {
  16885. return this._cachedMaterial;
  16886. };
  16887. Scene.prototype.getCachedEffect = function () {
  16888. return this._cachedEffect;
  16889. };
  16890. Scene.prototype.getCachedVisibility = function () {
  16891. return this._cachedVisibility;
  16892. };
  16893. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  16894. if (visibility === void 0) { visibility = 1; }
  16895. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  16896. };
  16897. Scene.prototype.getBoundingBoxRenderer = function () {
  16898. if (!this._boundingBoxRenderer) {
  16899. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  16900. }
  16901. return this._boundingBoxRenderer;
  16902. };
  16903. Scene.prototype.getOutlineRenderer = function () {
  16904. return this._outlineRenderer;
  16905. };
  16906. Scene.prototype.getEngine = function () {
  16907. return this._engine;
  16908. };
  16909. Scene.prototype.getTotalVertices = function () {
  16910. return this._totalVertices.current;
  16911. };
  16912. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  16913. get: function () {
  16914. return this._totalVertices;
  16915. },
  16916. enumerable: true,
  16917. configurable: true
  16918. });
  16919. Scene.prototype.getActiveIndices = function () {
  16920. return this._activeIndices.current;
  16921. };
  16922. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  16923. get: function () {
  16924. return this._activeIndices;
  16925. },
  16926. enumerable: true,
  16927. configurable: true
  16928. });
  16929. Scene.prototype.getActiveParticles = function () {
  16930. return this._activeParticles.current;
  16931. };
  16932. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  16933. get: function () {
  16934. return this._activeParticles;
  16935. },
  16936. enumerable: true,
  16937. configurable: true
  16938. });
  16939. Scene.prototype.getActiveBones = function () {
  16940. return this._activeBones.current;
  16941. };
  16942. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  16943. get: function () {
  16944. return this._activeBones;
  16945. },
  16946. enumerable: true,
  16947. configurable: true
  16948. });
  16949. // Stats
  16950. Scene.prototype.getLastFrameDuration = function () {
  16951. return this._lastFrameDuration.current;
  16952. };
  16953. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  16954. get: function () {
  16955. return this._lastFrameDuration;
  16956. },
  16957. enumerable: true,
  16958. configurable: true
  16959. });
  16960. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  16961. return this._evaluateActiveMeshesDuration.current;
  16962. };
  16963. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  16964. get: function () {
  16965. return this._evaluateActiveMeshesDuration;
  16966. },
  16967. enumerable: true,
  16968. configurable: true
  16969. });
  16970. Scene.prototype.getActiveMeshes = function () {
  16971. return this._activeMeshes;
  16972. };
  16973. Scene.prototype.getRenderTargetsDuration = function () {
  16974. return this._renderTargetsDuration.current;
  16975. };
  16976. Scene.prototype.getRenderDuration = function () {
  16977. return this._renderDuration.current;
  16978. };
  16979. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  16980. get: function () {
  16981. return this._renderDuration;
  16982. },
  16983. enumerable: true,
  16984. configurable: true
  16985. });
  16986. Scene.prototype.getParticlesDuration = function () {
  16987. return this._particlesDuration.current;
  16988. };
  16989. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  16990. get: function () {
  16991. return this._particlesDuration;
  16992. },
  16993. enumerable: true,
  16994. configurable: true
  16995. });
  16996. Scene.prototype.getSpritesDuration = function () {
  16997. return this._spritesDuration.current;
  16998. };
  16999. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  17000. get: function () {
  17001. return this._spritesDuration;
  17002. },
  17003. enumerable: true,
  17004. configurable: true
  17005. });
  17006. Scene.prototype.getAnimationRatio = function () {
  17007. return this._animationRatio;
  17008. };
  17009. Scene.prototype.getRenderId = function () {
  17010. return this._renderId;
  17011. };
  17012. Scene.prototype.incrementRenderId = function () {
  17013. this._renderId++;
  17014. };
  17015. Scene.prototype._updatePointerPosition = function (evt) {
  17016. var canvasRect = this._engine.getRenderingCanvasClientRect();
  17017. this._pointerX = evt.clientX - canvasRect.left;
  17018. this._pointerY = evt.clientY - canvasRect.top;
  17019. this._unTranslatedPointerX = this._pointerX;
  17020. this._unTranslatedPointerY = this._pointerY;
  17021. };
  17022. Scene.prototype._createUbo = function () {
  17023. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  17024. this._sceneUbo.addUniform("viewProjection", 16);
  17025. this._sceneUbo.addUniform("view", 16);
  17026. };
  17027. // Pointers handling
  17028. /**
  17029. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  17030. * @param attachUp defines if you want to attach events to pointerup
  17031. * @param attachDown defines if you want to attach events to pointerdown
  17032. * @param attachMove defines if you want to attach events to pointermove
  17033. */
  17034. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  17035. var _this = this;
  17036. if (attachUp === void 0) { attachUp = true; }
  17037. if (attachDown === void 0) { attachDown = true; }
  17038. if (attachMove === void 0) { attachMove = true; }
  17039. this._initActionManager = function (act, clickInfo) {
  17040. if (!_this._meshPickProceed) {
  17041. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17042. _this._currentPickResult = pickResult;
  17043. if (pickResult) {
  17044. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  17045. }
  17046. _this._meshPickProceed = true;
  17047. }
  17048. return act;
  17049. };
  17050. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  17051. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  17052. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  17053. btn !== _this._previousButtonPressed) {
  17054. _this._doubleClickOccured = false;
  17055. clickInfo.singleClick = true;
  17056. clickInfo.ignore = false;
  17057. cb(clickInfo, _this._currentPickResult);
  17058. }
  17059. };
  17060. this._initClickEvent = function (obs1, obs2, evt, cb) {
  17061. var clickInfo = new ClickInfo();
  17062. _this._currentPickResult = null;
  17063. var act;
  17064. var checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  17065. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  17066. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  17067. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  17068. act = _this._initActionManager(act, clickInfo);
  17069. if (act)
  17070. checkPicking = act.hasPickTriggers;
  17071. }
  17072. if (checkPicking) {
  17073. var btn = evt.button;
  17074. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  17075. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  17076. if (!clickInfo.hasSwiped) {
  17077. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  17078. if (!checkSingleClickImmediately) {
  17079. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  17080. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  17081. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17082. act = _this._initActionManager(act, clickInfo);
  17083. if (act)
  17084. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  17085. }
  17086. }
  17087. if (checkSingleClickImmediately) {
  17088. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  17089. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  17090. btn !== _this._previousButtonPressed) {
  17091. clickInfo.singleClick = true;
  17092. cb(clickInfo, _this._currentPickResult);
  17093. }
  17094. }
  17095. else {
  17096. // wait that no double click has been raised during the double click delay
  17097. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17098. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  17099. }
  17100. var checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  17101. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  17102. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17103. act = _this._initActionManager(act, clickInfo);
  17104. if (act)
  17105. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  17106. }
  17107. if (checkDoubleClick) {
  17108. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  17109. if (btn === _this._previousButtonPressed &&
  17110. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  17111. !_this._doubleClickOccured) {
  17112. // pointer has not moved for 2 clicks, it's a double click
  17113. if (!clickInfo.hasSwiped &&
  17114. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  17115. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  17116. _this._previousStartingPointerTime = 0;
  17117. _this._doubleClickOccured = true;
  17118. clickInfo.doubleClick = true;
  17119. clickInfo.ignore = false;
  17120. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  17121. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  17122. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17123. cb(clickInfo, _this._currentPickResult);
  17124. }
  17125. else {
  17126. _this._doubleClickOccured = false;
  17127. _this._previousStartingPointerTime = _this._startingPointerTime;
  17128. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  17129. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  17130. _this._previousButtonPressed = btn;
  17131. _this._previousHasSwiped = clickInfo.hasSwiped;
  17132. if (Scene.ExclusiveDoubleClickMode) {
  17133. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  17134. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  17135. }
  17136. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17137. cb(clickInfo, _this._previousPickResult);
  17138. }
  17139. else {
  17140. cb(clickInfo, _this._currentPickResult);
  17141. }
  17142. }
  17143. }
  17144. else {
  17145. _this._doubleClickOccured = false;
  17146. _this._previousStartingPointerTime = _this._startingPointerTime;
  17147. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  17148. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  17149. _this._previousButtonPressed = btn;
  17150. _this._previousHasSwiped = clickInfo.hasSwiped;
  17151. }
  17152. }
  17153. }
  17154. }
  17155. clickInfo.ignore = true;
  17156. cb(clickInfo, _this._currentPickResult);
  17157. };
  17158. var spritePredicate = function (sprite) {
  17159. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  17160. };
  17161. this._onPointerMove = function (evt) {
  17162. _this._updatePointerPosition(evt);
  17163. // PreObservable support
  17164. if (_this.onPrePointerObservable.hasObservers()) {
  17165. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  17166. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17167. _this.onPrePointerObservable.notifyObservers(pi, type);
  17168. if (pi.skipOnPointerObservable) {
  17169. return;
  17170. }
  17171. }
  17172. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17173. return;
  17174. }
  17175. var canvas = _this._engine.getRenderingCanvas();
  17176. if (!_this.pointerMovePredicate) {
  17177. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  17178. }
  17179. // Meshes
  17180. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  17181. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17182. _this.setPointerOverSprite(null);
  17183. _this.setPointerOverMesh(pickResult.pickedMesh);
  17184. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  17185. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  17186. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  17187. }
  17188. else {
  17189. canvas.style.cursor = _this.hoverCursor;
  17190. }
  17191. }
  17192. else {
  17193. canvas.style.cursor = _this.defaultCursor;
  17194. }
  17195. }
  17196. else {
  17197. _this.setPointerOverMesh(null);
  17198. // Sprites
  17199. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17200. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  17201. _this.setPointerOverSprite(pickResult.pickedSprite);
  17202. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  17203. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  17204. }
  17205. else {
  17206. canvas.style.cursor = _this.hoverCursor;
  17207. }
  17208. }
  17209. else {
  17210. _this.setPointerOverSprite(null);
  17211. // Restore pointer
  17212. canvas.style.cursor = _this.defaultCursor;
  17213. }
  17214. }
  17215. if (_this.onPointerMove) {
  17216. _this.onPointerMove(evt, pickResult);
  17217. }
  17218. if (_this.onPointerObservable.hasObservers()) {
  17219. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  17220. var pi = new PointerInfo(type, evt, pickResult);
  17221. _this.onPointerObservable.notifyObservers(pi, type);
  17222. }
  17223. };
  17224. this._onPointerDown = function (evt) {
  17225. _this._isButtonPressed = true;
  17226. _this._pickedDownMesh = null;
  17227. _this._meshPickProceed = false;
  17228. _this._updatePointerPosition(evt);
  17229. // PreObservable support
  17230. if (_this.onPrePointerObservable.hasObservers()) {
  17231. var type = PointerEventTypes.POINTERDOWN;
  17232. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17233. _this.onPrePointerObservable.notifyObservers(pi, type);
  17234. if (pi.skipOnPointerObservable) {
  17235. return;
  17236. }
  17237. }
  17238. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17239. return;
  17240. }
  17241. _this._startingPointerPosition.x = _this._pointerX;
  17242. _this._startingPointerPosition.y = _this._pointerY;
  17243. _this._startingPointerTime = new Date().getTime();
  17244. if (!_this.pointerDownPredicate) {
  17245. _this.pointerDownPredicate = function (mesh) {
  17246. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  17247. };
  17248. }
  17249. // Meshes
  17250. _this._pickedDownMesh = null;
  17251. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17252. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17253. _this._pickedDownMesh = pickResult.pickedMesh;
  17254. var actionManager = pickResult.pickedMesh.actionManager;
  17255. if (actionManager) {
  17256. if (actionManager.hasPickTriggers) {
  17257. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17258. switch (evt.button) {
  17259. case 0:
  17260. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17261. break;
  17262. case 1:
  17263. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17264. break;
  17265. case 2:
  17266. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17267. break;
  17268. }
  17269. }
  17270. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  17271. window.setTimeout((function () {
  17272. var _this = this;
  17273. 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);
  17274. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17275. if (this._isButtonPressed &&
  17276. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  17277. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  17278. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  17279. this._startingPointerTime = 0;
  17280. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17281. }
  17282. }
  17283. }).bind(_this), Scene.LongPressDelay);
  17284. }
  17285. }
  17286. }
  17287. if (_this.onPointerDown) {
  17288. _this.onPointerDown(evt, pickResult);
  17289. }
  17290. if (_this.onPointerObservable.hasObservers()) {
  17291. var type = PointerEventTypes.POINTERDOWN;
  17292. var pi = new PointerInfo(type, evt, pickResult);
  17293. _this.onPointerObservable.notifyObservers(pi, type);
  17294. }
  17295. // Sprites
  17296. _this._pickedDownSprite = null;
  17297. if (_this.spriteManagers.length > 0) {
  17298. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17299. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  17300. if (pickResult.pickedSprite.actionManager) {
  17301. _this._pickedDownSprite = pickResult.pickedSprite;
  17302. switch (evt.button) {
  17303. case 0:
  17304. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17305. break;
  17306. case 1:
  17307. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17308. break;
  17309. case 2:
  17310. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17311. break;
  17312. }
  17313. if (pickResult.pickedSprite.actionManager) {
  17314. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17315. }
  17316. }
  17317. }
  17318. }
  17319. };
  17320. this._onPointerUp = function (evt) {
  17321. _this._isButtonPressed = false;
  17322. _this._pickedUpMesh = null;
  17323. _this._meshPickProceed = false;
  17324. _this._updatePointerPosition(evt);
  17325. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  17326. // PreObservable support
  17327. if (this.onPrePointerObservable.hasObservers()) {
  17328. if (!clickInfo.ignore) {
  17329. if (!clickInfo.hasSwiped) {
  17330. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  17331. var type = PointerEventTypes.POINTERTAP;
  17332. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17333. this.onPrePointerObservable.notifyObservers(pi, type);
  17334. if (pi.skipOnPointerObservable) {
  17335. return;
  17336. }
  17337. }
  17338. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  17339. var type = PointerEventTypes.POINTERDOUBLETAP;
  17340. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17341. this.onPrePointerObservable.notifyObservers(pi, type);
  17342. if (pi.skipOnPointerObservable) {
  17343. return;
  17344. }
  17345. }
  17346. }
  17347. }
  17348. else {
  17349. var type = PointerEventTypes.POINTERUP;
  17350. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17351. this.onPrePointerObservable.notifyObservers(pi, type);
  17352. if (pi.skipOnPointerObservable) {
  17353. return;
  17354. }
  17355. }
  17356. }
  17357. if (!this.cameraToUseForPointers && !this.activeCamera) {
  17358. return;
  17359. }
  17360. if (!this.pointerUpPredicate) {
  17361. this.pointerUpPredicate = function (mesh) {
  17362. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  17363. };
  17364. }
  17365. // Meshes
  17366. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  17367. this._initActionManager(null, clickInfo);
  17368. }
  17369. if (!pickResult) {
  17370. pickResult = this._currentPickResult;
  17371. }
  17372. if (pickResult && pickResult && pickResult.pickedMesh) {
  17373. this._pickedUpMesh = pickResult.pickedMesh;
  17374. if (this._pickedDownMesh === this._pickedUpMesh) {
  17375. if (this.onPointerPick) {
  17376. this.onPointerPick(evt, pickResult);
  17377. }
  17378. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  17379. var type = PointerEventTypes.POINTERPICK;
  17380. var pi = new PointerInfo(type, evt, pickResult);
  17381. this.onPointerObservable.notifyObservers(pi, type);
  17382. }
  17383. }
  17384. if (pickResult.pickedMesh.actionManager) {
  17385. if (clickInfo.ignore) {
  17386. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17387. }
  17388. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  17389. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17390. }
  17391. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17392. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17393. }
  17394. }
  17395. }
  17396. if (this._pickedDownMesh &&
  17397. this._pickedDownMesh.actionManager &&
  17398. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  17399. this._pickedDownMesh !== this._pickedUpMesh) {
  17400. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  17401. }
  17402. if (this.onPointerUp) {
  17403. this.onPointerUp(evt, pickResult);
  17404. }
  17405. if (this.onPointerObservable.hasObservers()) {
  17406. if (!clickInfo.ignore) {
  17407. if (!clickInfo.hasSwiped) {
  17408. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  17409. var type = PointerEventTypes.POINTERTAP;
  17410. var pi = new PointerInfo(type, evt, pickResult);
  17411. this.onPointerObservable.notifyObservers(pi, type);
  17412. }
  17413. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  17414. var type = PointerEventTypes.POINTERDOUBLETAP;
  17415. var pi = new PointerInfo(type, evt, pickResult);
  17416. this.onPointerObservable.notifyObservers(pi, type);
  17417. }
  17418. }
  17419. }
  17420. else {
  17421. var type = PointerEventTypes.POINTERUP;
  17422. var pi = new PointerInfo(type, evt, pickResult);
  17423. this.onPointerObservable.notifyObservers(pi, type);
  17424. }
  17425. }
  17426. // Sprites
  17427. if (this.spriteManagers.length > 0) {
  17428. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  17429. if (pickResult.hit && pickResult.pickedSprite) {
  17430. if (pickResult.pickedSprite.actionManager) {
  17431. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  17432. if (pickResult.pickedSprite.actionManager) {
  17433. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  17434. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  17435. }
  17436. }
  17437. }
  17438. }
  17439. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  17440. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  17441. }
  17442. }
  17443. this._previousPickResult = this._currentPickResult;
  17444. }).bind(_this));
  17445. };
  17446. this._onKeyDown = function (evt) {
  17447. if (_this.actionManager) {
  17448. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17449. }
  17450. };
  17451. this._onKeyUp = function (evt) {
  17452. if (_this.actionManager) {
  17453. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17454. }
  17455. };
  17456. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17457. var canvas = this._engine.getRenderingCanvas();
  17458. if (attachMove) {
  17459. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  17460. // Wheel
  17461. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  17462. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  17463. }
  17464. if (attachDown) {
  17465. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  17466. }
  17467. if (attachUp) {
  17468. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  17469. }
  17470. canvas.tabIndex = 1;
  17471. canvas.addEventListener("keydown", this._onKeyDown, false);
  17472. canvas.addEventListener("keyup", this._onKeyUp, false);
  17473. };
  17474. Scene.prototype.detachControl = function () {
  17475. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17476. var canvas = this._engine.getRenderingCanvas();
  17477. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  17478. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  17479. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  17480. // Wheel
  17481. canvas.removeEventListener('mousewheel', this._onPointerMove);
  17482. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  17483. canvas.removeEventListener("keydown", this._onKeyDown);
  17484. canvas.removeEventListener("keyup", this._onKeyUp);
  17485. };
  17486. // Ready
  17487. Scene.prototype.isReady = function () {
  17488. if (this._pendingData.length > 0) {
  17489. return false;
  17490. }
  17491. var index;
  17492. // Geometries
  17493. for (index = 0; index < this._geometries.length; index++) {
  17494. var geometry = this._geometries[index];
  17495. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17496. return false;
  17497. }
  17498. }
  17499. // Meshes
  17500. for (index = 0; index < this.meshes.length; index++) {
  17501. var mesh = this.meshes[index];
  17502. if (!mesh.isEnabled()) {
  17503. continue;
  17504. }
  17505. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  17506. continue;
  17507. }
  17508. if (!mesh.isReady()) {
  17509. return false;
  17510. }
  17511. var mat = mesh.material;
  17512. if (mat) {
  17513. if (!mat.isReady(mesh)) {
  17514. return false;
  17515. }
  17516. }
  17517. }
  17518. return true;
  17519. };
  17520. Scene.prototype.resetCachedMaterial = function () {
  17521. this._cachedMaterial = null;
  17522. this._cachedEffect = null;
  17523. this._cachedVisibility = null;
  17524. };
  17525. Scene.prototype.registerBeforeRender = function (func) {
  17526. this.onBeforeRenderObservable.add(func);
  17527. };
  17528. Scene.prototype.unregisterBeforeRender = function (func) {
  17529. this.onBeforeRenderObservable.removeCallback(func);
  17530. };
  17531. Scene.prototype.registerAfterRender = function (func) {
  17532. this.onAfterRenderObservable.add(func);
  17533. };
  17534. Scene.prototype.unregisterAfterRender = function (func) {
  17535. this.onAfterRenderObservable.removeCallback(func);
  17536. };
  17537. Scene.prototype._addPendingData = function (data) {
  17538. this._pendingData.push(data);
  17539. };
  17540. Scene.prototype._removePendingData = function (data) {
  17541. var index = this._pendingData.indexOf(data);
  17542. if (index !== -1) {
  17543. this._pendingData.splice(index, 1);
  17544. }
  17545. };
  17546. Scene.prototype.getWaitingItemsCount = function () {
  17547. return this._pendingData.length;
  17548. };
  17549. /**
  17550. * Registers a function to be executed when the scene is ready.
  17551. * @param {Function} func - the function to be executed.
  17552. */
  17553. Scene.prototype.executeWhenReady = function (func) {
  17554. var _this = this;
  17555. this.onReadyObservable.add(func);
  17556. if (this._executeWhenReadyTimeoutId !== -1) {
  17557. return;
  17558. }
  17559. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17560. _this._checkIsReady();
  17561. }, 150);
  17562. };
  17563. Scene.prototype._checkIsReady = function () {
  17564. var _this = this;
  17565. if (this.isReady()) {
  17566. this.onReadyObservable.notifyObservers(this);
  17567. this.onReadyObservable.clear();
  17568. this._executeWhenReadyTimeoutId = -1;
  17569. return;
  17570. }
  17571. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17572. _this._checkIsReady();
  17573. }, 150);
  17574. };
  17575. // Animations
  17576. /**
  17577. * Will start the animation sequence of a given target
  17578. * @param target - the target
  17579. * @param {number} from - from which frame should animation start
  17580. * @param {number} to - till which frame should animation run.
  17581. * @param {boolean} [loop] - should the animation loop
  17582. * @param {number} [speedRatio] - the speed in which to run the animation
  17583. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  17584. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  17585. * Returns {BABYLON.Animatable} the animatable object created for this animation
  17586. * See BABYLON.Animatable
  17587. */
  17588. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  17589. if (speedRatio === void 0) { speedRatio = 1.0; }
  17590. if (from > to && speedRatio > 0) {
  17591. speedRatio *= -1;
  17592. }
  17593. this.stopAnimation(target);
  17594. if (!animatable) {
  17595. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  17596. }
  17597. // Local animations
  17598. if (target.animations) {
  17599. animatable.appendAnimations(target, target.animations);
  17600. }
  17601. // Children animations
  17602. if (target.getAnimatables) {
  17603. var animatables = target.getAnimatables();
  17604. for (var index = 0; index < animatables.length; index++) {
  17605. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  17606. }
  17607. }
  17608. animatable.reset();
  17609. return animatable;
  17610. };
  17611. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  17612. if (speedRatio === undefined) {
  17613. speedRatio = 1.0;
  17614. }
  17615. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  17616. return animatable;
  17617. };
  17618. Scene.prototype.getAnimatableByTarget = function (target) {
  17619. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17620. if (this._activeAnimatables[index].target === target) {
  17621. return this._activeAnimatables[index];
  17622. }
  17623. }
  17624. return null;
  17625. };
  17626. Object.defineProperty(Scene.prototype, "Animatables", {
  17627. get: function () {
  17628. return this._activeAnimatables;
  17629. },
  17630. enumerable: true,
  17631. configurable: true
  17632. });
  17633. /**
  17634. * Will stop the animation of the given target
  17635. * @param target - the target
  17636. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  17637. * @see beginAnimation
  17638. */
  17639. Scene.prototype.stopAnimation = function (target, animationName) {
  17640. var animatable = this.getAnimatableByTarget(target);
  17641. if (animatable) {
  17642. animatable.stop(animationName);
  17643. }
  17644. };
  17645. Scene.prototype._animate = function () {
  17646. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  17647. return;
  17648. }
  17649. // Getting time
  17650. var now = BABYLON.Tools.Now;
  17651. if (!this._animationTimeLast) {
  17652. if (this._pendingData.length > 0) {
  17653. return;
  17654. }
  17655. this._animationTimeLast = now;
  17656. }
  17657. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  17658. this._animationTime += deltaTime;
  17659. this._animationTimeLast = now;
  17660. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17661. this._activeAnimatables[index]._animate(this._animationTime);
  17662. }
  17663. };
  17664. // Matrix
  17665. Scene.prototype.getViewMatrix = function () {
  17666. return this._viewMatrix;
  17667. };
  17668. Scene.prototype.getProjectionMatrix = function () {
  17669. return this._projectionMatrix;
  17670. };
  17671. Scene.prototype.getTransformMatrix = function () {
  17672. return this._transformMatrix;
  17673. };
  17674. Scene.prototype.setTransformMatrix = function (view, projection) {
  17675. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  17676. return;
  17677. }
  17678. this._viewUpdateFlag = view.updateFlag;
  17679. this._projectionUpdateFlag = projection.updateFlag;
  17680. this._viewMatrix = view;
  17681. this._projectionMatrix = projection;
  17682. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  17683. // Update frustum
  17684. if (!this._frustumPlanes) {
  17685. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  17686. }
  17687. else {
  17688. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  17689. }
  17690. if (this._sceneUbo.useUbo) {
  17691. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  17692. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  17693. this._sceneUbo.update();
  17694. }
  17695. };
  17696. Scene.prototype.getSceneUniformBuffer = function () {
  17697. return this._sceneUbo;
  17698. };
  17699. // Methods
  17700. Scene.prototype.getUniqueId = function () {
  17701. var result = this._uniqueIdCounter;
  17702. this._uniqueIdCounter++;
  17703. return result;
  17704. };
  17705. Scene.prototype.addMesh = function (newMesh) {
  17706. newMesh.uniqueId = this.getUniqueId();
  17707. var position = this.meshes.push(newMesh);
  17708. //notify the collision coordinator
  17709. if (this.collisionCoordinator) {
  17710. this.collisionCoordinator.onMeshAdded(newMesh);
  17711. }
  17712. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  17713. };
  17714. Scene.prototype.removeMesh = function (toRemove) {
  17715. var index = this.meshes.indexOf(toRemove);
  17716. if (index !== -1) {
  17717. // Remove from the scene if mesh found
  17718. this.meshes.splice(index, 1);
  17719. }
  17720. //notify the collision coordinator
  17721. if (this.collisionCoordinator) {
  17722. this.collisionCoordinator.onMeshRemoved(toRemove);
  17723. }
  17724. this.onMeshRemovedObservable.notifyObservers(toRemove);
  17725. return index;
  17726. };
  17727. Scene.prototype.removeSkeleton = function (toRemove) {
  17728. var index = this.skeletons.indexOf(toRemove);
  17729. if (index !== -1) {
  17730. // Remove from the scene if found
  17731. this.skeletons.splice(index, 1);
  17732. }
  17733. return index;
  17734. };
  17735. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  17736. var index = this.morphTargetManagers.indexOf(toRemove);
  17737. if (index !== -1) {
  17738. // Remove from the scene if found
  17739. this.morphTargetManagers.splice(index, 1);
  17740. }
  17741. return index;
  17742. };
  17743. Scene.prototype.removeLight = function (toRemove) {
  17744. var index = this.lights.indexOf(toRemove);
  17745. if (index !== -1) {
  17746. // Remove from the scene if mesh found
  17747. this.lights.splice(index, 1);
  17748. this.sortLightsByPriority();
  17749. }
  17750. this.onLightRemovedObservable.notifyObservers(toRemove);
  17751. return index;
  17752. };
  17753. Scene.prototype.removeCamera = function (toRemove) {
  17754. var index = this.cameras.indexOf(toRemove);
  17755. if (index !== -1) {
  17756. // Remove from the scene if mesh found
  17757. this.cameras.splice(index, 1);
  17758. }
  17759. // Remove from activeCameras
  17760. var index2 = this.activeCameras.indexOf(toRemove);
  17761. if (index2 !== -1) {
  17762. // Remove from the scene if mesh found
  17763. this.activeCameras.splice(index2, 1);
  17764. }
  17765. // Reset the activeCamera
  17766. if (this.activeCamera === toRemove) {
  17767. if (this.cameras.length > 0) {
  17768. this.activeCamera = this.cameras[0];
  17769. }
  17770. else {
  17771. this.activeCamera = null;
  17772. }
  17773. }
  17774. this.onCameraRemovedObservable.notifyObservers(toRemove);
  17775. return index;
  17776. };
  17777. Scene.prototype.addLight = function (newLight) {
  17778. newLight.uniqueId = this.getUniqueId();
  17779. this.lights.push(newLight);
  17780. this.sortLightsByPriority();
  17781. this.onNewLightAddedObservable.notifyObservers(newLight);
  17782. };
  17783. Scene.prototype.sortLightsByPriority = function () {
  17784. if (this.requireLightSorting) {
  17785. this.lights.sort(BABYLON.Light.compareLightsPriority);
  17786. }
  17787. };
  17788. Scene.prototype.addCamera = function (newCamera) {
  17789. newCamera.uniqueId = this.getUniqueId();
  17790. var position = this.cameras.push(newCamera);
  17791. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  17792. };
  17793. /**
  17794. * Switch active camera
  17795. * @param {Camera} newCamera - new active camera
  17796. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  17797. */
  17798. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  17799. if (attachControl === void 0) { attachControl = true; }
  17800. var canvas = this._engine.getRenderingCanvas();
  17801. this.activeCamera.detachControl(canvas);
  17802. this.activeCamera = newCamera;
  17803. if (attachControl) {
  17804. newCamera.attachControl(canvas);
  17805. }
  17806. };
  17807. /**
  17808. * sets the active camera of the scene using its ID
  17809. * @param {string} id - the camera's ID
  17810. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17811. * @see activeCamera
  17812. */
  17813. Scene.prototype.setActiveCameraByID = function (id) {
  17814. var camera = this.getCameraByID(id);
  17815. if (camera) {
  17816. this.activeCamera = camera;
  17817. return camera;
  17818. }
  17819. return null;
  17820. };
  17821. /**
  17822. * sets the active camera of the scene using its name
  17823. * @param {string} name - the camera's name
  17824. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17825. * @see activeCamera
  17826. */
  17827. Scene.prototype.setActiveCameraByName = function (name) {
  17828. var camera = this.getCameraByName(name);
  17829. if (camera) {
  17830. this.activeCamera = camera;
  17831. return camera;
  17832. }
  17833. return null;
  17834. };
  17835. /**
  17836. * get a material using its id
  17837. * @param {string} the material's ID
  17838. * @return {BABYLON.Material|null} the material or null if none found.
  17839. */
  17840. Scene.prototype.getMaterialByID = function (id) {
  17841. for (var index = 0; index < this.materials.length; index++) {
  17842. if (this.materials[index].id === id) {
  17843. return this.materials[index];
  17844. }
  17845. }
  17846. return null;
  17847. };
  17848. /**
  17849. * get a material using its name
  17850. * @param {string} the material's name
  17851. * @return {BABYLON.Material|null} the material or null if none found.
  17852. */
  17853. Scene.prototype.getMaterialByName = function (name) {
  17854. for (var index = 0; index < this.materials.length; index++) {
  17855. if (this.materials[index].name === name) {
  17856. return this.materials[index];
  17857. }
  17858. }
  17859. return null;
  17860. };
  17861. Scene.prototype.getLensFlareSystemByName = function (name) {
  17862. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17863. if (this.lensFlareSystems[index].name === name) {
  17864. return this.lensFlareSystems[index];
  17865. }
  17866. }
  17867. return null;
  17868. };
  17869. Scene.prototype.getLensFlareSystemByID = function (id) {
  17870. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17871. if (this.lensFlareSystems[index].id === id) {
  17872. return this.lensFlareSystems[index];
  17873. }
  17874. }
  17875. return null;
  17876. };
  17877. Scene.prototype.getCameraByID = function (id) {
  17878. for (var index = 0; index < this.cameras.length; index++) {
  17879. if (this.cameras[index].id === id) {
  17880. return this.cameras[index];
  17881. }
  17882. }
  17883. return null;
  17884. };
  17885. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  17886. for (var index = 0; index < this.cameras.length; index++) {
  17887. if (this.cameras[index].uniqueId === uniqueId) {
  17888. return this.cameras[index];
  17889. }
  17890. }
  17891. return null;
  17892. };
  17893. /**
  17894. * get a camera using its name
  17895. * @param {string} the camera's name
  17896. * @return {BABYLON.Camera|null} the camera or null if none found.
  17897. */
  17898. Scene.prototype.getCameraByName = function (name) {
  17899. for (var index = 0; index < this.cameras.length; index++) {
  17900. if (this.cameras[index].name === name) {
  17901. return this.cameras[index];
  17902. }
  17903. }
  17904. return null;
  17905. };
  17906. /**
  17907. * get a bone using its id
  17908. * @param {string} the bone's id
  17909. * @return {BABYLON.Bone|null} the bone or null if not found
  17910. */
  17911. Scene.prototype.getBoneByID = function (id) {
  17912. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17913. var skeleton = this.skeletons[skeletonIndex];
  17914. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17915. if (skeleton.bones[boneIndex].id === id) {
  17916. return skeleton.bones[boneIndex];
  17917. }
  17918. }
  17919. }
  17920. return null;
  17921. };
  17922. /**
  17923. * get a bone using its id
  17924. * @param {string} the bone's name
  17925. * @return {BABYLON.Bone|null} the bone or null if not found
  17926. */
  17927. Scene.prototype.getBoneByName = function (name) {
  17928. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17929. var skeleton = this.skeletons[skeletonIndex];
  17930. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17931. if (skeleton.bones[boneIndex].name === name) {
  17932. return skeleton.bones[boneIndex];
  17933. }
  17934. }
  17935. }
  17936. return null;
  17937. };
  17938. /**
  17939. * get a light node using its name
  17940. * @param {string} the light's name
  17941. * @return {BABYLON.Light|null} the light or null if none found.
  17942. */
  17943. Scene.prototype.getLightByName = function (name) {
  17944. for (var index = 0; index < this.lights.length; index++) {
  17945. if (this.lights[index].name === name) {
  17946. return this.lights[index];
  17947. }
  17948. }
  17949. return null;
  17950. };
  17951. /**
  17952. * get a light node using its ID
  17953. * @param {string} the light's id
  17954. * @return {BABYLON.Light|null} the light or null if none found.
  17955. */
  17956. Scene.prototype.getLightByID = function (id) {
  17957. for (var index = 0; index < this.lights.length; index++) {
  17958. if (this.lights[index].id === id) {
  17959. return this.lights[index];
  17960. }
  17961. }
  17962. return null;
  17963. };
  17964. /**
  17965. * get a light node using its scene-generated unique ID
  17966. * @param {number} the light's unique id
  17967. * @return {BABYLON.Light|null} the light or null if none found.
  17968. */
  17969. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  17970. for (var index = 0; index < this.lights.length; index++) {
  17971. if (this.lights[index].uniqueId === uniqueId) {
  17972. return this.lights[index];
  17973. }
  17974. }
  17975. return null;
  17976. };
  17977. /**
  17978. * get a particle system by id
  17979. * @param id {number} the particle system id
  17980. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  17981. */
  17982. Scene.prototype.getParticleSystemByID = function (id) {
  17983. for (var index = 0; index < this.particleSystems.length; index++) {
  17984. if (this.particleSystems[index].id === id) {
  17985. return this.particleSystems[index];
  17986. }
  17987. }
  17988. return null;
  17989. };
  17990. /**
  17991. * get a geometry using its ID
  17992. * @param {string} the geometry's id
  17993. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  17994. */
  17995. Scene.prototype.getGeometryByID = function (id) {
  17996. for (var index = 0; index < this._geometries.length; index++) {
  17997. if (this._geometries[index].id === id) {
  17998. return this._geometries[index];
  17999. }
  18000. }
  18001. return null;
  18002. };
  18003. /**
  18004. * add a new geometry to this scene.
  18005. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  18006. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  18007. * @return {boolean} was the geometry added or not
  18008. */
  18009. Scene.prototype.pushGeometry = function (geometry, force) {
  18010. if (!force && this.getGeometryByID(geometry.id)) {
  18011. return false;
  18012. }
  18013. this._geometries.push(geometry);
  18014. //notify the collision coordinator
  18015. if (this.collisionCoordinator) {
  18016. this.collisionCoordinator.onGeometryAdded(geometry);
  18017. }
  18018. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  18019. return true;
  18020. };
  18021. /**
  18022. * Removes an existing geometry
  18023. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  18024. * @return {boolean} was the geometry removed or not
  18025. */
  18026. Scene.prototype.removeGeometry = function (geometry) {
  18027. var index = this._geometries.indexOf(geometry);
  18028. if (index > -1) {
  18029. this._geometries.splice(index, 1);
  18030. //notify the collision coordinator
  18031. if (this.collisionCoordinator) {
  18032. this.collisionCoordinator.onGeometryDeleted(geometry);
  18033. }
  18034. this.onGeometryRemovedObservable.notifyObservers(geometry);
  18035. return true;
  18036. }
  18037. return false;
  18038. };
  18039. Scene.prototype.getGeometries = function () {
  18040. return this._geometries;
  18041. };
  18042. /**
  18043. * Get the first added mesh found of a given ID
  18044. * @param {string} id - the id to search for
  18045. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18046. */
  18047. Scene.prototype.getMeshByID = function (id) {
  18048. for (var index = 0; index < this.meshes.length; index++) {
  18049. if (this.meshes[index].id === id) {
  18050. return this.meshes[index];
  18051. }
  18052. }
  18053. return null;
  18054. };
  18055. Scene.prototype.getMeshesByID = function (id) {
  18056. return this.meshes.filter(function (m) {
  18057. return m.id === id;
  18058. });
  18059. };
  18060. /**
  18061. * Get a mesh with its auto-generated unique id
  18062. * @param {number} uniqueId - the unique id to search for
  18063. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18064. */
  18065. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  18066. for (var index = 0; index < this.meshes.length; index++) {
  18067. if (this.meshes[index].uniqueId === uniqueId) {
  18068. return this.meshes[index];
  18069. }
  18070. }
  18071. return null;
  18072. };
  18073. /**
  18074. * Get a the last added mesh found of a given ID
  18075. * @param {string} id - the id to search for
  18076. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18077. */
  18078. Scene.prototype.getLastMeshByID = function (id) {
  18079. for (var index = this.meshes.length - 1; index >= 0; index--) {
  18080. if (this.meshes[index].id === id) {
  18081. return this.meshes[index];
  18082. }
  18083. }
  18084. return null;
  18085. };
  18086. /**
  18087. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  18088. * @param {string} id - the id to search for
  18089. * @return {BABYLON.Node|null} the node found or null if not found at all.
  18090. */
  18091. Scene.prototype.getLastEntryByID = function (id) {
  18092. var index;
  18093. for (index = this.meshes.length - 1; index >= 0; index--) {
  18094. if (this.meshes[index].id === id) {
  18095. return this.meshes[index];
  18096. }
  18097. }
  18098. for (index = this.cameras.length - 1; index >= 0; index--) {
  18099. if (this.cameras[index].id === id) {
  18100. return this.cameras[index];
  18101. }
  18102. }
  18103. for (index = this.lights.length - 1; index >= 0; index--) {
  18104. if (this.lights[index].id === id) {
  18105. return this.lights[index];
  18106. }
  18107. }
  18108. return null;
  18109. };
  18110. Scene.prototype.getNodeByID = function (id) {
  18111. var mesh = this.getMeshByID(id);
  18112. if (mesh) {
  18113. return mesh;
  18114. }
  18115. var light = this.getLightByID(id);
  18116. if (light) {
  18117. return light;
  18118. }
  18119. var camera = this.getCameraByID(id);
  18120. if (camera) {
  18121. return camera;
  18122. }
  18123. var bone = this.getBoneByID(id);
  18124. return bone;
  18125. };
  18126. Scene.prototype.getNodeByName = function (name) {
  18127. var mesh = this.getMeshByName(name);
  18128. if (mesh) {
  18129. return mesh;
  18130. }
  18131. var light = this.getLightByName(name);
  18132. if (light) {
  18133. return light;
  18134. }
  18135. var camera = this.getCameraByName(name);
  18136. if (camera) {
  18137. return camera;
  18138. }
  18139. var bone = this.getBoneByName(name);
  18140. return bone;
  18141. };
  18142. Scene.prototype.getMeshByName = function (name) {
  18143. for (var index = 0; index < this.meshes.length; index++) {
  18144. if (this.meshes[index].name === name) {
  18145. return this.meshes[index];
  18146. }
  18147. }
  18148. return null;
  18149. };
  18150. Scene.prototype.getSoundByName = function (name) {
  18151. var index;
  18152. if (BABYLON.AudioEngine) {
  18153. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  18154. if (this.mainSoundTrack.soundCollection[index].name === name) {
  18155. return this.mainSoundTrack.soundCollection[index];
  18156. }
  18157. }
  18158. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  18159. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  18160. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  18161. return this.soundTracks[sdIndex].soundCollection[index];
  18162. }
  18163. }
  18164. }
  18165. }
  18166. return null;
  18167. };
  18168. Scene.prototype.getLastSkeletonByID = function (id) {
  18169. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  18170. if (this.skeletons[index].id === id) {
  18171. return this.skeletons[index];
  18172. }
  18173. }
  18174. return null;
  18175. };
  18176. Scene.prototype.getSkeletonById = function (id) {
  18177. for (var index = 0; index < this.skeletons.length; index++) {
  18178. if (this.skeletons[index].id === id) {
  18179. return this.skeletons[index];
  18180. }
  18181. }
  18182. return null;
  18183. };
  18184. Scene.prototype.getSkeletonByName = function (name) {
  18185. for (var index = 0; index < this.skeletons.length; index++) {
  18186. if (this.skeletons[index].name === name) {
  18187. return this.skeletons[index];
  18188. }
  18189. }
  18190. return null;
  18191. };
  18192. Scene.prototype.getMorphTargetManagerById = function (id) {
  18193. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  18194. if (this.morphTargetManagers[index].uniqueId === id) {
  18195. return this.morphTargetManagers[index];
  18196. }
  18197. }
  18198. return null;
  18199. };
  18200. Scene.prototype.isActiveMesh = function (mesh) {
  18201. return (this._activeMeshes.indexOf(mesh) !== -1);
  18202. };
  18203. /**
  18204. * Return a the first highlight layer of the scene with a given name.
  18205. * @param name The name of the highlight layer to look for.
  18206. * @return The highlight layer if found otherwise null.
  18207. */
  18208. Scene.prototype.getHighlightLayerByName = function (name) {
  18209. for (var index = 0; index < this.highlightLayers.length; index++) {
  18210. if (this.highlightLayers[index].name === name) {
  18211. return this.highlightLayers[index];
  18212. }
  18213. }
  18214. return null;
  18215. };
  18216. Object.defineProperty(Scene.prototype, "uid", {
  18217. /**
  18218. * Return a unique id as a string which can serve as an identifier for the scene
  18219. */
  18220. get: function () {
  18221. if (!this._uid) {
  18222. this._uid = BABYLON.Tools.RandomId();
  18223. }
  18224. return this._uid;
  18225. },
  18226. enumerable: true,
  18227. configurable: true
  18228. });
  18229. /**
  18230. * Add an externaly attached data from its key.
  18231. * This method call will fail and return false, if such key already exists.
  18232. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  18233. * @param key the unique key that identifies the data
  18234. * @param data the data object to associate to the key for this Engine instance
  18235. * @return true if no such key were already present and the data was added successfully, false otherwise
  18236. */
  18237. Scene.prototype.addExternalData = function (key, data) {
  18238. if (!this._externalData) {
  18239. this._externalData = new BABYLON.StringDictionary();
  18240. }
  18241. return this._externalData.add(key, data);
  18242. };
  18243. /**
  18244. * Get an externaly attached data from its key
  18245. * @param key the unique key that identifies the data
  18246. * @return the associated data, if present (can be null), or undefined if not present
  18247. */
  18248. Scene.prototype.getExternalData = function (key) {
  18249. if (!this._externalData) {
  18250. return null;
  18251. }
  18252. return this._externalData.get(key);
  18253. };
  18254. /**
  18255. * Get an externaly attached data from its key, create it using a factory if it's not already present
  18256. * @param key the unique key that identifies the data
  18257. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  18258. * @return the associated data, can be null if the factory returned null.
  18259. */
  18260. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  18261. if (!this._externalData) {
  18262. this._externalData = new BABYLON.StringDictionary();
  18263. }
  18264. return this._externalData.getOrAddWithFactory(key, factory);
  18265. };
  18266. /**
  18267. * Remove an externaly attached data from the Engine instance
  18268. * @param key the unique key that identifies the data
  18269. * @return true if the data was successfully removed, false if it doesn't exist
  18270. */
  18271. Scene.prototype.removeExternalData = function (key) {
  18272. return this._externalData.remove(key);
  18273. };
  18274. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  18275. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  18276. var material = subMesh.getMaterial();
  18277. if (mesh.showSubMeshesBoundingBox) {
  18278. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  18279. }
  18280. if (material) {
  18281. // Render targets
  18282. if (material.getRenderTargetTextures) {
  18283. if (this._processedMaterials.indexOf(material) === -1) {
  18284. this._processedMaterials.push(material);
  18285. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  18286. }
  18287. }
  18288. // Dispatch
  18289. this._activeIndices.addCount(subMesh.indexCount, false);
  18290. this._renderingManager.dispatch(subMesh);
  18291. }
  18292. }
  18293. };
  18294. Scene.prototype._isInIntermediateRendering = function () {
  18295. return this._intermediateRendering;
  18296. };
  18297. Scene.prototype._evaluateActiveMeshes = function () {
  18298. this.activeCamera._activeMeshes.reset();
  18299. this._activeMeshes.reset();
  18300. this._renderingManager.reset();
  18301. this._processedMaterials.reset();
  18302. this._activeParticleSystems.reset();
  18303. this._activeSkeletons.reset();
  18304. this._softwareSkinnedMeshes.reset();
  18305. if (this._boundingBoxRenderer) {
  18306. this._boundingBoxRenderer.reset();
  18307. }
  18308. // Meshes
  18309. var meshes;
  18310. var len;
  18311. if (this._selectionOctree) {
  18312. var selection = this._selectionOctree.select(this._frustumPlanes);
  18313. meshes = selection.data;
  18314. len = selection.length;
  18315. }
  18316. else {
  18317. len = this.meshes.length;
  18318. meshes = this.meshes;
  18319. }
  18320. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  18321. var mesh = meshes[meshIndex];
  18322. if (mesh.isBlocked) {
  18323. continue;
  18324. }
  18325. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  18326. if (!mesh.isReady() || !mesh.isEnabled()) {
  18327. continue;
  18328. }
  18329. mesh.computeWorldMatrix();
  18330. // Intersections
  18331. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  18332. this._meshesForIntersections.pushNoDuplicate(mesh);
  18333. }
  18334. // Switch to current LOD
  18335. var meshLOD = mesh.getLOD(this.activeCamera);
  18336. if (!meshLOD) {
  18337. continue;
  18338. }
  18339. mesh._preActivate();
  18340. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  18341. this._activeMeshes.push(mesh);
  18342. this.activeCamera._activeMeshes.push(mesh);
  18343. mesh._activate(this._renderId);
  18344. if (meshLOD !== mesh) {
  18345. meshLOD._activate(this._renderId);
  18346. }
  18347. this._activeMesh(mesh, meshLOD);
  18348. }
  18349. }
  18350. // Particle systems
  18351. this._particlesDuration.beginMonitoring();
  18352. var beforeParticlesDate = BABYLON.Tools.Now;
  18353. if (this.particlesEnabled) {
  18354. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  18355. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  18356. var particleSystem = this.particleSystems[particleIndex];
  18357. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  18358. continue;
  18359. }
  18360. var emitter = particleSystem.emitter;
  18361. if (!emitter.position || emitter.isEnabled()) {
  18362. this._activeParticleSystems.push(particleSystem);
  18363. particleSystem.animate();
  18364. this._renderingManager.dispatchParticles(particleSystem);
  18365. }
  18366. }
  18367. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  18368. }
  18369. this._particlesDuration.endMonitoring(false);
  18370. };
  18371. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  18372. if (mesh.skeleton && this.skeletonsEnabled) {
  18373. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  18374. mesh.skeleton.prepare();
  18375. }
  18376. if (!mesh.computeBonesUsingShaders) {
  18377. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  18378. }
  18379. }
  18380. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  18381. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  18382. }
  18383. if (mesh && mesh.subMeshes) {
  18384. // Submeshes Octrees
  18385. var len;
  18386. var subMeshes;
  18387. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  18388. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  18389. len = intersections.length;
  18390. subMeshes = intersections.data;
  18391. }
  18392. else {
  18393. subMeshes = mesh.subMeshes;
  18394. len = subMeshes.length;
  18395. }
  18396. for (var subIndex = 0; subIndex < len; subIndex++) {
  18397. var subMesh = subMeshes[subIndex];
  18398. this._evaluateSubMesh(subMesh, mesh);
  18399. }
  18400. }
  18401. };
  18402. Scene.prototype.updateTransformMatrix = function (force) {
  18403. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  18404. };
  18405. Scene.prototype._renderForCamera = function (camera) {
  18406. var engine = this._engine;
  18407. var startTime = BABYLON.Tools.Now;
  18408. this.activeCamera = camera;
  18409. if (!this.activeCamera)
  18410. throw new Error("Active camera not set");
  18411. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18412. // Viewport
  18413. engine.setViewport(this.activeCamera.viewport);
  18414. // Camera
  18415. this.resetCachedMaterial();
  18416. this._renderId++;
  18417. this.updateTransformMatrix();
  18418. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  18419. // Meshes
  18420. this._evaluateActiveMeshesDuration.beginMonitoring();
  18421. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  18422. this._evaluateActiveMeshes();
  18423. this._evaluateActiveMeshesDuration.endMonitoring(false);
  18424. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  18425. // Software skinning
  18426. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  18427. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  18428. mesh.applySkeleton(mesh.skeleton);
  18429. }
  18430. // Render targets
  18431. this._renderTargetsDuration.beginMonitoring();
  18432. var needsRestoreFrameBuffer = false;
  18433. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18434. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  18435. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  18436. }
  18437. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  18438. this._intermediateRendering = true;
  18439. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18440. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  18441. var renderTarget = this._renderTargets.data[renderIndex];
  18442. if (renderTarget._shouldRender()) {
  18443. this._renderId++;
  18444. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  18445. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  18446. }
  18447. }
  18448. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18449. this._intermediateRendering = false;
  18450. this._renderId++;
  18451. needsRestoreFrameBuffer = true; // Restore back buffer
  18452. }
  18453. // Render HighlightLayer Texture
  18454. var stencilState = this._engine.getStencilBuffer();
  18455. var renderhighlights = false;
  18456. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  18457. this._intermediateRendering = true;
  18458. for (var i = 0; i < this.highlightLayers.length; i++) {
  18459. var highlightLayer = this.highlightLayers[i];
  18460. if (highlightLayer.shouldRender() &&
  18461. (!highlightLayer.camera ||
  18462. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  18463. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  18464. renderhighlights = true;
  18465. var renderTarget = highlightLayer._mainTexture;
  18466. if (renderTarget._shouldRender()) {
  18467. this._renderId++;
  18468. renderTarget.render(false, false);
  18469. needsRestoreFrameBuffer = true;
  18470. }
  18471. }
  18472. }
  18473. this._intermediateRendering = false;
  18474. this._renderId++;
  18475. }
  18476. if (needsRestoreFrameBuffer) {
  18477. engine.restoreDefaultFramebuffer(); // Restore back buffer
  18478. }
  18479. this._renderTargetsDuration.endMonitoring(false);
  18480. // Prepare Frame
  18481. this.postProcessManager._prepareFrame();
  18482. this._renderDuration.beginMonitoring();
  18483. // Backgrounds
  18484. var layerIndex;
  18485. var layer;
  18486. if (this.layers.length) {
  18487. engine.setDepthBuffer(false);
  18488. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18489. layer = this.layers[layerIndex];
  18490. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  18491. layer.render();
  18492. }
  18493. }
  18494. engine.setDepthBuffer(true);
  18495. }
  18496. // Render
  18497. BABYLON.Tools.StartPerformanceCounter("Main render");
  18498. // Activate HighlightLayer stencil
  18499. if (renderhighlights) {
  18500. this._engine.setStencilBuffer(true);
  18501. }
  18502. this._renderingManager.render(null, null, true, true);
  18503. // Restore HighlightLayer stencil
  18504. if (renderhighlights) {
  18505. this._engine.setStencilBuffer(stencilState);
  18506. }
  18507. BABYLON.Tools.EndPerformanceCounter("Main render");
  18508. // Bounding boxes
  18509. if (this._boundingBoxRenderer) {
  18510. this._boundingBoxRenderer.render();
  18511. }
  18512. // Lens flares
  18513. if (this.lensFlaresEnabled) {
  18514. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18515. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  18516. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  18517. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  18518. lensFlareSystem.render();
  18519. }
  18520. }
  18521. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18522. }
  18523. // Foregrounds
  18524. if (this.layers.length) {
  18525. engine.setDepthBuffer(false);
  18526. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18527. layer = this.layers[layerIndex];
  18528. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  18529. layer.render();
  18530. }
  18531. }
  18532. engine.setDepthBuffer(true);
  18533. }
  18534. // Highlight Layer
  18535. if (renderhighlights) {
  18536. engine.setDepthBuffer(false);
  18537. for (var i = 0; i < this.highlightLayers.length; i++) {
  18538. if (this.highlightLayers[i].shouldRender()) {
  18539. this.highlightLayers[i].render();
  18540. }
  18541. }
  18542. engine.setDepthBuffer(true);
  18543. }
  18544. this._renderDuration.endMonitoring(false);
  18545. // Finalize frame
  18546. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  18547. // Update camera
  18548. this.activeCamera._updateFromScene();
  18549. // Reset some special arrays
  18550. this._renderTargets.reset();
  18551. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  18552. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18553. };
  18554. Scene.prototype._processSubCameras = function (camera) {
  18555. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  18556. this._renderForCamera(camera);
  18557. return;
  18558. }
  18559. // rig cameras
  18560. for (var index = 0; index < camera._rigCameras.length; index++) {
  18561. this._renderForCamera(camera._rigCameras[index]);
  18562. }
  18563. this.activeCamera = camera;
  18564. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  18565. // Update camera
  18566. this.activeCamera._updateFromScene();
  18567. };
  18568. Scene.prototype._checkIntersections = function () {
  18569. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  18570. var sourceMesh = this._meshesForIntersections.data[index];
  18571. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  18572. var action = sourceMesh.actionManager.actions[actionIndex];
  18573. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18574. var parameters = action.getTriggerParameter();
  18575. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  18576. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  18577. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  18578. if (areIntersecting && currentIntersectionInProgress === -1) {
  18579. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  18580. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18581. sourceMesh._intersectionsInProgress.push(otherMesh);
  18582. }
  18583. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18584. sourceMesh._intersectionsInProgress.push(otherMesh);
  18585. }
  18586. }
  18587. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  18588. //They intersected, and now they don't.
  18589. //is this trigger an exit trigger? execute an event.
  18590. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18591. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18592. }
  18593. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  18594. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18595. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  18596. }
  18597. }
  18598. }
  18599. }
  18600. }
  18601. };
  18602. Scene.prototype.render = function () {
  18603. if (this.isDisposed) {
  18604. return;
  18605. }
  18606. this._lastFrameDuration.beginMonitoring();
  18607. this._particlesDuration.fetchNewFrame();
  18608. this._spritesDuration.fetchNewFrame();
  18609. this._activeParticles.fetchNewFrame();
  18610. this._renderDuration.fetchNewFrame();
  18611. this._renderTargetsDuration.fetchNewFrame();
  18612. this._evaluateActiveMeshesDuration.fetchNewFrame();
  18613. this._totalVertices.fetchNewFrame();
  18614. this._activeIndices.fetchNewFrame();
  18615. this._activeBones.fetchNewFrame();
  18616. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  18617. this._meshesForIntersections.reset();
  18618. this.resetCachedMaterial();
  18619. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  18620. // Actions
  18621. if (this.actionManager) {
  18622. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  18623. }
  18624. //Simplification Queue
  18625. if (this.simplificationQueue && !this.simplificationQueue.running) {
  18626. this.simplificationQueue.executeNext();
  18627. }
  18628. if (this._engine.isDeterministicLockStep()) {
  18629. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) / 1000;
  18630. var defaultTimeStep = (60.0 / 1000.0);
  18631. if (this._physicsEngine) {
  18632. defaultTimeStep = this._physicsEngine.getTimeStep();
  18633. }
  18634. var maxSubSteps = this._engine.getLockstepMaxSteps();
  18635. this._timeAccumulator += deltaTime;
  18636. // compute the amount of fixed steps we should have taken since the last step
  18637. var internalSteps = Math.floor(this._timeAccumulator / defaultTimeStep);
  18638. internalSteps = Math.min(internalSteps, maxSubSteps);
  18639. for (this._currentInternalStep = 0; this._currentInternalStep < internalSteps; this._currentInternalStep++) {
  18640. this.onBeforeStepObservable.notifyObservers(this);
  18641. // Animations
  18642. this._animationRatio = defaultTimeStep * (60.0 / 1000.0);
  18643. this._animate();
  18644. // Physics
  18645. if (this._physicsEngine) {
  18646. BABYLON.Tools.StartPerformanceCounter("Physics");
  18647. this._physicsEngine._step(defaultTimeStep);
  18648. BABYLON.Tools.EndPerformanceCounter("Physics");
  18649. }
  18650. this._timeAccumulator -= defaultTimeStep;
  18651. this.onAfterStepObservable.notifyObservers(this);
  18652. this._currentStepId++;
  18653. if ((internalSteps > 1) && (this._currentInternalStep != internalSteps - 1)) {
  18654. // Q: can this be optimized by putting some code in the afterStep callback?
  18655. // I had to put this code here, otherwise mesh attached to bones of another mesh skeleton,
  18656. // would return incorrect positions for internal stepIds (non-rendered steps)
  18657. this._evaluateActiveMeshes();
  18658. }
  18659. }
  18660. }
  18661. else {
  18662. // Animations
  18663. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  18664. this._animationRatio = deltaTime * (60.0 / 1000.0);
  18665. this._animate();
  18666. // Physics
  18667. if (this._physicsEngine) {
  18668. BABYLON.Tools.StartPerformanceCounter("Physics");
  18669. this._physicsEngine._step(deltaTime / 1000.0);
  18670. BABYLON.Tools.EndPerformanceCounter("Physics");
  18671. }
  18672. }
  18673. // Before render
  18674. this.onBeforeRenderObservable.notifyObservers(this);
  18675. // Customs render targets
  18676. this._renderTargetsDuration.beginMonitoring();
  18677. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18678. var engine = this.getEngine();
  18679. var currentActiveCamera = this.activeCamera;
  18680. if (this.renderTargetsEnabled) {
  18681. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18682. this._intermediateRendering = true;
  18683. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  18684. var renderTarget = this.customRenderTargets[customIndex];
  18685. if (renderTarget._shouldRender()) {
  18686. this._renderId++;
  18687. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  18688. if (!this.activeCamera)
  18689. throw new Error("Active camera not set");
  18690. // Viewport
  18691. engine.setViewport(this.activeCamera.viewport);
  18692. // Camera
  18693. this.updateTransformMatrix();
  18694. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  18695. }
  18696. }
  18697. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18698. this._intermediateRendering = false;
  18699. this._renderId++;
  18700. }
  18701. // Restore back buffer
  18702. if (this.customRenderTargets.length > 0) {
  18703. engine.restoreDefaultFramebuffer();
  18704. }
  18705. this._renderTargetsDuration.endMonitoring();
  18706. this.activeCamera = currentActiveCamera;
  18707. // Procedural textures
  18708. if (this.proceduralTexturesEnabled) {
  18709. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18710. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  18711. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  18712. if (proceduralTexture._shouldRender()) {
  18713. proceduralTexture.render();
  18714. }
  18715. }
  18716. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18717. }
  18718. // Clear
  18719. if (this.autoClearDepthAndStencil || this.autoClear) {
  18720. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  18721. }
  18722. // Shadows
  18723. if (this.shadowsEnabled) {
  18724. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  18725. var light = this.lights[lightIndex];
  18726. var shadowGenerator = light.getShadowGenerator();
  18727. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  18728. var shadowMap = shadowGenerator.getShadowMap();
  18729. if (shadowMap.getScene().textures.indexOf(shadowMap) !== -1) {
  18730. this._renderTargets.push(shadowMap);
  18731. }
  18732. }
  18733. }
  18734. }
  18735. // Depth renderer
  18736. if (this._depthRenderer) {
  18737. this._renderTargets.push(this._depthRenderer.getDepthMap());
  18738. }
  18739. // Geometry renderer
  18740. if (this._geometryBufferRenderer) {
  18741. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  18742. }
  18743. // RenderPipeline
  18744. if (this._postProcessRenderPipelineManager) {
  18745. this._postProcessRenderPipelineManager.update();
  18746. }
  18747. // Multi-cameras?
  18748. if (this.activeCameras.length > 0) {
  18749. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  18750. if (cameraIndex > 0) {
  18751. this._engine.clear(null, false, true, true);
  18752. }
  18753. this._processSubCameras(this.activeCameras[cameraIndex]);
  18754. }
  18755. }
  18756. else {
  18757. if (!this.activeCamera) {
  18758. throw new Error("No camera defined");
  18759. }
  18760. this._processSubCameras(this.activeCamera);
  18761. }
  18762. // Intersection checks
  18763. this._checkIntersections();
  18764. // Update the audio listener attached to the camera
  18765. if (BABYLON.AudioEngine) {
  18766. this._updateAudioParameters();
  18767. }
  18768. // After render
  18769. if (this.afterRender) {
  18770. this.afterRender();
  18771. }
  18772. this.onAfterRenderObservable.notifyObservers(this);
  18773. // Cleaning
  18774. for (var index = 0; index < this._toBeDisposed.length; index++) {
  18775. this._toBeDisposed.data[index].dispose();
  18776. this._toBeDisposed[index] = null;
  18777. }
  18778. this._toBeDisposed.reset();
  18779. if (this.dumpNextRenderTargets) {
  18780. this.dumpNextRenderTargets = false;
  18781. }
  18782. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  18783. this._lastFrameDuration.endMonitoring();
  18784. this._totalMeshesCounter.addCount(this.meshes.length, true);
  18785. this._totalLightsCounter.addCount(this.lights.length, true);
  18786. this._totalMaterialsCounter.addCount(this.materials.length, true);
  18787. this._totalTexturesCounter.addCount(this.textures.length, true);
  18788. this._activeBones.addCount(0, true);
  18789. this._activeIndices.addCount(0, true);
  18790. this._activeParticles.addCount(0, true);
  18791. };
  18792. Scene.prototype._updateAudioParameters = function () {
  18793. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  18794. return;
  18795. }
  18796. var listeningCamera;
  18797. var audioEngine = BABYLON.Engine.audioEngine;
  18798. if (this.activeCameras.length > 0) {
  18799. listeningCamera = this.activeCameras[0];
  18800. }
  18801. else {
  18802. listeningCamera = this.activeCamera;
  18803. }
  18804. if (listeningCamera && audioEngine.canUseWebAudio) {
  18805. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  18806. // for VR cameras
  18807. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  18808. listeningCamera = listeningCamera.rigCameras[0];
  18809. }
  18810. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  18811. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  18812. cameraDirection.normalize();
  18813. // To avoid some errors on GearVR
  18814. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  18815. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  18816. }
  18817. var i;
  18818. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18819. var sound = this.mainSoundTrack.soundCollection[i];
  18820. if (sound.useCustomAttenuation) {
  18821. sound.updateDistanceFromListener();
  18822. }
  18823. }
  18824. for (i = 0; i < this.soundTracks.length; i++) {
  18825. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18826. sound = this.soundTracks[i].soundCollection[j];
  18827. if (sound.useCustomAttenuation) {
  18828. sound.updateDistanceFromListener();
  18829. }
  18830. }
  18831. }
  18832. }
  18833. };
  18834. Object.defineProperty(Scene.prototype, "audioEnabled", {
  18835. // Audio
  18836. get: function () {
  18837. return this._audioEnabled;
  18838. },
  18839. set: function (value) {
  18840. this._audioEnabled = value;
  18841. if (BABYLON.AudioEngine) {
  18842. if (this._audioEnabled) {
  18843. this._enableAudio();
  18844. }
  18845. else {
  18846. this._disableAudio();
  18847. }
  18848. }
  18849. },
  18850. enumerable: true,
  18851. configurable: true
  18852. });
  18853. Scene.prototype._disableAudio = function () {
  18854. var i;
  18855. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18856. this.mainSoundTrack.soundCollection[i].pause();
  18857. }
  18858. for (i = 0; i < this.soundTracks.length; i++) {
  18859. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18860. this.soundTracks[i].soundCollection[j].pause();
  18861. }
  18862. }
  18863. };
  18864. Scene.prototype._enableAudio = function () {
  18865. var i;
  18866. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18867. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  18868. this.mainSoundTrack.soundCollection[i].play();
  18869. }
  18870. }
  18871. for (i = 0; i < this.soundTracks.length; i++) {
  18872. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18873. if (this.soundTracks[i].soundCollection[j].isPaused) {
  18874. this.soundTracks[i].soundCollection[j].play();
  18875. }
  18876. }
  18877. }
  18878. };
  18879. Object.defineProperty(Scene.prototype, "headphone", {
  18880. get: function () {
  18881. return this._headphone;
  18882. },
  18883. set: function (value) {
  18884. this._headphone = value;
  18885. if (BABYLON.AudioEngine) {
  18886. if (this._headphone) {
  18887. this._switchAudioModeForHeadphones();
  18888. }
  18889. else {
  18890. this._switchAudioModeForNormalSpeakers();
  18891. }
  18892. }
  18893. },
  18894. enumerable: true,
  18895. configurable: true
  18896. });
  18897. Scene.prototype._switchAudioModeForHeadphones = function () {
  18898. this.mainSoundTrack.switchPanningModelToHRTF();
  18899. for (var i = 0; i < this.soundTracks.length; i++) {
  18900. this.soundTracks[i].switchPanningModelToHRTF();
  18901. }
  18902. };
  18903. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  18904. this.mainSoundTrack.switchPanningModelToEqualPower();
  18905. for (var i = 0; i < this.soundTracks.length; i++) {
  18906. this.soundTracks[i].switchPanningModelToEqualPower();
  18907. }
  18908. };
  18909. Scene.prototype.enableDepthRenderer = function () {
  18910. if (this._depthRenderer) {
  18911. return this._depthRenderer;
  18912. }
  18913. this._depthRenderer = new BABYLON.DepthRenderer(this);
  18914. return this._depthRenderer;
  18915. };
  18916. Scene.prototype.disableDepthRenderer = function () {
  18917. if (!this._depthRenderer) {
  18918. return;
  18919. }
  18920. this._depthRenderer.dispose();
  18921. this._depthRenderer = null;
  18922. };
  18923. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  18924. if (ratio === void 0) { ratio = 1; }
  18925. if (this._geometryBufferRenderer) {
  18926. return this._geometryBufferRenderer;
  18927. }
  18928. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  18929. if (!this._geometryBufferRenderer.isSupported) {
  18930. this._geometryBufferRenderer = null;
  18931. }
  18932. return this._geometryBufferRenderer;
  18933. };
  18934. Scene.prototype.disableGeometryBufferRenderer = function () {
  18935. if (!this._geometryBufferRenderer) {
  18936. return;
  18937. }
  18938. this._geometryBufferRenderer.dispose();
  18939. this._geometryBufferRenderer = null;
  18940. };
  18941. Scene.prototype.freezeMaterials = function () {
  18942. for (var i = 0; i < this.materials.length; i++) {
  18943. this.materials[i].freeze();
  18944. }
  18945. };
  18946. Scene.prototype.unfreezeMaterials = function () {
  18947. for (var i = 0; i < this.materials.length; i++) {
  18948. this.materials[i].unfreeze();
  18949. }
  18950. };
  18951. Scene.prototype.dispose = function () {
  18952. this.beforeRender = null;
  18953. this.afterRender = null;
  18954. this.skeletons = [];
  18955. this.morphTargetManagers = [];
  18956. this.importedMeshesFiles = new Array();
  18957. this.resetCachedMaterial();
  18958. if (this._depthRenderer) {
  18959. this._depthRenderer.dispose();
  18960. }
  18961. if (this._gamepadManager) {
  18962. this._gamepadManager.dispose();
  18963. this._gamepadManager = null;
  18964. }
  18965. // Smart arrays
  18966. if (this.activeCamera) {
  18967. this.activeCamera._activeMeshes.dispose();
  18968. this.activeCamera = null;
  18969. }
  18970. this._activeMeshes.dispose();
  18971. this._renderingManager.dispose();
  18972. this._processedMaterials.dispose();
  18973. this._activeParticleSystems.dispose();
  18974. this._activeSkeletons.dispose();
  18975. this._softwareSkinnedMeshes.dispose();
  18976. this._renderTargets.dispose();
  18977. if (this._boundingBoxRenderer) {
  18978. this._boundingBoxRenderer.dispose();
  18979. }
  18980. this._meshesForIntersections.dispose();
  18981. this._toBeDisposed.dispose();
  18982. // Debug layer
  18983. if (this._debugLayer) {
  18984. this._debugLayer.hide();
  18985. }
  18986. // Events
  18987. this.onDisposeObservable.notifyObservers(this);
  18988. this.onDisposeObservable.clear();
  18989. this.onBeforeRenderObservable.clear();
  18990. this.onAfterRenderObservable.clear();
  18991. this.detachControl();
  18992. // Release sounds & sounds tracks
  18993. if (BABYLON.AudioEngine) {
  18994. this.disposeSounds();
  18995. }
  18996. // VR Helper
  18997. if (this.VRHelper) {
  18998. this.VRHelper.dispose();
  18999. }
  19000. // Detach cameras
  19001. var canvas = this._engine.getRenderingCanvas();
  19002. var index;
  19003. for (index = 0; index < this.cameras.length; index++) {
  19004. this.cameras[index].detachControl(canvas);
  19005. }
  19006. // Release lights
  19007. while (this.lights.length) {
  19008. this.lights[0].dispose();
  19009. }
  19010. // Release meshes
  19011. while (this.meshes.length) {
  19012. this.meshes[0].dispose(true);
  19013. }
  19014. // Release cameras
  19015. while (this.cameras.length) {
  19016. this.cameras[0].dispose();
  19017. }
  19018. // Release materials
  19019. if (this.defaultMaterial) {
  19020. this.defaultMaterial.dispose();
  19021. }
  19022. while (this.multiMaterials.length) {
  19023. this.multiMaterials[0].dispose();
  19024. }
  19025. while (this.materials.length) {
  19026. this.materials[0].dispose();
  19027. }
  19028. // Release particles
  19029. while (this.particleSystems.length) {
  19030. this.particleSystems[0].dispose();
  19031. }
  19032. // Release sprites
  19033. while (this.spriteManagers.length) {
  19034. this.spriteManagers[0].dispose();
  19035. }
  19036. // Release postProcesses
  19037. while (this.postProcesses.length) {
  19038. this.postProcesses[0].dispose();
  19039. }
  19040. // Release layers
  19041. while (this.layers.length) {
  19042. this.layers[0].dispose();
  19043. }
  19044. while (this.highlightLayers.length) {
  19045. this.highlightLayers[0].dispose();
  19046. }
  19047. // Release textures
  19048. while (this.textures.length) {
  19049. this.textures[0].dispose();
  19050. }
  19051. // Release UBO
  19052. this._sceneUbo.dispose();
  19053. // Post-processes
  19054. this.postProcessManager.dispose();
  19055. if (this._postProcessRenderPipelineManager) {
  19056. this._postProcessRenderPipelineManager.dispose();
  19057. }
  19058. // Physics
  19059. if (this._physicsEngine) {
  19060. this.disablePhysicsEngine();
  19061. }
  19062. // Remove from engine
  19063. index = this._engine.scenes.indexOf(this);
  19064. if (index > -1) {
  19065. this._engine.scenes.splice(index, 1);
  19066. }
  19067. this._engine.wipeCaches();
  19068. this._engine = null;
  19069. this.defaultMaterial = null;
  19070. this.multiMaterials = null;
  19071. this.materials = null;
  19072. };
  19073. Object.defineProperty(Scene.prototype, "isDisposed", {
  19074. get: function () {
  19075. return !this._engine;
  19076. },
  19077. enumerable: true,
  19078. configurable: true
  19079. });
  19080. // Release sounds & sounds tracks
  19081. Scene.prototype.disposeSounds = function () {
  19082. this.mainSoundTrack.dispose();
  19083. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  19084. this.soundTracks[scIndex].dispose();
  19085. }
  19086. };
  19087. // Octrees
  19088. Scene.prototype.getWorldExtends = function () {
  19089. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19090. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  19091. for (var index = 0; index < this.meshes.length; index++) {
  19092. var mesh = this.meshes[index];
  19093. mesh.computeWorldMatrix(true);
  19094. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  19095. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  19096. BABYLON.Tools.CheckExtends(minBox, min, max);
  19097. BABYLON.Tools.CheckExtends(maxBox, min, max);
  19098. }
  19099. return {
  19100. min: min,
  19101. max: max
  19102. };
  19103. };
  19104. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  19105. if (maxCapacity === void 0) { maxCapacity = 64; }
  19106. if (maxDepth === void 0) { maxDepth = 2; }
  19107. if (!this._selectionOctree) {
  19108. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  19109. }
  19110. var worldExtends = this.getWorldExtends();
  19111. // Update octree
  19112. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  19113. return this._selectionOctree;
  19114. };
  19115. // Picking
  19116. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  19117. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  19118. var engine = this._engine;
  19119. if (!camera) {
  19120. if (!this.activeCamera)
  19121. throw new Error("Active camera not set");
  19122. camera = this.activeCamera;
  19123. }
  19124. var cameraViewport = camera.viewport;
  19125. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19126. // Moving coordinates to local viewport world
  19127. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19128. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19129. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  19130. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  19131. };
  19132. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  19133. if (!BABYLON.PickingInfo) {
  19134. return null;
  19135. }
  19136. var engine = this._engine;
  19137. if (!camera) {
  19138. if (!this.activeCamera)
  19139. throw new Error("Active camera not set");
  19140. camera = this.activeCamera;
  19141. }
  19142. var cameraViewport = camera.viewport;
  19143. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19144. var identity = BABYLON.Matrix.Identity();
  19145. // Moving coordinates to local viewport world
  19146. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19147. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19148. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  19149. };
  19150. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  19151. if (!BABYLON.PickingInfo) {
  19152. return null;
  19153. }
  19154. var pickingInfo = null;
  19155. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19156. var mesh = this.meshes[meshIndex];
  19157. if (predicate) {
  19158. if (!predicate(mesh)) {
  19159. continue;
  19160. }
  19161. }
  19162. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19163. continue;
  19164. }
  19165. var world = mesh.getWorldMatrix();
  19166. var ray = rayFunction(world);
  19167. var result = mesh.intersects(ray, fastCheck);
  19168. if (!result || !result.hit)
  19169. continue;
  19170. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19171. continue;
  19172. pickingInfo = result;
  19173. if (fastCheck) {
  19174. break;
  19175. }
  19176. }
  19177. return pickingInfo || new BABYLON.PickingInfo();
  19178. };
  19179. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  19180. if (!BABYLON.PickingInfo) {
  19181. return null;
  19182. }
  19183. var pickingInfos = new Array();
  19184. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19185. var mesh = this.meshes[meshIndex];
  19186. if (predicate) {
  19187. if (!predicate(mesh)) {
  19188. continue;
  19189. }
  19190. }
  19191. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19192. continue;
  19193. }
  19194. var world = mesh.getWorldMatrix();
  19195. var ray = rayFunction(world);
  19196. var result = mesh.intersects(ray, false);
  19197. if (!result || !result.hit)
  19198. continue;
  19199. pickingInfos.push(result);
  19200. }
  19201. return pickingInfos;
  19202. };
  19203. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  19204. if (!BABYLON.PickingInfo) {
  19205. return null;
  19206. }
  19207. var pickingInfo = null;
  19208. camera = camera || this.activeCamera;
  19209. if (this.spriteManagers.length > 0) {
  19210. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  19211. var spriteManager = this.spriteManagers[spriteIndex];
  19212. if (!spriteManager.isPickable) {
  19213. continue;
  19214. }
  19215. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  19216. if (!result || !result.hit)
  19217. continue;
  19218. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19219. continue;
  19220. pickingInfo = result;
  19221. if (fastCheck) {
  19222. break;
  19223. }
  19224. }
  19225. }
  19226. return pickingInfo || new BABYLON.PickingInfo();
  19227. };
  19228. /** Launch a ray to try to pick a mesh in the scene
  19229. * @param x position on screen
  19230. * @param y position on screen
  19231. * @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
  19232. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19233. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19234. */
  19235. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  19236. var _this = this;
  19237. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  19238. };
  19239. /** Launch a ray to try to pick a sprite in the scene
  19240. * @param x position on screen
  19241. * @param y position on screen
  19242. * @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
  19243. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19244. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19245. */
  19246. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  19247. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  19248. };
  19249. /** Use the given ray to pick a mesh in the scene
  19250. * @param ray The ray to use to pick meshes
  19251. * @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
  19252. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19253. */
  19254. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  19255. var _this = this;
  19256. return this._internalPick(function (world) {
  19257. if (!_this._pickWithRayInverseMatrix) {
  19258. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19259. }
  19260. world.invertToRef(_this._pickWithRayInverseMatrix);
  19261. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19262. }, predicate, fastCheck);
  19263. };
  19264. /**
  19265. * Launch a ray to try to pick a mesh in the scene
  19266. * @param x X position on screen
  19267. * @param y Y position on screen
  19268. * @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
  19269. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19270. */
  19271. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  19272. var _this = this;
  19273. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  19274. };
  19275. /**
  19276. * Launch a ray to try to pick a mesh in the scene
  19277. * @param ray Ray to use
  19278. * @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
  19279. */
  19280. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  19281. var _this = this;
  19282. return this._internalMultiPick(function (world) {
  19283. if (!_this._pickWithRayInverseMatrix) {
  19284. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19285. }
  19286. world.invertToRef(_this._pickWithRayInverseMatrix);
  19287. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19288. }, predicate);
  19289. };
  19290. Scene.prototype.setPointerOverMesh = function (mesh) {
  19291. if (this._pointerOverMesh === mesh) {
  19292. return;
  19293. }
  19294. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19295. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19296. }
  19297. this._pointerOverMesh = mesh;
  19298. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19299. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19300. }
  19301. };
  19302. Scene.prototype.getPointerOverMesh = function () {
  19303. return this._pointerOverMesh;
  19304. };
  19305. Scene.prototype.setPointerOverSprite = function (sprite) {
  19306. if (this._pointerOverSprite === sprite) {
  19307. return;
  19308. }
  19309. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19310. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19311. }
  19312. this._pointerOverSprite = sprite;
  19313. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19314. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19315. }
  19316. };
  19317. Scene.prototype.getPointerOverSprite = function () {
  19318. return this._pointerOverSprite;
  19319. };
  19320. // Physics
  19321. Scene.prototype.getPhysicsEngine = function () {
  19322. return this._physicsEngine;
  19323. };
  19324. /**
  19325. * Enables physics to the current scene
  19326. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  19327. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  19328. * @return {boolean} was the physics engine initialized
  19329. */
  19330. Scene.prototype.enablePhysics = function (gravity, plugin) {
  19331. if (this._physicsEngine) {
  19332. return true;
  19333. }
  19334. try {
  19335. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  19336. return true;
  19337. }
  19338. catch (e) {
  19339. BABYLON.Tools.Error(e.message);
  19340. return false;
  19341. }
  19342. };
  19343. Scene.prototype.disablePhysicsEngine = function () {
  19344. if (!this._physicsEngine) {
  19345. return;
  19346. }
  19347. this._physicsEngine.dispose();
  19348. this._physicsEngine = undefined;
  19349. };
  19350. Scene.prototype.isPhysicsEnabled = function () {
  19351. return this._physicsEngine !== undefined;
  19352. };
  19353. Scene.prototype.deleteCompoundImpostor = function (compound) {
  19354. var mesh = compound.parts[0].mesh;
  19355. mesh.physicsImpostor.dispose();
  19356. mesh.physicsImpostor = null;
  19357. };
  19358. // Misc.
  19359. Scene.prototype._rebuildGeometries = function () {
  19360. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  19361. var geometry = _a[_i];
  19362. geometry._rebuild();
  19363. }
  19364. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  19365. var mesh = _c[_b];
  19366. mesh._rebuild();
  19367. }
  19368. if (this.postProcessManager) {
  19369. this.postProcessManager._rebuild();
  19370. }
  19371. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  19372. var layer = _e[_d];
  19373. layer._rebuild();
  19374. }
  19375. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  19376. var highlightLayer = _g[_f];
  19377. highlightLayer._rebuild();
  19378. }
  19379. if (this._boundingBoxRenderer) {
  19380. this._boundingBoxRenderer._rebuild();
  19381. }
  19382. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  19383. var system = _j[_h];
  19384. system.rebuild();
  19385. }
  19386. if (this._postProcessRenderPipelineManager) {
  19387. this._postProcessRenderPipelineManager._rebuild();
  19388. }
  19389. };
  19390. Scene.prototype._rebuildTextures = function () {
  19391. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  19392. var texture = _a[_i];
  19393. texture._rebuild();
  19394. }
  19395. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19396. };
  19397. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  19398. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  19399. if (replace === void 0) { replace = false; }
  19400. if (attachCameraControls === void 0) { attachCameraControls = false; }
  19401. // Dispose existing camera or light in replace mode.
  19402. if (replace) {
  19403. if (this.activeCamera) {
  19404. this.activeCamera.dispose();
  19405. this.activeCamera = null;
  19406. }
  19407. if (this.lights) {
  19408. for (var i = 0; i < this.lights.length; i++) {
  19409. this.lights[i].dispose();
  19410. }
  19411. }
  19412. }
  19413. // Light
  19414. if (this.lights.length === 0) {
  19415. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  19416. }
  19417. // Camera
  19418. if (!this.activeCamera) {
  19419. var worldExtends = this.getWorldExtends();
  19420. var worldSize = worldExtends.max.subtract(worldExtends.min);
  19421. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  19422. var camera;
  19423. var radius = worldSize.length() * 1.5;
  19424. if (createArcRotateCamera) {
  19425. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  19426. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  19427. arcRotateCamera.wheelPrecision = 100 / radius;
  19428. camera = arcRotateCamera;
  19429. }
  19430. else {
  19431. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  19432. freeCamera.setTarget(worldCenter);
  19433. camera = freeCamera;
  19434. }
  19435. camera.minZ = radius * 0.01;
  19436. camera.maxZ = radius * 100;
  19437. camera.speed = radius * 0.2;
  19438. this.activeCamera = camera;
  19439. if (attachCameraControls) {
  19440. camera.attachControl(this.getEngine().getRenderingCanvas());
  19441. }
  19442. }
  19443. };
  19444. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  19445. if (pbr === void 0) { pbr = false; }
  19446. if (scale === void 0) { scale = 1000; }
  19447. if (blur === void 0) { blur = 0; }
  19448. if (environmentTexture) {
  19449. this.environmentTexture = environmentTexture;
  19450. }
  19451. if (!this.environmentTexture) {
  19452. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  19453. return;
  19454. }
  19455. // Skybox
  19456. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  19457. if (pbr) {
  19458. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  19459. hdrSkyboxMaterial.backFaceCulling = false;
  19460. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  19461. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  19462. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  19463. hdrSkyboxMaterial.disableLighting = true;
  19464. hdrSkyboxMaterial.twoSidedLighting = true;
  19465. hdrSkybox.infiniteDistance = true;
  19466. hdrSkybox.material = hdrSkyboxMaterial;
  19467. }
  19468. else {
  19469. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  19470. skyboxMaterial.backFaceCulling = false;
  19471. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  19472. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  19473. skyboxMaterial.disableLighting = true;
  19474. hdrSkybox.infiniteDistance = true;
  19475. hdrSkybox.material = skyboxMaterial;
  19476. }
  19477. return hdrSkybox;
  19478. };
  19479. Scene.prototype.createDefaultVRExperience = function () {
  19480. this.VRHelper = new BABYLON.VRExperienceHelper(this, null);
  19481. };
  19482. // Tags
  19483. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  19484. if (tagsQuery === undefined) {
  19485. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  19486. return list;
  19487. }
  19488. var listByTags = [];
  19489. forEach = forEach || (function (item) { return; });
  19490. for (var i in list) {
  19491. var item = list[i];
  19492. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  19493. listByTags.push(item);
  19494. forEach(item);
  19495. }
  19496. }
  19497. return listByTags;
  19498. };
  19499. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  19500. return this._getByTags(this.meshes, tagsQuery, forEach);
  19501. };
  19502. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  19503. return this._getByTags(this.cameras, tagsQuery, forEach);
  19504. };
  19505. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  19506. return this._getByTags(this.lights, tagsQuery, forEach);
  19507. };
  19508. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  19509. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  19510. };
  19511. /**
  19512. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  19513. * This allowed control for front to back rendering or reversly depending of the special needs.
  19514. *
  19515. * @param renderingGroupId The rendering group id corresponding to its index
  19516. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  19517. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  19518. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  19519. */
  19520. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19521. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19522. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19523. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19524. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  19525. };
  19526. /**
  19527. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19528. *
  19529. * @param renderingGroupId The rendering group id corresponding to its index
  19530. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19531. * @param depth Automatically clears depth between groups if true and autoClear is true.
  19532. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  19533. */
  19534. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  19535. if (depth === void 0) { depth = true; }
  19536. if (stencil === void 0) { stencil = true; }
  19537. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  19538. };
  19539. /**
  19540. * Will flag all materials as dirty to trigger new shader compilation
  19541. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  19542. */
  19543. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  19544. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  19545. var material = _a[_i];
  19546. if (predicate && !predicate(material)) {
  19547. continue;
  19548. }
  19549. material.markAsDirty(flag);
  19550. }
  19551. };
  19552. // Statics
  19553. Scene._FOGMODE_NONE = 0;
  19554. Scene._FOGMODE_EXP = 1;
  19555. Scene._FOGMODE_EXP2 = 2;
  19556. Scene._FOGMODE_LINEAR = 3;
  19557. Scene.MinDeltaTime = 1.0;
  19558. Scene.MaxDeltaTime = 1000.0;
  19559. /** The distance in pixel that you have to move to prevent some events */
  19560. Scene.DragMovementThreshold = 10; // in pixels
  19561. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  19562. Scene.LongPressDelay = 500; // in milliseconds
  19563. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  19564. Scene.DoubleClickDelay = 300; // in milliseconds
  19565. /** If you need to check double click without raising a single click at first click, enable this flag */
  19566. Scene.ExclusiveDoubleClickMode = false;
  19567. return Scene;
  19568. }());
  19569. BABYLON.Scene = Scene;
  19570. })(BABYLON || (BABYLON = {}));
  19571. //# sourceMappingURL=babylon.scene.js.map
  19572. var BABYLON;
  19573. (function (BABYLON) {
  19574. var Buffer = (function () {
  19575. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  19576. if (engine instanceof BABYLON.Mesh) {
  19577. this._engine = engine.getScene().getEngine();
  19578. }
  19579. else {
  19580. this._engine = engine;
  19581. }
  19582. this._updatable = updatable;
  19583. this._data = data;
  19584. this._strideSize = stride;
  19585. if (!postponeInternalCreation) {
  19586. this.create();
  19587. }
  19588. this._instanced = instanced;
  19589. this._instanceDivisor = instanced ? 1 : 0;
  19590. }
  19591. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  19592. // a lot of these parameters are ignored as they are overriden by the buffer
  19593. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  19594. };
  19595. // Properties
  19596. Buffer.prototype.isUpdatable = function () {
  19597. return this._updatable;
  19598. };
  19599. Buffer.prototype.getData = function () {
  19600. return this._data;
  19601. };
  19602. Buffer.prototype.getBuffer = function () {
  19603. return this._buffer;
  19604. };
  19605. Buffer.prototype.getStrideSize = function () {
  19606. return this._strideSize;
  19607. };
  19608. Buffer.prototype.getIsInstanced = function () {
  19609. return this._instanced;
  19610. };
  19611. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  19612. get: function () {
  19613. return this._instanceDivisor;
  19614. },
  19615. set: function (value) {
  19616. this._instanceDivisor = value;
  19617. if (value == 0) {
  19618. this._instanced = false;
  19619. }
  19620. else {
  19621. this._instanced = true;
  19622. }
  19623. },
  19624. enumerable: true,
  19625. configurable: true
  19626. });
  19627. // Methods
  19628. Buffer.prototype.create = function (data) {
  19629. if (!data && this._buffer) {
  19630. return; // nothing to do
  19631. }
  19632. data = data || this._data;
  19633. if (!this._buffer) {
  19634. if (this._updatable) {
  19635. this._buffer = this._engine.createDynamicVertexBuffer(data);
  19636. this._data = data;
  19637. }
  19638. else {
  19639. this._buffer = this._engine.createVertexBuffer(data);
  19640. }
  19641. }
  19642. else if (this._updatable) {
  19643. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  19644. this._data = data;
  19645. }
  19646. };
  19647. Buffer.prototype._rebuild = function () {
  19648. this._buffer = null;
  19649. this.create(this._data);
  19650. };
  19651. Buffer.prototype.update = function (data) {
  19652. this.create(data);
  19653. };
  19654. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  19655. if (!this._buffer) {
  19656. return;
  19657. }
  19658. if (this._updatable) {
  19659. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  19660. this._data = null;
  19661. }
  19662. };
  19663. Buffer.prototype.dispose = function () {
  19664. if (!this._buffer) {
  19665. return;
  19666. }
  19667. if (this._engine._releaseBuffer(this._buffer)) {
  19668. this._buffer = null;
  19669. }
  19670. };
  19671. return Buffer;
  19672. }());
  19673. BABYLON.Buffer = Buffer;
  19674. })(BABYLON || (BABYLON = {}));
  19675. //# sourceMappingURL=babylon.buffer.js.map
  19676. var BABYLON;
  19677. (function (BABYLON) {
  19678. var VertexBuffer = (function () {
  19679. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  19680. if (!stride) {
  19681. // Deduce stride from kind
  19682. switch (kind) {
  19683. case VertexBuffer.PositionKind:
  19684. stride = 3;
  19685. break;
  19686. case VertexBuffer.NormalKind:
  19687. stride = 3;
  19688. break;
  19689. case VertexBuffer.UVKind:
  19690. case VertexBuffer.UV2Kind:
  19691. case VertexBuffer.UV3Kind:
  19692. case VertexBuffer.UV4Kind:
  19693. case VertexBuffer.UV5Kind:
  19694. case VertexBuffer.UV6Kind:
  19695. stride = 2;
  19696. break;
  19697. case VertexBuffer.TangentKind:
  19698. case VertexBuffer.ColorKind:
  19699. stride = 4;
  19700. break;
  19701. case VertexBuffer.MatricesIndicesKind:
  19702. case VertexBuffer.MatricesIndicesExtraKind:
  19703. stride = 4;
  19704. break;
  19705. case VertexBuffer.MatricesWeightsKind:
  19706. case VertexBuffer.MatricesWeightsExtraKind:
  19707. stride = 4;
  19708. break;
  19709. }
  19710. }
  19711. if (data instanceof BABYLON.Buffer) {
  19712. if (!stride) {
  19713. stride = data.getStrideSize();
  19714. }
  19715. this._buffer = data;
  19716. this._ownsBuffer = false;
  19717. }
  19718. else {
  19719. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  19720. this._ownsBuffer = true;
  19721. }
  19722. this._stride = stride;
  19723. this._offset = offset ? offset : 0;
  19724. this._size = size ? size : stride;
  19725. this._kind = kind;
  19726. }
  19727. VertexBuffer.prototype._rebuild = function () {
  19728. if (!this._buffer) {
  19729. return;
  19730. }
  19731. this._buffer._rebuild();
  19732. };
  19733. /**
  19734. * Returns the kind of the VertexBuffer (string).
  19735. */
  19736. VertexBuffer.prototype.getKind = function () {
  19737. return this._kind;
  19738. };
  19739. // Properties
  19740. /**
  19741. * Boolean : is the VertexBuffer updatable ?
  19742. */
  19743. VertexBuffer.prototype.isUpdatable = function () {
  19744. return this._buffer.isUpdatable();
  19745. };
  19746. /**
  19747. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  19748. */
  19749. VertexBuffer.prototype.getData = function () {
  19750. return this._buffer.getData();
  19751. };
  19752. /**
  19753. * Returns the WebGLBuffer associated to the VertexBuffer.
  19754. */
  19755. VertexBuffer.prototype.getBuffer = function () {
  19756. return this._buffer.getBuffer();
  19757. };
  19758. /**
  19759. * Returns the stride of the VertexBuffer (integer).
  19760. */
  19761. VertexBuffer.prototype.getStrideSize = function () {
  19762. return this._stride;
  19763. };
  19764. /**
  19765. * Returns the offset (integer).
  19766. */
  19767. VertexBuffer.prototype.getOffset = function () {
  19768. return this._offset;
  19769. };
  19770. /**
  19771. * Returns the VertexBuffer total size (integer).
  19772. */
  19773. VertexBuffer.prototype.getSize = function () {
  19774. return this._size;
  19775. };
  19776. /**
  19777. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  19778. */
  19779. VertexBuffer.prototype.getIsInstanced = function () {
  19780. return this._buffer.getIsInstanced();
  19781. };
  19782. /**
  19783. * Returns the instancing divisor, zero for non-instanced (integer).
  19784. */
  19785. VertexBuffer.prototype.getInstanceDivisor = function () {
  19786. return this._buffer.instanceDivisor;
  19787. };
  19788. // Methods
  19789. /**
  19790. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  19791. * Returns the created WebGLBuffer.
  19792. */
  19793. VertexBuffer.prototype.create = function (data) {
  19794. return this._buffer.create(data);
  19795. };
  19796. /**
  19797. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  19798. * Returns the updated WebGLBuffer.
  19799. */
  19800. VertexBuffer.prototype.update = function (data) {
  19801. return this._buffer.update(data);
  19802. };
  19803. /**
  19804. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  19805. * Returns the directly updated WebGLBuffer.
  19806. */
  19807. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  19808. return this._buffer.updateDirectly(data, offset);
  19809. };
  19810. /**
  19811. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  19812. */
  19813. VertexBuffer.prototype.dispose = function () {
  19814. if (this._ownsBuffer) {
  19815. this._buffer.dispose();
  19816. }
  19817. };
  19818. Object.defineProperty(VertexBuffer, "PositionKind", {
  19819. get: function () {
  19820. return VertexBuffer._PositionKind;
  19821. },
  19822. enumerable: true,
  19823. configurable: true
  19824. });
  19825. Object.defineProperty(VertexBuffer, "NormalKind", {
  19826. get: function () {
  19827. return VertexBuffer._NormalKind;
  19828. },
  19829. enumerable: true,
  19830. configurable: true
  19831. });
  19832. Object.defineProperty(VertexBuffer, "TangentKind", {
  19833. get: function () {
  19834. return VertexBuffer._TangentKind;
  19835. },
  19836. enumerable: true,
  19837. configurable: true
  19838. });
  19839. Object.defineProperty(VertexBuffer, "UVKind", {
  19840. get: function () {
  19841. return VertexBuffer._UVKind;
  19842. },
  19843. enumerable: true,
  19844. configurable: true
  19845. });
  19846. Object.defineProperty(VertexBuffer, "UV2Kind", {
  19847. get: function () {
  19848. return VertexBuffer._UV2Kind;
  19849. },
  19850. enumerable: true,
  19851. configurable: true
  19852. });
  19853. Object.defineProperty(VertexBuffer, "UV3Kind", {
  19854. get: function () {
  19855. return VertexBuffer._UV3Kind;
  19856. },
  19857. enumerable: true,
  19858. configurable: true
  19859. });
  19860. Object.defineProperty(VertexBuffer, "UV4Kind", {
  19861. get: function () {
  19862. return VertexBuffer._UV4Kind;
  19863. },
  19864. enumerable: true,
  19865. configurable: true
  19866. });
  19867. Object.defineProperty(VertexBuffer, "UV5Kind", {
  19868. get: function () {
  19869. return VertexBuffer._UV5Kind;
  19870. },
  19871. enumerable: true,
  19872. configurable: true
  19873. });
  19874. Object.defineProperty(VertexBuffer, "UV6Kind", {
  19875. get: function () {
  19876. return VertexBuffer._UV6Kind;
  19877. },
  19878. enumerable: true,
  19879. configurable: true
  19880. });
  19881. Object.defineProperty(VertexBuffer, "ColorKind", {
  19882. get: function () {
  19883. return VertexBuffer._ColorKind;
  19884. },
  19885. enumerable: true,
  19886. configurable: true
  19887. });
  19888. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  19889. get: function () {
  19890. return VertexBuffer._MatricesIndicesKind;
  19891. },
  19892. enumerable: true,
  19893. configurable: true
  19894. });
  19895. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  19896. get: function () {
  19897. return VertexBuffer._MatricesWeightsKind;
  19898. },
  19899. enumerable: true,
  19900. configurable: true
  19901. });
  19902. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  19903. get: function () {
  19904. return VertexBuffer._MatricesIndicesExtraKind;
  19905. },
  19906. enumerable: true,
  19907. configurable: true
  19908. });
  19909. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  19910. get: function () {
  19911. return VertexBuffer._MatricesWeightsExtraKind;
  19912. },
  19913. enumerable: true,
  19914. configurable: true
  19915. });
  19916. // Enums
  19917. VertexBuffer._PositionKind = "position";
  19918. VertexBuffer._NormalKind = "normal";
  19919. VertexBuffer._TangentKind = "tangent";
  19920. VertexBuffer._UVKind = "uv";
  19921. VertexBuffer._UV2Kind = "uv2";
  19922. VertexBuffer._UV3Kind = "uv3";
  19923. VertexBuffer._UV4Kind = "uv4";
  19924. VertexBuffer._UV5Kind = "uv5";
  19925. VertexBuffer._UV6Kind = "uv6";
  19926. VertexBuffer._ColorKind = "color";
  19927. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  19928. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  19929. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  19930. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  19931. return VertexBuffer;
  19932. }());
  19933. BABYLON.VertexBuffer = VertexBuffer;
  19934. })(BABYLON || (BABYLON = {}));
  19935. //# sourceMappingURL=babylon.vertexBuffer.js.map
  19936. var BABYLON;
  19937. (function (BABYLON) {
  19938. var InternalTexture = (function () {
  19939. function InternalTexture(engine, dataSource) {
  19940. this.onLoadedObservable = new BABYLON.Observable();
  19941. // Private
  19942. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  19943. this._references = 1;
  19944. this._engine = engine;
  19945. this._dataSource = dataSource;
  19946. this._webGLTexture = engine._createTexture();
  19947. }
  19948. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  19949. get: function () {
  19950. return this._dataSource;
  19951. },
  19952. enumerable: true,
  19953. configurable: true
  19954. });
  19955. InternalTexture.prototype.incrementReferences = function () {
  19956. this._references++;
  19957. };
  19958. InternalTexture.prototype.updateSize = function (width, height) {
  19959. this.width = width;
  19960. this.height = height;
  19961. this._size = width * height;
  19962. this.baseWidth = width;
  19963. this.baseHeight = height;
  19964. };
  19965. InternalTexture.prototype._rebuild = function () {
  19966. var _this = this;
  19967. var proxy;
  19968. this.isReady = false;
  19969. this._cachedCoordinatesMode = null;
  19970. this._cachedWrapU = null;
  19971. this._cachedWrapV = null;
  19972. this._cachedAnisotropicFilteringLevel = null;
  19973. switch (this._dataSource) {
  19974. case InternalTexture.DATASOURCE_TEMP:
  19975. return;
  19976. case InternalTexture.DATASOURCE_URL:
  19977. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  19978. _this.isReady = true;
  19979. }, null, this._buffer, null, this.format);
  19980. proxy._swapAndDie(this);
  19981. return;
  19982. case InternalTexture.DATASOURCE_RAW:
  19983. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  19984. proxy._swapAndDie(this);
  19985. this.isReady = true;
  19986. return;
  19987. case InternalTexture.DATASOURCE_DYNAMIC:
  19988. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  19989. proxy._swapAndDie(this);
  19990. // The engine will make sure to update content so no need to flag it as isReady = true
  19991. return;
  19992. case InternalTexture.DATASOURCE_RENDERTARGET:
  19993. var options = new BABYLON.RenderTargetCreationOptions();
  19994. options.generateDepthBuffer = this._generateDepthBuffer;
  19995. options.generateMipMaps = this.generateMipMaps;
  19996. options.generateStencilBuffer = this._generateStencilBuffer;
  19997. options.samplingMode = this.samplingMode;
  19998. options.type = this.type;
  19999. if (this.isCube) {
  20000. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  20001. }
  20002. else {
  20003. var size = {
  20004. width: this.width,
  20005. height: this.height
  20006. };
  20007. proxy = this._engine.createRenderTargetTexture(size, options);
  20008. }
  20009. proxy._swapAndDie(this);
  20010. this.isReady = true;
  20011. return;
  20012. case InternalTexture.DATASOURCE_CUBE:
  20013. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  20014. _this.isReady = true;
  20015. }, null, this.format, this._extension);
  20016. proxy._swapAndDie(this);
  20017. return;
  20018. case InternalTexture.DATASOURCE_CUBERAW:
  20019. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  20020. proxy._swapAndDie(this);
  20021. this.isReady = true;
  20022. return;
  20023. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  20024. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  20025. proxy._swapAndDie(_this);
  20026. _this.isReady = true;
  20027. }, null, this.format, this._extension);
  20028. return;
  20029. }
  20030. };
  20031. InternalTexture.prototype._swapAndDie = function (target) {
  20032. target._webGLTexture = this._webGLTexture;
  20033. if (this._framebuffer) {
  20034. target._framebuffer = this._framebuffer;
  20035. }
  20036. if (this._depthStencilBuffer) {
  20037. target._depthStencilBuffer = this._depthStencilBuffer;
  20038. }
  20039. if (this._lodTextureHigh) {
  20040. if (target._lodTextureHigh) {
  20041. target._lodTextureHigh.dispose();
  20042. }
  20043. target._lodTextureHigh = this._lodTextureHigh;
  20044. }
  20045. if (this._lodTextureMid) {
  20046. if (target._lodTextureMid) {
  20047. target._lodTextureMid.dispose();
  20048. }
  20049. target._lodTextureMid = this._lodTextureMid;
  20050. }
  20051. if (this._lodTextureLow) {
  20052. if (target._lodTextureLow) {
  20053. target._lodTextureLow.dispose();
  20054. }
  20055. target._lodTextureLow = this._lodTextureLow;
  20056. }
  20057. var cache = this._engine.getLoadedTexturesCache();
  20058. var index = cache.indexOf(this);
  20059. if (index !== -1) {
  20060. cache.splice(index, 1);
  20061. }
  20062. };
  20063. InternalTexture.prototype.dispose = function () {
  20064. if (!this._webGLTexture) {
  20065. return;
  20066. }
  20067. this._references--;
  20068. if (this._references === 0) {
  20069. this._engine._releaseTexture(this);
  20070. this._webGLTexture = null;
  20071. }
  20072. };
  20073. InternalTexture.DATASOURCE_UNKNOWN = 0;
  20074. InternalTexture.DATASOURCE_URL = 1;
  20075. InternalTexture.DATASOURCE_TEMP = 2;
  20076. InternalTexture.DATASOURCE_RAW = 3;
  20077. InternalTexture.DATASOURCE_DYNAMIC = 4;
  20078. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  20079. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  20080. InternalTexture.DATASOURCE_CUBE = 7;
  20081. InternalTexture.DATASOURCE_CUBERAW = 8;
  20082. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  20083. return InternalTexture;
  20084. }());
  20085. BABYLON.InternalTexture = InternalTexture;
  20086. })(BABYLON || (BABYLON = {}));
  20087. //# sourceMappingURL=babylon.internalTexture.js.map
  20088. var BABYLON;
  20089. (function (BABYLON) {
  20090. var BaseTexture = (function () {
  20091. function BaseTexture(scene) {
  20092. this._hasAlpha = false;
  20093. this.getAlphaFromRGB = false;
  20094. this.level = 1;
  20095. this.coordinatesIndex = 0;
  20096. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  20097. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  20098. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  20099. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  20100. this.isCube = false;
  20101. this.gammaSpace = true;
  20102. this.invertZ = false;
  20103. this.lodLevelInAlpha = false;
  20104. this.lodGenerationOffset = 0.0;
  20105. this.lodGenerationScale = 0.8;
  20106. this.isRenderTarget = false;
  20107. this.animations = new Array();
  20108. /**
  20109. * An event triggered when the texture is disposed.
  20110. * @type {BABYLON.Observable}
  20111. */
  20112. this.onDisposeObservable = new BABYLON.Observable();
  20113. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20114. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  20115. this._scene.textures.push(this);
  20116. this._uid = null;
  20117. }
  20118. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  20119. get: function () {
  20120. return this._hasAlpha;
  20121. },
  20122. set: function (value) {
  20123. if (this._hasAlpha === value) {
  20124. return;
  20125. }
  20126. this._hasAlpha = value;
  20127. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20128. },
  20129. enumerable: true,
  20130. configurable: true
  20131. });
  20132. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  20133. get: function () {
  20134. return this._coordinatesMode;
  20135. },
  20136. set: function (value) {
  20137. if (this._coordinatesMode === value) {
  20138. return;
  20139. }
  20140. this._coordinatesMode = value;
  20141. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20142. },
  20143. enumerable: true,
  20144. configurable: true
  20145. });
  20146. Object.defineProperty(BaseTexture.prototype, "uid", {
  20147. get: function () {
  20148. if (!this._uid) {
  20149. this._uid = BABYLON.Tools.RandomId();
  20150. }
  20151. return this._uid;
  20152. },
  20153. enumerable: true,
  20154. configurable: true
  20155. });
  20156. BaseTexture.prototype.toString = function () {
  20157. return this.name;
  20158. };
  20159. BaseTexture.prototype.getClassName = function () {
  20160. return "BaseTexture";
  20161. };
  20162. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  20163. set: function (callback) {
  20164. if (this._onDisposeObserver) {
  20165. this.onDisposeObservable.remove(this._onDisposeObserver);
  20166. }
  20167. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  20168. },
  20169. enumerable: true,
  20170. configurable: true
  20171. });
  20172. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  20173. get: function () {
  20174. return true;
  20175. },
  20176. enumerable: true,
  20177. configurable: true
  20178. });
  20179. BaseTexture.prototype.getScene = function () {
  20180. return this._scene;
  20181. };
  20182. BaseTexture.prototype.getTextureMatrix = function () {
  20183. return null;
  20184. };
  20185. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  20186. return null;
  20187. };
  20188. BaseTexture.prototype.getInternalTexture = function () {
  20189. return this._texture;
  20190. };
  20191. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  20192. return !this.isBlocking || this.isReady();
  20193. };
  20194. BaseTexture.prototype.isReady = function () {
  20195. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20196. this.delayLoad();
  20197. return false;
  20198. }
  20199. if (this._texture) {
  20200. return this._texture.isReady;
  20201. }
  20202. return false;
  20203. };
  20204. BaseTexture.prototype.getSize = function () {
  20205. if (this._texture.width) {
  20206. return new BABYLON.Size(this._texture.width, this._texture.height);
  20207. }
  20208. if (this._texture._size) {
  20209. return new BABYLON.Size(this._texture._size, this._texture._size);
  20210. }
  20211. return BABYLON.Size.Zero();
  20212. };
  20213. BaseTexture.prototype.getBaseSize = function () {
  20214. if (!this.isReady() || !this._texture)
  20215. return BABYLON.Size.Zero();
  20216. if (this._texture._size) {
  20217. return new BABYLON.Size(this._texture._size, this._texture._size);
  20218. }
  20219. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  20220. };
  20221. BaseTexture.prototype.scale = function (ratio) {
  20222. };
  20223. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  20224. get: function () {
  20225. return false;
  20226. },
  20227. enumerable: true,
  20228. configurable: true
  20229. });
  20230. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  20231. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20232. for (var index = 0; index < texturesCache.length; index++) {
  20233. var texturesCacheEntry = texturesCache[index];
  20234. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  20235. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  20236. texturesCacheEntry.incrementReferences();
  20237. return texturesCacheEntry;
  20238. }
  20239. }
  20240. }
  20241. return null;
  20242. };
  20243. BaseTexture.prototype._rebuild = function () {
  20244. };
  20245. BaseTexture.prototype.delayLoad = function () {
  20246. };
  20247. BaseTexture.prototype.clone = function () {
  20248. return null;
  20249. };
  20250. Object.defineProperty(BaseTexture.prototype, "textureType", {
  20251. get: function () {
  20252. if (!this._texture) {
  20253. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  20254. }
  20255. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  20256. },
  20257. enumerable: true,
  20258. configurable: true
  20259. });
  20260. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  20261. get: function () {
  20262. if (!this._texture) {
  20263. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  20264. }
  20265. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  20266. },
  20267. enumerable: true,
  20268. configurable: true
  20269. });
  20270. BaseTexture.prototype.readPixels = function (faceIndex) {
  20271. if (faceIndex === void 0) { faceIndex = 0; }
  20272. if (!this._texture) {
  20273. return null;
  20274. }
  20275. var size = this.getSize();
  20276. var engine = this.getScene().getEngine();
  20277. if (this._texture.isCube) {
  20278. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  20279. }
  20280. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  20281. };
  20282. BaseTexture.prototype.releaseInternalTexture = function () {
  20283. if (this._texture) {
  20284. this._texture.dispose();
  20285. this._texture = null;
  20286. }
  20287. };
  20288. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  20289. get: function () {
  20290. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  20291. return null;
  20292. }
  20293. if (!this._texture._sphericalPolynomial) {
  20294. this._texture._sphericalPolynomial =
  20295. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  20296. }
  20297. return this._texture._sphericalPolynomial;
  20298. },
  20299. set: function (value) {
  20300. if (this._texture) {
  20301. this._texture._sphericalPolynomial = value;
  20302. }
  20303. },
  20304. enumerable: true,
  20305. configurable: true
  20306. });
  20307. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  20308. get: function () {
  20309. if (this._texture) {
  20310. return this._texture._lodTextureHigh;
  20311. }
  20312. return null;
  20313. },
  20314. enumerable: true,
  20315. configurable: true
  20316. });
  20317. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  20318. get: function () {
  20319. if (this._texture) {
  20320. return this._texture._lodTextureMid;
  20321. }
  20322. return null;
  20323. },
  20324. enumerable: true,
  20325. configurable: true
  20326. });
  20327. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  20328. get: function () {
  20329. if (this._texture) {
  20330. return this._texture._lodTextureLow;
  20331. }
  20332. return null;
  20333. },
  20334. enumerable: true,
  20335. configurable: true
  20336. });
  20337. BaseTexture.prototype.dispose = function () {
  20338. // Animations
  20339. this.getScene().stopAnimation(this);
  20340. // Remove from scene
  20341. this._scene._removePendingData(this);
  20342. var index = this._scene.textures.indexOf(this);
  20343. if (index >= 0) {
  20344. this._scene.textures.splice(index, 1);
  20345. }
  20346. if (this._texture === undefined) {
  20347. return;
  20348. }
  20349. // Release
  20350. this.releaseInternalTexture();
  20351. // Callback
  20352. this.onDisposeObservable.notifyObservers(this);
  20353. this.onDisposeObservable.clear();
  20354. };
  20355. BaseTexture.prototype.serialize = function () {
  20356. if (!this.name) {
  20357. return null;
  20358. }
  20359. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20360. // Animations
  20361. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20362. return serializationObject;
  20363. };
  20364. BaseTexture.WhenAllReady = function (textures, callback) {
  20365. var numRemaining = textures.length;
  20366. if (numRemaining === 0) {
  20367. callback();
  20368. return;
  20369. }
  20370. var _loop_1 = function () {
  20371. texture = textures[i];
  20372. if (texture.isReady()) {
  20373. if (--numRemaining === 0) {
  20374. callback();
  20375. }
  20376. }
  20377. else {
  20378. onLoadObservable = texture.onLoadObservable;
  20379. var onLoadCallback_1 = function () {
  20380. onLoadObservable.removeCallback(onLoadCallback_1);
  20381. if (--numRemaining === 0) {
  20382. callback();
  20383. }
  20384. };
  20385. onLoadObservable.add(onLoadCallback_1);
  20386. }
  20387. };
  20388. var texture, onLoadObservable;
  20389. for (var i = 0; i < textures.length; i++) {
  20390. _loop_1();
  20391. }
  20392. };
  20393. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  20394. __decorate([
  20395. BABYLON.serialize()
  20396. ], BaseTexture.prototype, "name", void 0);
  20397. __decorate([
  20398. BABYLON.serialize("hasAlpha")
  20399. ], BaseTexture.prototype, "_hasAlpha", void 0);
  20400. __decorate([
  20401. BABYLON.serialize()
  20402. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  20403. __decorate([
  20404. BABYLON.serialize()
  20405. ], BaseTexture.prototype, "level", void 0);
  20406. __decorate([
  20407. BABYLON.serialize()
  20408. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  20409. __decorate([
  20410. BABYLON.serialize("coordinatesMode")
  20411. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  20412. __decorate([
  20413. BABYLON.serialize()
  20414. ], BaseTexture.prototype, "wrapU", void 0);
  20415. __decorate([
  20416. BABYLON.serialize()
  20417. ], BaseTexture.prototype, "wrapV", void 0);
  20418. __decorate([
  20419. BABYLON.serialize()
  20420. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  20421. __decorate([
  20422. BABYLON.serialize()
  20423. ], BaseTexture.prototype, "isCube", void 0);
  20424. __decorate([
  20425. BABYLON.serialize()
  20426. ], BaseTexture.prototype, "gammaSpace", void 0);
  20427. __decorate([
  20428. BABYLON.serialize()
  20429. ], BaseTexture.prototype, "invertZ", void 0);
  20430. __decorate([
  20431. BABYLON.serialize()
  20432. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  20433. __decorate([
  20434. BABYLON.serialize()
  20435. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  20436. __decorate([
  20437. BABYLON.serialize()
  20438. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  20439. __decorate([
  20440. BABYLON.serialize()
  20441. ], BaseTexture.prototype, "isRenderTarget", void 0);
  20442. return BaseTexture;
  20443. }());
  20444. BABYLON.BaseTexture = BaseTexture;
  20445. })(BABYLON || (BABYLON = {}));
  20446. //# sourceMappingURL=babylon.baseTexture.js.map
  20447. var BABYLON;
  20448. (function (BABYLON) {
  20449. var Texture = (function (_super) {
  20450. __extends(Texture, _super);
  20451. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  20452. if (noMipmap === void 0) { noMipmap = false; }
  20453. if (invertY === void 0) { invertY = true; }
  20454. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20455. if (onLoad === void 0) { onLoad = null; }
  20456. if (onError === void 0) { onError = null; }
  20457. if (buffer === void 0) { buffer = null; }
  20458. if (deleteBuffer === void 0) { deleteBuffer = false; }
  20459. var _this = _super.call(this, scene) || this;
  20460. _this.uOffset = 0;
  20461. _this.vOffset = 0;
  20462. _this.uScale = 1.0;
  20463. _this.vScale = 1.0;
  20464. _this.uAng = 0;
  20465. _this.vAng = 0;
  20466. _this.wAng = 0;
  20467. _this._isBlocking = true;
  20468. _this.name = url;
  20469. _this.url = url;
  20470. _this._noMipmap = noMipmap;
  20471. _this._invertY = invertY;
  20472. _this._samplingMode = samplingMode;
  20473. _this._buffer = buffer;
  20474. _this._deleteBuffer = deleteBuffer;
  20475. _this._format = format;
  20476. scene = _this.getScene();
  20477. var load = function () {
  20478. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  20479. _this.onLoadObservable.notifyObservers(_this);
  20480. }
  20481. if (onLoad) {
  20482. onLoad();
  20483. }
  20484. if (!_this.isBlocking) {
  20485. scene.resetCachedMaterial();
  20486. }
  20487. };
  20488. if (!url) {
  20489. _this._delayedOnLoad = load;
  20490. _this._delayedOnError = onError;
  20491. return _this;
  20492. }
  20493. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  20494. if (!_this._texture) {
  20495. if (!scene.useDelayedTextureLoading) {
  20496. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  20497. if (deleteBuffer) {
  20498. delete _this._buffer;
  20499. }
  20500. }
  20501. else {
  20502. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20503. _this._delayedOnLoad = load;
  20504. _this._delayedOnError = onError;
  20505. }
  20506. }
  20507. else {
  20508. if (_this._texture.isReady) {
  20509. BABYLON.Tools.SetImmediate(function () { return load(); });
  20510. }
  20511. else {
  20512. _this._texture.onLoadedObservable.add(load);
  20513. }
  20514. }
  20515. return _this;
  20516. }
  20517. Object.defineProperty(Texture.prototype, "noMipmap", {
  20518. get: function () {
  20519. return this._noMipmap;
  20520. },
  20521. enumerable: true,
  20522. configurable: true
  20523. });
  20524. Object.defineProperty(Texture.prototype, "isBlocking", {
  20525. get: function () {
  20526. return this._isBlocking;
  20527. },
  20528. set: function (value) {
  20529. this._isBlocking = value;
  20530. },
  20531. enumerable: true,
  20532. configurable: true
  20533. });
  20534. Object.defineProperty(Texture.prototype, "samplingMode", {
  20535. get: function () {
  20536. return this._samplingMode;
  20537. },
  20538. enumerable: true,
  20539. configurable: true
  20540. });
  20541. Texture.prototype.updateURL = function (url) {
  20542. this.url = url;
  20543. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20544. this.delayLoad();
  20545. };
  20546. Texture.prototype.delayLoad = function () {
  20547. var _this = this;
  20548. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20549. return;
  20550. }
  20551. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20552. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  20553. if (!this._texture) {
  20554. 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);
  20555. if (this._deleteBuffer) {
  20556. delete this._buffer;
  20557. }
  20558. }
  20559. else {
  20560. if (this._texture.isReady) {
  20561. BABYLON.Tools.SetImmediate(function () { return _this._delayedOnLoad(); });
  20562. }
  20563. else {
  20564. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  20565. }
  20566. }
  20567. };
  20568. Texture.prototype.updateSamplingMode = function (samplingMode) {
  20569. if (!this._texture) {
  20570. return;
  20571. }
  20572. this._samplingMode = samplingMode;
  20573. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  20574. };
  20575. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  20576. x *= this.uScale;
  20577. y *= this.vScale;
  20578. x -= 0.5 * this.uScale;
  20579. y -= 0.5 * this.vScale;
  20580. z -= 0.5;
  20581. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  20582. t.x += 0.5 * this.uScale + this.uOffset;
  20583. t.y += 0.5 * this.vScale + this.vOffset;
  20584. t.z += 0.5;
  20585. };
  20586. Texture.prototype.getTextureMatrix = function () {
  20587. var _this = this;
  20588. if (this.uOffset === this._cachedUOffset &&
  20589. this.vOffset === this._cachedVOffset &&
  20590. this.uScale === this._cachedUScale &&
  20591. this.vScale === this._cachedVScale &&
  20592. this.uAng === this._cachedUAng &&
  20593. this.vAng === this._cachedVAng &&
  20594. this.wAng === this._cachedWAng) {
  20595. return this._cachedTextureMatrix;
  20596. }
  20597. this._cachedUOffset = this.uOffset;
  20598. this._cachedVOffset = this.vOffset;
  20599. this._cachedUScale = this.uScale;
  20600. this._cachedVScale = this.vScale;
  20601. this._cachedUAng = this.uAng;
  20602. this._cachedVAng = this.vAng;
  20603. this._cachedWAng = this.wAng;
  20604. if (!this._cachedTextureMatrix) {
  20605. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20606. this._rowGenerationMatrix = new BABYLON.Matrix();
  20607. this._t0 = BABYLON.Vector3.Zero();
  20608. this._t1 = BABYLON.Vector3.Zero();
  20609. this._t2 = BABYLON.Vector3.Zero();
  20610. }
  20611. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  20612. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  20613. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  20614. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  20615. this._t1.subtractInPlace(this._t0);
  20616. this._t2.subtractInPlace(this._t0);
  20617. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20618. this._cachedTextureMatrix.m[0] = this._t1.x;
  20619. this._cachedTextureMatrix.m[1] = this._t1.y;
  20620. this._cachedTextureMatrix.m[2] = this._t1.z;
  20621. this._cachedTextureMatrix.m[4] = this._t2.x;
  20622. this._cachedTextureMatrix.m[5] = this._t2.y;
  20623. this._cachedTextureMatrix.m[6] = this._t2.z;
  20624. this._cachedTextureMatrix.m[8] = this._t0.x;
  20625. this._cachedTextureMatrix.m[9] = this._t0.y;
  20626. this._cachedTextureMatrix.m[10] = this._t0.z;
  20627. this.getScene().markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  20628. return mat.hasTexture(_this);
  20629. });
  20630. return this._cachedTextureMatrix;
  20631. };
  20632. Texture.prototype.getReflectionTextureMatrix = function () {
  20633. var _this = this;
  20634. var scene = this.getScene();
  20635. if (this.uOffset === this._cachedUOffset &&
  20636. this.vOffset === this._cachedVOffset &&
  20637. this.uScale === this._cachedUScale &&
  20638. this.vScale === this._cachedVScale &&
  20639. this.coordinatesMode === this._cachedCoordinatesMode) {
  20640. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  20641. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  20642. return this._cachedTextureMatrix;
  20643. }
  20644. }
  20645. else {
  20646. return this._cachedTextureMatrix;
  20647. }
  20648. }
  20649. if (!this._cachedTextureMatrix) {
  20650. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20651. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  20652. }
  20653. this._cachedUOffset = this.uOffset;
  20654. this._cachedVOffset = this.vOffset;
  20655. this._cachedUScale = this.uScale;
  20656. this._cachedVScale = this.vScale;
  20657. this._cachedCoordinatesMode = this.coordinatesMode;
  20658. switch (this.coordinatesMode) {
  20659. case Texture.PLANAR_MODE:
  20660. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20661. this._cachedTextureMatrix[0] = this.uScale;
  20662. this._cachedTextureMatrix[5] = this.vScale;
  20663. this._cachedTextureMatrix[12] = this.uOffset;
  20664. this._cachedTextureMatrix[13] = this.vOffset;
  20665. break;
  20666. case Texture.PROJECTION_MODE:
  20667. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  20668. this._projectionModeMatrix.m[0] = 0.5;
  20669. this._projectionModeMatrix.m[5] = -0.5;
  20670. this._projectionModeMatrix.m[10] = 0.0;
  20671. this._projectionModeMatrix.m[12] = 0.5;
  20672. this._projectionModeMatrix.m[13] = 0.5;
  20673. this._projectionModeMatrix.m[14] = 1.0;
  20674. this._projectionModeMatrix.m[15] = 1.0;
  20675. var projectionMatrix = scene.getProjectionMatrix();
  20676. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  20677. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  20678. break;
  20679. default:
  20680. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20681. break;
  20682. }
  20683. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  20684. return (mat.getActiveTextures().indexOf(_this) !== -1);
  20685. });
  20686. return this._cachedTextureMatrix;
  20687. };
  20688. Texture.prototype.clone = function () {
  20689. var _this = this;
  20690. return BABYLON.SerializationHelper.Clone(function () {
  20691. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  20692. }, this);
  20693. };
  20694. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  20695. get: function () {
  20696. if (!this._onLoadObservable) {
  20697. this._onLoadObservable = new BABYLON.Observable();
  20698. }
  20699. return this._onLoadObservable;
  20700. },
  20701. enumerable: true,
  20702. configurable: true
  20703. });
  20704. Texture.prototype.serialize = function () {
  20705. var serializationObject = _super.prototype.serialize.call(this);
  20706. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  20707. serializationObject.base64String = this._buffer;
  20708. serializationObject.name = serializationObject.name.replace("data:", "");
  20709. }
  20710. return serializationObject;
  20711. };
  20712. Texture.prototype.getClassName = function () {
  20713. return "Texture";
  20714. };
  20715. Texture.prototype.dispose = function () {
  20716. _super.prototype.dispose.call(this);
  20717. if (this.onLoadObservable) {
  20718. this.onLoadObservable.clear();
  20719. this._onLoadObservable = null;
  20720. }
  20721. this._delayedOnLoad = null;
  20722. this._delayedOnError = null;
  20723. };
  20724. // Statics
  20725. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  20726. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20727. if (onLoad === void 0) { onLoad = null; }
  20728. if (onError === void 0) { onError = null; }
  20729. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  20730. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  20731. };
  20732. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  20733. if (parsedTexture.customType) {
  20734. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  20735. // Update Sampling Mode
  20736. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  20737. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  20738. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  20739. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  20740. }
  20741. }
  20742. return parsedCustomTexture;
  20743. }
  20744. if (parsedTexture.isCube) {
  20745. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  20746. }
  20747. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  20748. return null;
  20749. }
  20750. var texture = BABYLON.SerializationHelper.Parse(function () {
  20751. if (parsedTexture.mirrorPlane) {
  20752. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20753. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  20754. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  20755. return mirrorTexture;
  20756. }
  20757. else if (parsedTexture.isRenderTarget) {
  20758. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20759. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  20760. return renderTargetTexture;
  20761. }
  20762. else {
  20763. var texture;
  20764. if (parsedTexture.base64String) {
  20765. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  20766. }
  20767. else {
  20768. texture = new Texture(rootUrl + parsedTexture.name, scene);
  20769. }
  20770. return texture;
  20771. }
  20772. }, parsedTexture, scene);
  20773. // Update Sampling Mode
  20774. if (parsedTexture.samplingMode) {
  20775. var sampling = parsedTexture.samplingMode;
  20776. if (texture._samplingMode !== sampling) {
  20777. texture.updateSamplingMode(sampling);
  20778. }
  20779. }
  20780. // Animations
  20781. if (parsedTexture.animations) {
  20782. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  20783. var parsedAnimation = parsedTexture.animations[animationIndex];
  20784. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20785. }
  20786. }
  20787. return texture;
  20788. };
  20789. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  20790. if (deleteBuffer === void 0) { deleteBuffer = false; }
  20791. if (noMipmap === void 0) { noMipmap = false; }
  20792. if (invertY === void 0) { invertY = true; }
  20793. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20794. if (onLoad === void 0) { onLoad = null; }
  20795. if (onError === void 0) { onError = null; }
  20796. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  20797. if (name.substr(0, 5) !== "data:") {
  20798. name = "data:" + name;
  20799. }
  20800. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  20801. };
  20802. // Constants
  20803. Texture.NEAREST_SAMPLINGMODE = 1;
  20804. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  20805. Texture.BILINEAR_SAMPLINGMODE = 2;
  20806. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  20807. Texture.TRILINEAR_SAMPLINGMODE = 3;
  20808. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  20809. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  20810. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  20811. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  20812. Texture.NEAREST_LINEAR = 7;
  20813. Texture.NEAREST_NEAREST = 8;
  20814. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  20815. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  20816. Texture.LINEAR_LINEAR = 11;
  20817. Texture.LINEAR_NEAREST = 12;
  20818. Texture.EXPLICIT_MODE = 0;
  20819. Texture.SPHERICAL_MODE = 1;
  20820. Texture.PLANAR_MODE = 2;
  20821. Texture.CUBIC_MODE = 3;
  20822. Texture.PROJECTION_MODE = 4;
  20823. Texture.SKYBOX_MODE = 5;
  20824. Texture.INVCUBIC_MODE = 6;
  20825. Texture.EQUIRECTANGULAR_MODE = 7;
  20826. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  20827. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  20828. Texture.CLAMP_ADDRESSMODE = 0;
  20829. Texture.WRAP_ADDRESSMODE = 1;
  20830. Texture.MIRROR_ADDRESSMODE = 2;
  20831. __decorate([
  20832. BABYLON.serialize()
  20833. ], Texture.prototype, "url", void 0);
  20834. __decorate([
  20835. BABYLON.serialize()
  20836. ], Texture.prototype, "uOffset", void 0);
  20837. __decorate([
  20838. BABYLON.serialize()
  20839. ], Texture.prototype, "vOffset", void 0);
  20840. __decorate([
  20841. BABYLON.serialize()
  20842. ], Texture.prototype, "uScale", void 0);
  20843. __decorate([
  20844. BABYLON.serialize()
  20845. ], Texture.prototype, "vScale", void 0);
  20846. __decorate([
  20847. BABYLON.serialize()
  20848. ], Texture.prototype, "uAng", void 0);
  20849. __decorate([
  20850. BABYLON.serialize()
  20851. ], Texture.prototype, "vAng", void 0);
  20852. __decorate([
  20853. BABYLON.serialize()
  20854. ], Texture.prototype, "wAng", void 0);
  20855. __decorate([
  20856. BABYLON.serialize()
  20857. ], Texture.prototype, "isBlocking", null);
  20858. return Texture;
  20859. }(BABYLON.BaseTexture));
  20860. BABYLON.Texture = Texture;
  20861. })(BABYLON || (BABYLON = {}));
  20862. //# sourceMappingURL=babylon.texture.js.map
  20863. var BABYLON;
  20864. (function (BABYLON) {
  20865. var _InstancesBatch = (function () {
  20866. function _InstancesBatch() {
  20867. this.mustReturn = false;
  20868. this.visibleInstances = new Array();
  20869. this.renderSelf = new Array();
  20870. }
  20871. return _InstancesBatch;
  20872. }());
  20873. BABYLON._InstancesBatch = _InstancesBatch;
  20874. var Mesh = (function (_super) {
  20875. __extends(Mesh, _super);
  20876. /**
  20877. * @constructor
  20878. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  20879. * @param {Scene} scene The scene to add this mesh to.
  20880. * @param {Node} parent The parent of this mesh, if it has one
  20881. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  20882. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  20883. * When false, achieved by calling a clone(), also passing False.
  20884. * This will make creation of children, recursive.
  20885. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  20886. */
  20887. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  20888. if (parent === void 0) { parent = null; }
  20889. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20890. var _this = _super.call(this, name, scene) || this;
  20891. // Events
  20892. /**
  20893. * An event triggered before rendering the mesh
  20894. * @type {BABYLON.Observable}
  20895. */
  20896. _this.onBeforeRenderObservable = new BABYLON.Observable();
  20897. /**
  20898. * An event triggered after rendering the mesh
  20899. * @type {BABYLON.Observable}
  20900. */
  20901. _this.onAfterRenderObservable = new BABYLON.Observable();
  20902. /**
  20903. * An event triggered before drawing the mesh
  20904. * @type {BABYLON.Observable}
  20905. */
  20906. _this.onBeforeDrawObservable = new BABYLON.Observable();
  20907. // Members
  20908. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20909. _this.instances = new Array();
  20910. _this._LODLevels = new Array();
  20911. _this._visibleInstances = {};
  20912. _this._renderIdForInstances = new Array();
  20913. _this._batchCache = new _InstancesBatch();
  20914. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  20915. _this._sideOrientation = Mesh._DEFAULTSIDE;
  20916. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  20917. // Will be used to save a source mesh reference, If any
  20918. _this._source = null;
  20919. if (source) {
  20920. // Source mesh
  20921. _this._source = source;
  20922. // Geometry
  20923. if (source._geometry) {
  20924. source._geometry.applyToMesh(_this);
  20925. }
  20926. // Deep copy
  20927. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  20928. // Parent
  20929. _this.parent = source.parent;
  20930. // Pivot
  20931. _this.setPivotMatrix(source.getPivotMatrix());
  20932. _this.id = name + "." + source.id;
  20933. // Material
  20934. _this.material = source.material;
  20935. var index;
  20936. if (!doNotCloneChildren) {
  20937. // Children
  20938. for (index = 0; index < scene.meshes.length; index++) {
  20939. var mesh = scene.meshes[index];
  20940. if (mesh.parent === source) {
  20941. // doNotCloneChildren is always going to be False
  20942. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  20943. }
  20944. }
  20945. }
  20946. // Physics clone
  20947. var physicsEngine = _this.getScene().getPhysicsEngine();
  20948. if (clonePhysicsImpostor && physicsEngine) {
  20949. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  20950. if (impostor) {
  20951. _this.physicsImpostor = impostor.clone(_this);
  20952. }
  20953. }
  20954. // Particles
  20955. for (index = 0; index < scene.particleSystems.length; index++) {
  20956. var system = scene.particleSystems[index];
  20957. if (system.emitter === source) {
  20958. system.clone(system.name, _this);
  20959. }
  20960. }
  20961. _this.computeWorldMatrix(true);
  20962. }
  20963. // Parent
  20964. if (parent !== null) {
  20965. _this.parent = parent;
  20966. }
  20967. return _this;
  20968. }
  20969. Object.defineProperty(Mesh, "FRONTSIDE", {
  20970. /**
  20971. * Mesh side orientation : usually the external or front surface
  20972. */
  20973. get: function () {
  20974. return Mesh._FRONTSIDE;
  20975. },
  20976. enumerable: true,
  20977. configurable: true
  20978. });
  20979. Object.defineProperty(Mesh, "BACKSIDE", {
  20980. /**
  20981. * Mesh side orientation : usually the internal or back surface
  20982. */
  20983. get: function () {
  20984. return Mesh._BACKSIDE;
  20985. },
  20986. enumerable: true,
  20987. configurable: true
  20988. });
  20989. Object.defineProperty(Mesh, "DOUBLESIDE", {
  20990. /**
  20991. * Mesh side orientation : both internal and external or front and back surfaces
  20992. */
  20993. get: function () {
  20994. return Mesh._DOUBLESIDE;
  20995. },
  20996. enumerable: true,
  20997. configurable: true
  20998. });
  20999. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  21000. /**
  21001. * Mesh side orientation : by default, `FRONTSIDE`
  21002. */
  21003. get: function () {
  21004. return Mesh._DEFAULTSIDE;
  21005. },
  21006. enumerable: true,
  21007. configurable: true
  21008. });
  21009. Object.defineProperty(Mesh, "NO_CAP", {
  21010. /**
  21011. * Mesh cap setting : no cap
  21012. */
  21013. get: function () {
  21014. return Mesh._NO_CAP;
  21015. },
  21016. enumerable: true,
  21017. configurable: true
  21018. });
  21019. Object.defineProperty(Mesh, "CAP_START", {
  21020. /**
  21021. * Mesh cap setting : one cap at the beginning of the mesh
  21022. */
  21023. get: function () {
  21024. return Mesh._CAP_START;
  21025. },
  21026. enumerable: true,
  21027. configurable: true
  21028. });
  21029. Object.defineProperty(Mesh, "CAP_END", {
  21030. /**
  21031. * Mesh cap setting : one cap at the end of the mesh
  21032. */
  21033. get: function () {
  21034. return Mesh._CAP_END;
  21035. },
  21036. enumerable: true,
  21037. configurable: true
  21038. });
  21039. Object.defineProperty(Mesh, "CAP_ALL", {
  21040. /**
  21041. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  21042. */
  21043. get: function () {
  21044. return Mesh._CAP_ALL;
  21045. },
  21046. enumerable: true,
  21047. configurable: true
  21048. });
  21049. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  21050. set: function (callback) {
  21051. if (this._onBeforeDrawObserver) {
  21052. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  21053. }
  21054. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  21055. },
  21056. enumerable: true,
  21057. configurable: true
  21058. });
  21059. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  21060. get: function () {
  21061. return this._morphTargetManager;
  21062. },
  21063. set: function (value) {
  21064. if (this._morphTargetManager === value) {
  21065. return;
  21066. }
  21067. this._morphTargetManager = value;
  21068. this._syncGeometryWithMorphTargetManager();
  21069. },
  21070. enumerable: true,
  21071. configurable: true
  21072. });
  21073. Object.defineProperty(Mesh.prototype, "source", {
  21074. get: function () {
  21075. return this._source;
  21076. },
  21077. enumerable: true,
  21078. configurable: true
  21079. });
  21080. // Methods
  21081. /**
  21082. * Returns the string "Mesh".
  21083. */
  21084. Mesh.prototype.getClassName = function () {
  21085. return "Mesh";
  21086. };
  21087. /**
  21088. * Returns a string.
  21089. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  21090. */
  21091. Mesh.prototype.toString = function (fullDetails) {
  21092. var ret = _super.prototype.toString.call(this, fullDetails);
  21093. ret += ", n vertices: " + this.getTotalVertices();
  21094. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  21095. if (this.animations) {
  21096. for (var i = 0; i < this.animations.length; i++) {
  21097. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21098. }
  21099. }
  21100. if (fullDetails) {
  21101. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  21102. }
  21103. return ret;
  21104. };
  21105. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  21106. /**
  21107. * True if the mesh has some Levels Of Details (LOD).
  21108. * Returns a boolean.
  21109. */
  21110. get: function () {
  21111. return this._LODLevels.length > 0;
  21112. },
  21113. enumerable: true,
  21114. configurable: true
  21115. });
  21116. Mesh.prototype._sortLODLevels = function () {
  21117. this._LODLevels.sort(function (a, b) {
  21118. if (a.distance < b.distance) {
  21119. return 1;
  21120. }
  21121. if (a.distance > b.distance) {
  21122. return -1;
  21123. }
  21124. return 0;
  21125. });
  21126. };
  21127. /**
  21128. * Add a mesh as LOD level triggered at the given distance.
  21129. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21130. * @param {number} distance The distance from the center of the object to show this level
  21131. * @param {Mesh} mesh The mesh to be added as LOD level
  21132. * @return {Mesh} This mesh (for chaining)
  21133. */
  21134. Mesh.prototype.addLODLevel = function (distance, mesh) {
  21135. if (mesh && mesh._masterMesh) {
  21136. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  21137. return this;
  21138. }
  21139. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  21140. this._LODLevels.push(level);
  21141. if (mesh) {
  21142. mesh._masterMesh = this;
  21143. }
  21144. this._sortLODLevels();
  21145. return this;
  21146. };
  21147. /**
  21148. * Returns the LOD level mesh at the passed distance or null if not found.
  21149. * It is related to the method `addLODLevel(distance, mesh)`.
  21150. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21151. * Returns an object Mesh or `null`.
  21152. */
  21153. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  21154. for (var index = 0; index < this._LODLevels.length; index++) {
  21155. var level = this._LODLevels[index];
  21156. if (level.distance === distance) {
  21157. return level.mesh;
  21158. }
  21159. }
  21160. return null;
  21161. };
  21162. /**
  21163. * Remove a mesh from the LOD array
  21164. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21165. * @param {Mesh} mesh The mesh to be removed.
  21166. * @return {Mesh} This mesh (for chaining)
  21167. */
  21168. Mesh.prototype.removeLODLevel = function (mesh) {
  21169. for (var index = 0; index < this._LODLevels.length; index++) {
  21170. if (this._LODLevels[index].mesh === mesh) {
  21171. this._LODLevels.splice(index, 1);
  21172. if (mesh) {
  21173. mesh._masterMesh = null;
  21174. }
  21175. }
  21176. }
  21177. this._sortLODLevels();
  21178. return this;
  21179. };
  21180. /**
  21181. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  21182. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21183. */
  21184. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  21185. if (!this._LODLevels || this._LODLevels.length === 0) {
  21186. return this;
  21187. }
  21188. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  21189. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  21190. if (this.onLODLevelSelection) {
  21191. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  21192. }
  21193. return this;
  21194. }
  21195. for (var index = 0; index < this._LODLevels.length; index++) {
  21196. var level = this._LODLevels[index];
  21197. if (level.distance < distanceToCamera) {
  21198. if (level.mesh) {
  21199. level.mesh._preActivate();
  21200. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  21201. }
  21202. if (this.onLODLevelSelection) {
  21203. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  21204. }
  21205. return level.mesh;
  21206. }
  21207. }
  21208. if (this.onLODLevelSelection) {
  21209. this.onLODLevelSelection(distanceToCamera, this, this);
  21210. }
  21211. return this;
  21212. };
  21213. Object.defineProperty(Mesh.prototype, "geometry", {
  21214. /**
  21215. * Returns the mesh internal Geometry object.
  21216. */
  21217. get: function () {
  21218. return this._geometry;
  21219. },
  21220. enumerable: true,
  21221. configurable: true
  21222. });
  21223. /**
  21224. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  21225. */
  21226. Mesh.prototype.getTotalVertices = function () {
  21227. if (!this._geometry) {
  21228. return 0;
  21229. }
  21230. return this._geometry.getTotalVertices();
  21231. };
  21232. /**
  21233. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  21234. * 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.
  21235. * You can force the copy with forceCopy === true
  21236. * Returns null if the mesh has no geometry or no vertex buffer.
  21237. * Possible `kind` values :
  21238. * - BABYLON.VertexBuffer.PositionKind
  21239. * - BABYLON.VertexBuffer.UVKind
  21240. * - BABYLON.VertexBuffer.UV2Kind
  21241. * - BABYLON.VertexBuffer.UV3Kind
  21242. * - BABYLON.VertexBuffer.UV4Kind
  21243. * - BABYLON.VertexBuffer.UV5Kind
  21244. * - BABYLON.VertexBuffer.UV6Kind
  21245. * - BABYLON.VertexBuffer.ColorKind
  21246. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21247. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21248. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21249. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21250. */
  21251. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  21252. if (!this._geometry) {
  21253. return null;
  21254. }
  21255. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  21256. };
  21257. /**
  21258. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  21259. * Returns `undefined` if the mesh has no geometry.
  21260. * Possible `kind` values :
  21261. * - BABYLON.VertexBuffer.PositionKind
  21262. * - BABYLON.VertexBuffer.UVKind
  21263. * - BABYLON.VertexBuffer.UV2Kind
  21264. * - BABYLON.VertexBuffer.UV3Kind
  21265. * - BABYLON.VertexBuffer.UV4Kind
  21266. * - BABYLON.VertexBuffer.UV5Kind
  21267. * - BABYLON.VertexBuffer.UV6Kind
  21268. * - BABYLON.VertexBuffer.ColorKind
  21269. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21270. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21271. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21272. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21273. */
  21274. Mesh.prototype.getVertexBuffer = function (kind) {
  21275. if (!this._geometry) {
  21276. return undefined;
  21277. }
  21278. return this._geometry.getVertexBuffer(kind);
  21279. };
  21280. /**
  21281. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  21282. * Possible `kind` values :
  21283. * - BABYLON.VertexBuffer.PositionKind
  21284. * - BABYLON.VertexBuffer.UVKind
  21285. * - BABYLON.VertexBuffer.UV2Kind
  21286. * - BABYLON.VertexBuffer.UV3Kind
  21287. * - BABYLON.VertexBuffer.UV4Kind
  21288. * - BABYLON.VertexBuffer.UV5Kind
  21289. * - BABYLON.VertexBuffer.UV6Kind
  21290. * - BABYLON.VertexBuffer.ColorKind
  21291. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21292. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21293. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21294. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21295. */
  21296. Mesh.prototype.isVerticesDataPresent = function (kind) {
  21297. if (!this._geometry) {
  21298. if (this._delayInfo) {
  21299. return this._delayInfo.indexOf(kind) !== -1;
  21300. }
  21301. return false;
  21302. }
  21303. return this._geometry.isVerticesDataPresent(kind);
  21304. };
  21305. /**
  21306. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  21307. * Possible `kind` values :
  21308. * - BABYLON.VertexBuffer.PositionKind
  21309. * - BABYLON.VertexBuffer.UVKind
  21310. * - BABYLON.VertexBuffer.UV2Kind
  21311. * - BABYLON.VertexBuffer.UV3Kind
  21312. * - BABYLON.VertexBuffer.UV4Kind
  21313. * - BABYLON.VertexBuffer.UV5Kind
  21314. * - BABYLON.VertexBuffer.UV6Kind
  21315. * - BABYLON.VertexBuffer.ColorKind
  21316. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21317. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21318. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21319. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21320. */
  21321. Mesh.prototype.getVerticesDataKinds = function () {
  21322. if (!this._geometry) {
  21323. var result = [];
  21324. if (this._delayInfo) {
  21325. this._delayInfo.forEach(function (kind, index, array) {
  21326. result.push(kind);
  21327. });
  21328. }
  21329. return result;
  21330. }
  21331. return this._geometry.getVerticesDataKinds();
  21332. };
  21333. /**
  21334. * Returns a positive integer : the total number of indices in this mesh geometry.
  21335. * Returns zero if the mesh has no geometry.
  21336. */
  21337. Mesh.prototype.getTotalIndices = function () {
  21338. if (!this._geometry) {
  21339. return 0;
  21340. }
  21341. return this._geometry.getTotalIndices();
  21342. };
  21343. /**
  21344. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  21345. * 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.
  21346. * Returns an empty array if the mesh has no geometry.
  21347. */
  21348. Mesh.prototype.getIndices = function (copyWhenShared) {
  21349. if (!this._geometry) {
  21350. return [];
  21351. }
  21352. return this._geometry.getIndices(copyWhenShared);
  21353. };
  21354. Object.defineProperty(Mesh.prototype, "isBlocked", {
  21355. get: function () {
  21356. return this._masterMesh !== null && this._masterMesh !== undefined;
  21357. },
  21358. enumerable: true,
  21359. configurable: true
  21360. });
  21361. /**
  21362. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  21363. */
  21364. Mesh.prototype.isReady = function () {
  21365. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21366. return false;
  21367. }
  21368. return _super.prototype.isReady.call(this);
  21369. };
  21370. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  21371. get: function () {
  21372. return this._sideOrientation;
  21373. },
  21374. /**
  21375. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  21376. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  21377. */
  21378. set: function (sideO) {
  21379. this._sideOrientation = sideO;
  21380. },
  21381. enumerable: true,
  21382. configurable: true
  21383. });
  21384. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  21385. /**
  21386. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  21387. * This property is pertinent only for updatable parametric shapes.
  21388. */
  21389. get: function () {
  21390. return this._areNormalsFrozen;
  21391. },
  21392. enumerable: true,
  21393. configurable: true
  21394. });
  21395. /**
  21396. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  21397. * It has no effect at all on other shapes.
  21398. * It prevents the mesh normals from being recomputed on next `positions` array update.
  21399. * Returns the Mesh.
  21400. */
  21401. Mesh.prototype.freezeNormals = function () {
  21402. this._areNormalsFrozen = true;
  21403. return this;
  21404. };
  21405. /**
  21406. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  21407. * It has no effect at all on other shapes.
  21408. * It reactivates the mesh normals computation if it was previously frozen.
  21409. * Returns the Mesh.
  21410. */
  21411. Mesh.prototype.unfreezeNormals = function () {
  21412. this._areNormalsFrozen = false;
  21413. return this;
  21414. };
  21415. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  21416. /**
  21417. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  21418. */
  21419. set: function (count) {
  21420. this._overridenInstanceCount = count;
  21421. },
  21422. enumerable: true,
  21423. configurable: true
  21424. });
  21425. // Methods
  21426. Mesh.prototype._preActivate = function () {
  21427. var sceneRenderId = this.getScene().getRenderId();
  21428. if (this._preActivateId === sceneRenderId) {
  21429. return this;
  21430. }
  21431. this._preActivateId = sceneRenderId;
  21432. this._visibleInstances = null;
  21433. return this;
  21434. };
  21435. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  21436. if (this._visibleInstances) {
  21437. this._visibleInstances.intermediateDefaultRenderId = renderId;
  21438. }
  21439. return this;
  21440. };
  21441. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  21442. if (!this._visibleInstances) {
  21443. this._visibleInstances = {};
  21444. this._visibleInstances.defaultRenderId = renderId;
  21445. this._visibleInstances.selfDefaultRenderId = this._renderId;
  21446. }
  21447. if (!this._visibleInstances[renderId]) {
  21448. this._visibleInstances[renderId] = new Array();
  21449. }
  21450. this._visibleInstances[renderId].push(instance);
  21451. return this;
  21452. };
  21453. /**
  21454. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  21455. * This means the mesh underlying bounding box and sphere are recomputed.
  21456. * Returns the Mesh.
  21457. */
  21458. Mesh.prototype.refreshBoundingInfo = function () {
  21459. if (this._boundingInfo.isLocked) {
  21460. return;
  21461. }
  21462. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21463. if (data) {
  21464. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  21465. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21466. }
  21467. if (this.subMeshes) {
  21468. for (var index = 0; index < this.subMeshes.length; index++) {
  21469. this.subMeshes[index].refreshBoundingInfo();
  21470. }
  21471. }
  21472. this._updateBoundingInfo();
  21473. return this;
  21474. };
  21475. Mesh.prototype._createGlobalSubMesh = function (force) {
  21476. var totalVertices = this.getTotalVertices();
  21477. if (!totalVertices || !this.getIndices()) {
  21478. return null;
  21479. }
  21480. // Check if we need to recreate the submeshes
  21481. if (this.subMeshes && this.subMeshes.length > 0) {
  21482. var totalIndices = this.getIndices().length;
  21483. var needToRecreate = false;
  21484. if (force) {
  21485. needToRecreate = true;
  21486. }
  21487. else {
  21488. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21489. var submesh = _a[_i];
  21490. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  21491. needToRecreate = true;
  21492. break;
  21493. }
  21494. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  21495. needToRecreate = true;
  21496. break;
  21497. }
  21498. }
  21499. }
  21500. if (!needToRecreate) {
  21501. return;
  21502. }
  21503. }
  21504. this.releaseSubMeshes();
  21505. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  21506. };
  21507. Mesh.prototype.subdivide = function (count) {
  21508. if (count < 1) {
  21509. return;
  21510. }
  21511. var totalIndices = this.getTotalIndices();
  21512. var subdivisionSize = (totalIndices / count) | 0;
  21513. var offset = 0;
  21514. // Ensure that subdivisionSize is a multiple of 3
  21515. while (subdivisionSize % 3 !== 0) {
  21516. subdivisionSize++;
  21517. }
  21518. this.releaseSubMeshes();
  21519. for (var index = 0; index < count; index++) {
  21520. if (offset >= totalIndices) {
  21521. break;
  21522. }
  21523. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  21524. offset += subdivisionSize;
  21525. }
  21526. this.synchronizeInstances();
  21527. };
  21528. /**
  21529. * Sets the vertex data of the mesh geometry for the requested `kind`.
  21530. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  21531. * The `data` are either a numeric array either a Float32Array.
  21532. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  21533. * 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).
  21534. * Note that a new underlying VertexBuffer object is created each call.
  21535. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  21536. *
  21537. * Possible `kind` values :
  21538. * - BABYLON.VertexBuffer.PositionKind
  21539. * - BABYLON.VertexBuffer.UVKind
  21540. * - BABYLON.VertexBuffer.UV2Kind
  21541. * - BABYLON.VertexBuffer.UV3Kind
  21542. * - BABYLON.VertexBuffer.UV4Kind
  21543. * - BABYLON.VertexBuffer.UV5Kind
  21544. * - BABYLON.VertexBuffer.UV6Kind
  21545. * - BABYLON.VertexBuffer.ColorKind
  21546. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21547. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21548. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21549. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21550. *
  21551. * Returns the Mesh.
  21552. */
  21553. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  21554. if (!this._geometry) {
  21555. var vertexData = new BABYLON.VertexData();
  21556. vertexData.set(data, kind);
  21557. var scene = this.getScene();
  21558. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  21559. }
  21560. else {
  21561. this._geometry.setVerticesData(kind, data, updatable, stride);
  21562. }
  21563. return this;
  21564. };
  21565. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  21566. if (updatable === void 0) { updatable = true; }
  21567. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  21568. return;
  21569. }
  21570. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  21571. };
  21572. /**
  21573. * Sets the mesh VertexBuffer.
  21574. * Returns the Mesh.
  21575. */
  21576. Mesh.prototype.setVerticesBuffer = function (buffer) {
  21577. if (!this._geometry) {
  21578. var scene = this.getScene();
  21579. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  21580. }
  21581. this._geometry.setVerticesBuffer(buffer);
  21582. return this;
  21583. };
  21584. /**
  21585. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  21586. * If the mesh has no geometry, it is simply returned as it is.
  21587. * The `data` are either a numeric array either a Float32Array.
  21588. * No new underlying VertexBuffer object is created.
  21589. * 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.
  21590. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  21591. *
  21592. * Possible `kind` values :
  21593. * - BABYLON.VertexBuffer.PositionKind
  21594. * - BABYLON.VertexBuffer.UVKind
  21595. * - BABYLON.VertexBuffer.UV2Kind
  21596. * - BABYLON.VertexBuffer.UV3Kind
  21597. * - BABYLON.VertexBuffer.UV4Kind
  21598. * - BABYLON.VertexBuffer.UV5Kind
  21599. * - BABYLON.VertexBuffer.UV6Kind
  21600. * - BABYLON.VertexBuffer.ColorKind
  21601. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21602. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21603. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21604. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21605. *
  21606. * Returns the Mesh.
  21607. */
  21608. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  21609. if (!this._geometry) {
  21610. return;
  21611. }
  21612. if (!makeItUnique) {
  21613. this._geometry.updateVerticesData(kind, data, updateExtends);
  21614. }
  21615. else {
  21616. this.makeGeometryUnique();
  21617. this.updateVerticesData(kind, data, updateExtends, false);
  21618. }
  21619. return this;
  21620. };
  21621. /**
  21622. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  21623. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  21624. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  21625. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  21626. * Returns the Mesh.
  21627. */
  21628. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  21629. if (computeNormals === void 0) { computeNormals = true; }
  21630. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21631. positionFunction(positions);
  21632. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  21633. if (computeNormals) {
  21634. var indices = this.getIndices();
  21635. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21636. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21637. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  21638. }
  21639. return this;
  21640. };
  21641. /**
  21642. * Creates a un-shared specific occurence of the geometry for the mesh.
  21643. * Returns the Mesh.
  21644. */
  21645. Mesh.prototype.makeGeometryUnique = function () {
  21646. if (!this._geometry) {
  21647. return;
  21648. }
  21649. var oldGeometry = this._geometry;
  21650. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  21651. oldGeometry.releaseForMesh(this, true);
  21652. geometry.applyToMesh(this);
  21653. return this;
  21654. };
  21655. /**
  21656. * Sets the mesh indices.
  21657. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  21658. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  21659. * This method creates a new index buffer each call.
  21660. * Returns the Mesh.
  21661. */
  21662. Mesh.prototype.setIndices = function (indices, totalVertices) {
  21663. if (!this._geometry) {
  21664. var vertexData = new BABYLON.VertexData();
  21665. vertexData.indices = indices;
  21666. var scene = this.getScene();
  21667. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  21668. }
  21669. else {
  21670. this._geometry.setIndices(indices, totalVertices);
  21671. }
  21672. return this;
  21673. };
  21674. /**
  21675. * Invert the geometry to move from a right handed system to a left handed one.
  21676. * Returns the Mesh.
  21677. */
  21678. Mesh.prototype.toLeftHanded = function () {
  21679. if (!this._geometry) {
  21680. return;
  21681. }
  21682. this._geometry.toLeftHanded();
  21683. return this;
  21684. };
  21685. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  21686. var engine = this.getScene().getEngine();
  21687. // Wireframe
  21688. var indexToBind;
  21689. if (this._unIndexed) {
  21690. indexToBind = null;
  21691. }
  21692. else {
  21693. switch (fillMode) {
  21694. case BABYLON.Material.PointFillMode:
  21695. indexToBind = null;
  21696. break;
  21697. case BABYLON.Material.WireFrameFillMode:
  21698. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  21699. break;
  21700. default:
  21701. case BABYLON.Material.TriangleFillMode:
  21702. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  21703. break;
  21704. }
  21705. }
  21706. // VBOs
  21707. this._geometry._bind(effect, indexToBind);
  21708. return this;
  21709. };
  21710. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  21711. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  21712. return this;
  21713. }
  21714. this.onBeforeDrawObservable.notifyObservers(this);
  21715. var engine = this.getScene().getEngine();
  21716. // Draw order
  21717. switch (fillMode) {
  21718. case BABYLON.Material.PointFillMode:
  21719. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21720. break;
  21721. case BABYLON.Material.WireFrameFillMode:
  21722. if (this._unIndexed) {
  21723. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21724. }
  21725. else {
  21726. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  21727. }
  21728. break;
  21729. default:
  21730. if (this._unIndexed) {
  21731. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21732. }
  21733. else {
  21734. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  21735. }
  21736. }
  21737. return this;
  21738. };
  21739. /**
  21740. * Registers for this mesh a javascript function called just before the rendering process.
  21741. * This function is passed the current mesh.
  21742. * Return the Mesh.
  21743. */
  21744. Mesh.prototype.registerBeforeRender = function (func) {
  21745. this.onBeforeRenderObservable.add(func);
  21746. return this;
  21747. };
  21748. /**
  21749. * Disposes a previously registered javascript function called before the rendering.
  21750. * This function is passed the current mesh.
  21751. * Returns the Mesh.
  21752. */
  21753. Mesh.prototype.unregisterBeforeRender = function (func) {
  21754. this.onBeforeRenderObservable.removeCallback(func);
  21755. return this;
  21756. };
  21757. /**
  21758. * Registers for this mesh a javascript function called just after the rendering is complete.
  21759. * This function is passed the current mesh.
  21760. * Returns the Mesh.
  21761. */
  21762. Mesh.prototype.registerAfterRender = function (func) {
  21763. this.onAfterRenderObservable.add(func);
  21764. return this;
  21765. };
  21766. /**
  21767. * Disposes a previously registered javascript function called after the rendering.
  21768. * This function is passed the current mesh.
  21769. * Return the Mesh.
  21770. */
  21771. Mesh.prototype.unregisterAfterRender = function (func) {
  21772. this.onAfterRenderObservable.removeCallback(func);
  21773. return this;
  21774. };
  21775. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  21776. var scene = this.getScene();
  21777. this._batchCache.mustReturn = false;
  21778. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  21779. this._batchCache.visibleInstances[subMeshId] = null;
  21780. if (this._visibleInstances) {
  21781. var currentRenderId = scene.getRenderId();
  21782. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  21783. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  21784. var selfRenderId = this._renderId;
  21785. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  21786. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  21787. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  21788. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  21789. }
  21790. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  21791. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  21792. this._batchCache.mustReturn = true;
  21793. return this._batchCache;
  21794. }
  21795. if (currentRenderId !== selfRenderId) {
  21796. this._batchCache.renderSelf[subMeshId] = false;
  21797. }
  21798. }
  21799. this._renderIdForInstances[subMeshId] = currentRenderId;
  21800. }
  21801. return this._batchCache;
  21802. };
  21803. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  21804. var visibleInstances = batch.visibleInstances[subMesh._id];
  21805. var matricesCount = visibleInstances.length + 1;
  21806. var bufferSize = matricesCount * 16 * 4;
  21807. var currentInstancesBufferSize = this._instancesBufferSize;
  21808. var instancesBuffer = this._instancesBuffer;
  21809. while (this._instancesBufferSize < bufferSize) {
  21810. this._instancesBufferSize *= 2;
  21811. }
  21812. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  21813. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  21814. }
  21815. var offset = 0;
  21816. var instancesCount = 0;
  21817. var world = this.getWorldMatrix();
  21818. if (batch.renderSelf[subMesh._id]) {
  21819. world.copyToArray(this._instancesData, offset);
  21820. offset += 16;
  21821. instancesCount++;
  21822. }
  21823. if (visibleInstances) {
  21824. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  21825. var instance = visibleInstances[instanceIndex];
  21826. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  21827. offset += 16;
  21828. instancesCount++;
  21829. }
  21830. }
  21831. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  21832. if (instancesBuffer) {
  21833. instancesBuffer.dispose();
  21834. }
  21835. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  21836. this._instancesBuffer = instancesBuffer;
  21837. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  21838. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  21839. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  21840. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  21841. }
  21842. else {
  21843. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  21844. }
  21845. this._bind(subMesh, effect, fillMode);
  21846. this._draw(subMesh, fillMode, instancesCount);
  21847. engine.unbindInstanceAttributes();
  21848. return this;
  21849. };
  21850. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  21851. var scene = this.getScene();
  21852. var engine = scene.getEngine();
  21853. if (hardwareInstancedRendering) {
  21854. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  21855. }
  21856. else {
  21857. if (batch.renderSelf[subMesh._id]) {
  21858. // Draw
  21859. if (onBeforeDraw) {
  21860. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  21861. }
  21862. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  21863. }
  21864. if (batch.visibleInstances[subMesh._id]) {
  21865. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  21866. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  21867. // World
  21868. var world = instance.getWorldMatrix();
  21869. if (onBeforeDraw) {
  21870. onBeforeDraw(true, world, effectiveMaterial);
  21871. }
  21872. // Draw
  21873. this._draw(subMesh, fillMode);
  21874. }
  21875. }
  21876. }
  21877. return this;
  21878. };
  21879. /**
  21880. * Triggers the draw call for the mesh.
  21881. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  21882. * Returns the Mesh.
  21883. */
  21884. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  21885. this.checkOcclusionQuery();
  21886. if (this._isOccluded) {
  21887. return;
  21888. }
  21889. var scene = this.getScene();
  21890. // Managing instances
  21891. var batch = this._getInstancesRenderList(subMesh._id);
  21892. if (batch.mustReturn) {
  21893. return this;
  21894. }
  21895. // Checking geometry state
  21896. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  21897. return this;
  21898. }
  21899. var callbackIndex;
  21900. this.onBeforeRenderObservable.notifyObservers(this);
  21901. var engine = scene.getEngine();
  21902. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  21903. // Material
  21904. var effectiveMaterial = subMesh.getMaterial();
  21905. if (!effectiveMaterial) {
  21906. return this;
  21907. }
  21908. if (effectiveMaterial.storeEffectOnSubMeshes) {
  21909. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  21910. return this;
  21911. }
  21912. }
  21913. else if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  21914. return this;
  21915. }
  21916. // Alpha mode
  21917. if (enableAlphaMode) {
  21918. engine.setAlphaMode(effectiveMaterial.alphaMode);
  21919. }
  21920. // Outline - step 1
  21921. var savedDepthWrite = engine.getDepthWrite();
  21922. if (this.renderOutline) {
  21923. engine.setDepthWrite(false);
  21924. scene.getOutlineRenderer().render(subMesh, batch);
  21925. engine.setDepthWrite(savedDepthWrite);
  21926. }
  21927. var effect;
  21928. if (effectiveMaterial.storeEffectOnSubMeshes) {
  21929. effect = subMesh.effect;
  21930. }
  21931. else {
  21932. effect = effectiveMaterial.getEffect();
  21933. }
  21934. effectiveMaterial._preBind(effect);
  21935. // Bind
  21936. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  21937. if (!hardwareInstancedRendering) {
  21938. this._bind(subMesh, effect, fillMode);
  21939. }
  21940. var world = this.getWorldMatrix();
  21941. if (effectiveMaterial.storeEffectOnSubMeshes) {
  21942. effectiveMaterial.bindForSubMesh(world, this, subMesh);
  21943. }
  21944. else {
  21945. effectiveMaterial.bind(world, this);
  21946. }
  21947. // Draw
  21948. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  21949. // Unbind
  21950. effectiveMaterial.unbind();
  21951. // Outline - step 2
  21952. if (this.renderOutline && savedDepthWrite) {
  21953. engine.setDepthWrite(true);
  21954. engine.setColorWrite(false);
  21955. scene.getOutlineRenderer().render(subMesh, batch);
  21956. engine.setColorWrite(true);
  21957. }
  21958. // Overlay
  21959. if (this.renderOverlay) {
  21960. var currentMode = engine.getAlphaMode();
  21961. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21962. scene.getOutlineRenderer().render(subMesh, batch, true);
  21963. engine.setAlphaMode(currentMode);
  21964. }
  21965. this.onAfterRenderObservable.notifyObservers(this);
  21966. return this;
  21967. };
  21968. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  21969. if (isInstance) {
  21970. effectiveMaterial.bindOnlyWorldMatrix(world);
  21971. }
  21972. return this;
  21973. };
  21974. /**
  21975. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  21976. */
  21977. Mesh.prototype.getEmittedParticleSystems = function () {
  21978. var results = new Array();
  21979. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  21980. var particleSystem = this.getScene().particleSystems[index];
  21981. if (particleSystem.emitter === this) {
  21982. results.push(particleSystem);
  21983. }
  21984. }
  21985. return results;
  21986. };
  21987. /**
  21988. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  21989. */
  21990. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  21991. var results = new Array();
  21992. var descendants = this.getDescendants();
  21993. descendants.push(this);
  21994. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  21995. var particleSystem = this.getScene().particleSystems[index];
  21996. var emitter = particleSystem.emitter;
  21997. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  21998. results.push(particleSystem);
  21999. }
  22000. }
  22001. return results;
  22002. };
  22003. Mesh.prototype._checkDelayState = function () {
  22004. var scene = this.getScene();
  22005. if (this._geometry) {
  22006. this._geometry.load(scene);
  22007. }
  22008. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22009. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  22010. this._queueLoad(this, scene);
  22011. }
  22012. return this;
  22013. };
  22014. Mesh.prototype._queueLoad = function (mesh, scene) {
  22015. var _this = this;
  22016. scene._addPendingData(mesh);
  22017. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  22018. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  22019. if (data instanceof ArrayBuffer) {
  22020. _this._delayLoadingFunction(data, _this);
  22021. }
  22022. else {
  22023. _this._delayLoadingFunction(JSON.parse(data), _this);
  22024. }
  22025. _this.instances.forEach(function (instance) {
  22026. instance._syncSubMeshes();
  22027. });
  22028. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22029. scene._removePendingData(_this);
  22030. }, function () { }, scene.database, getBinaryData);
  22031. return this;
  22032. };
  22033. /**
  22034. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  22035. */
  22036. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  22037. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22038. return false;
  22039. }
  22040. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  22041. return false;
  22042. }
  22043. this._checkDelayState();
  22044. return true;
  22045. };
  22046. /**
  22047. * Sets the mesh material by the material or multiMaterial `id` property.
  22048. * The material `id` is a string identifying the material or the multiMaterial.
  22049. * This method returns the Mesh.
  22050. */
  22051. Mesh.prototype.setMaterialByID = function (id) {
  22052. var materials = this.getScene().materials;
  22053. var index;
  22054. for (index = materials.length - 1; index > -1; index--) {
  22055. if (materials[index].id === id) {
  22056. this.material = materials[index];
  22057. return this;
  22058. }
  22059. }
  22060. // Multi
  22061. var multiMaterials = this.getScene().multiMaterials;
  22062. for (index = multiMaterials.length - 1; index > -1; index--) {
  22063. if (multiMaterials[index].id === id) {
  22064. this.material = multiMaterials[index];
  22065. return this;
  22066. }
  22067. }
  22068. return this;
  22069. };
  22070. /**
  22071. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  22072. */
  22073. Mesh.prototype.getAnimatables = function () {
  22074. var results = [];
  22075. if (this.material) {
  22076. results.push(this.material);
  22077. }
  22078. if (this.skeleton) {
  22079. results.push(this.skeleton);
  22080. }
  22081. return results;
  22082. };
  22083. /**
  22084. * Modifies the mesh geometry according to the passed transformation matrix.
  22085. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  22086. * The mesh normals are modified accordingly the same transformation.
  22087. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  22088. * Note that, under the hood, this method sets a new VertexBuffer each call.
  22089. * Returns the Mesh.
  22090. */
  22091. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  22092. // Position
  22093. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22094. return this;
  22095. }
  22096. var submeshes = this.subMeshes.splice(0);
  22097. this._resetPointsArrayCache();
  22098. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22099. var temp = [];
  22100. var index;
  22101. for (index = 0; index < data.length; index += 3) {
  22102. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  22103. }
  22104. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  22105. // Normals
  22106. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22107. return this;
  22108. }
  22109. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22110. temp = [];
  22111. for (index = 0; index < data.length; index += 3) {
  22112. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  22113. }
  22114. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  22115. // flip faces?
  22116. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  22117. this.flipFaces();
  22118. }
  22119. // Restore submeshes
  22120. this.releaseSubMeshes();
  22121. this.subMeshes = submeshes;
  22122. return this;
  22123. };
  22124. /**
  22125. * Modifies the mesh geometry according to its own current World Matrix.
  22126. * The mesh World Matrix is then reset.
  22127. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  22128. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  22129. * Note that, under the hood, this method sets a new VertexBuffer each call.
  22130. * Returns the Mesh.
  22131. */
  22132. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  22133. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  22134. this.scaling.copyFromFloats(1, 1, 1);
  22135. this.position.copyFromFloats(0, 0, 0);
  22136. this.rotation.copyFromFloats(0, 0, 0);
  22137. //only if quaternion is already set
  22138. if (this.rotationQuaternion) {
  22139. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  22140. }
  22141. this._worldMatrix = BABYLON.Matrix.Identity();
  22142. return this;
  22143. };
  22144. Object.defineProperty(Mesh.prototype, "_positions", {
  22145. // Cache
  22146. get: function () {
  22147. if (this._geometry) {
  22148. return this._geometry._positions;
  22149. }
  22150. return null;
  22151. },
  22152. enumerable: true,
  22153. configurable: true
  22154. });
  22155. Mesh.prototype._resetPointsArrayCache = function () {
  22156. if (this._geometry) {
  22157. this._geometry._resetPointsArrayCache();
  22158. }
  22159. return this;
  22160. };
  22161. Mesh.prototype._generatePointsArray = function () {
  22162. if (this._geometry) {
  22163. return this._geometry._generatePointsArray();
  22164. }
  22165. return false;
  22166. };
  22167. /**
  22168. * Returns a new Mesh object generated from the current mesh properties.
  22169. * This method must not get confused with createInstance().
  22170. * The parameter `name` is a string, the name given to the new mesh.
  22171. * The optional parameter `newParent` can be any Node object (default `null`).
  22172. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  22173. * 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.
  22174. */
  22175. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  22176. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  22177. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  22178. };
  22179. /**
  22180. * Disposes the mesh.
  22181. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  22182. */
  22183. Mesh.prototype.dispose = function (doNotRecurse) {
  22184. var _this = this;
  22185. this.morphTargetManager = undefined;
  22186. if (this._geometry) {
  22187. this._geometry.releaseForMesh(this, true);
  22188. }
  22189. // Sources
  22190. var meshes = this.getScene().meshes;
  22191. meshes.forEach(function (mesh) {
  22192. if (mesh._source && mesh._source === _this) {
  22193. mesh._source = null;
  22194. }
  22195. });
  22196. this._source = null;
  22197. // Instances
  22198. if (this._instancesBuffer) {
  22199. this._instancesBuffer.dispose();
  22200. this._instancesBuffer = null;
  22201. }
  22202. while (this.instances.length) {
  22203. this.instances[0].dispose();
  22204. }
  22205. // Highlight layers.
  22206. var highlightLayers = this.getScene().highlightLayers;
  22207. for (var i = 0; i < highlightLayers.length; i++) {
  22208. var highlightLayer = highlightLayers[i];
  22209. if (highlightLayer) {
  22210. highlightLayer.removeMesh(this);
  22211. highlightLayer.removeExcludedMesh(this);
  22212. }
  22213. }
  22214. _super.prototype.dispose.call(this, doNotRecurse);
  22215. };
  22216. /**
  22217. * Modifies the mesh geometry according to a displacement map.
  22218. * 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.
  22219. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  22220. * This method returns nothing.
  22221. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  22222. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  22223. * 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.
  22224. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  22225. * The parameter `uvScale` is an optional vector2 used to scale UV.
  22226. *
  22227. * Returns the Mesh.
  22228. */
  22229. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  22230. var _this = this;
  22231. var scene = this.getScene();
  22232. var onload = function (img) {
  22233. // Getting height map data
  22234. var canvas = document.createElement("canvas");
  22235. var context = canvas.getContext("2d");
  22236. var heightMapWidth = img.width;
  22237. var heightMapHeight = img.height;
  22238. canvas.width = heightMapWidth;
  22239. canvas.height = heightMapHeight;
  22240. context.drawImage(img, 0, 0);
  22241. // Create VertexData from map data
  22242. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  22243. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  22244. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  22245. //execute success callback, if set
  22246. if (onSuccess) {
  22247. onSuccess(_this);
  22248. }
  22249. };
  22250. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  22251. return this;
  22252. };
  22253. /**
  22254. * Modifies the mesh geometry according to a displacementMap buffer.
  22255. * 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.
  22256. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  22257. * This method returns nothing.
  22258. * 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.
  22259. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  22260. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  22261. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  22262. * The parameter `uvScale` is an optional vector2 used to scale UV.
  22263. *
  22264. * Returns the Mesh.
  22265. */
  22266. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  22267. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  22268. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  22269. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22270. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  22271. return this;
  22272. }
  22273. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22274. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22275. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  22276. var position = BABYLON.Vector3.Zero();
  22277. var normal = BABYLON.Vector3.Zero();
  22278. var uv = BABYLON.Vector2.Zero();
  22279. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  22280. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  22281. for (var index = 0; index < positions.length; index += 3) {
  22282. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  22283. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  22284. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  22285. // Compute height
  22286. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  22287. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  22288. var pos = (u + v * heightMapWidth) * 4;
  22289. var r = buffer[pos] / 255.0;
  22290. var g = buffer[pos + 1] / 255.0;
  22291. var b = buffer[pos + 2] / 255.0;
  22292. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  22293. normal.normalize();
  22294. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  22295. position = position.add(normal);
  22296. position.toArray(positions, index);
  22297. }
  22298. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  22299. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  22300. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  22301. return this;
  22302. };
  22303. /**
  22304. * Modify the mesh to get a flat shading rendering.
  22305. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  22306. * This method returns the Mesh.
  22307. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  22308. */
  22309. Mesh.prototype.convertToFlatShadedMesh = function () {
  22310. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  22311. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  22312. var kinds = this.getVerticesDataKinds();
  22313. var vbs = [];
  22314. var data = [];
  22315. var newdata = [];
  22316. var updatableNormals = false;
  22317. var kindIndex;
  22318. var kind;
  22319. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22320. kind = kinds[kindIndex];
  22321. var vertexBuffer = this.getVertexBuffer(kind);
  22322. if (kind === BABYLON.VertexBuffer.NormalKind) {
  22323. updatableNormals = vertexBuffer.isUpdatable();
  22324. kinds.splice(kindIndex, 1);
  22325. kindIndex--;
  22326. continue;
  22327. }
  22328. vbs[kind] = vertexBuffer;
  22329. data[kind] = vbs[kind].getData();
  22330. newdata[kind] = [];
  22331. }
  22332. // Save previous submeshes
  22333. var previousSubmeshes = this.subMeshes.slice(0);
  22334. var indices = this.getIndices();
  22335. var totalIndices = this.getTotalIndices();
  22336. // Generating unique vertices per face
  22337. var index;
  22338. for (index = 0; index < totalIndices; index++) {
  22339. var vertexIndex = indices[index];
  22340. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22341. kind = kinds[kindIndex];
  22342. var stride = vbs[kind].getStrideSize();
  22343. for (var offset = 0; offset < stride; offset++) {
  22344. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  22345. }
  22346. }
  22347. }
  22348. // Updating faces & normal
  22349. var normals = [];
  22350. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  22351. for (index = 0; index < totalIndices; index += 3) {
  22352. indices[index] = index;
  22353. indices[index + 1] = index + 1;
  22354. indices[index + 2] = index + 2;
  22355. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  22356. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  22357. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  22358. var p1p2 = p1.subtract(p2);
  22359. var p3p2 = p3.subtract(p2);
  22360. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  22361. // Store same normals for every vertex
  22362. for (var localIndex = 0; localIndex < 3; localIndex++) {
  22363. normals.push(normal.x);
  22364. normals.push(normal.y);
  22365. normals.push(normal.z);
  22366. }
  22367. }
  22368. this.setIndices(indices);
  22369. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  22370. // Updating vertex buffers
  22371. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22372. kind = kinds[kindIndex];
  22373. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  22374. }
  22375. // Updating submeshes
  22376. this.releaseSubMeshes();
  22377. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  22378. var previousOne = previousSubmeshes[submeshIndex];
  22379. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  22380. }
  22381. this.synchronizeInstances();
  22382. return this;
  22383. };
  22384. /**
  22385. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  22386. * In other words, more vertices, no more indices and a single bigger VBO.
  22387. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  22388. * Returns the Mesh.
  22389. */
  22390. Mesh.prototype.convertToUnIndexedMesh = function () {
  22391. /// <summary>Remove indices by unfolding faces into buffers</summary>
  22392. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  22393. var kinds = this.getVerticesDataKinds();
  22394. var vbs = [];
  22395. var data = [];
  22396. var newdata = [];
  22397. var updatableNormals = false;
  22398. var kindIndex;
  22399. var kind;
  22400. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22401. kind = kinds[kindIndex];
  22402. var vertexBuffer = this.getVertexBuffer(kind);
  22403. vbs[kind] = vertexBuffer;
  22404. data[kind] = vbs[kind].getData();
  22405. newdata[kind] = [];
  22406. }
  22407. // Save previous submeshes
  22408. var previousSubmeshes = this.subMeshes.slice(0);
  22409. var indices = this.getIndices();
  22410. var totalIndices = this.getTotalIndices();
  22411. // Generating unique vertices per face
  22412. var index;
  22413. for (index = 0; index < totalIndices; index++) {
  22414. var vertexIndex = indices[index];
  22415. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22416. kind = kinds[kindIndex];
  22417. var stride = vbs[kind].getStrideSize();
  22418. for (var offset = 0; offset < stride; offset++) {
  22419. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  22420. }
  22421. }
  22422. }
  22423. // Updating indices
  22424. for (index = 0; index < totalIndices; index += 3) {
  22425. indices[index] = index;
  22426. indices[index + 1] = index + 1;
  22427. indices[index + 2] = index + 2;
  22428. }
  22429. this.setIndices(indices);
  22430. // Updating vertex buffers
  22431. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22432. kind = kinds[kindIndex];
  22433. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  22434. }
  22435. // Updating submeshes
  22436. this.releaseSubMeshes();
  22437. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  22438. var previousOne = previousSubmeshes[submeshIndex];
  22439. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  22440. }
  22441. this._unIndexed = true;
  22442. this.synchronizeInstances();
  22443. return this;
  22444. };
  22445. /**
  22446. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  22447. * This method returns the Mesh.
  22448. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  22449. */
  22450. Mesh.prototype.flipFaces = function (flipNormals) {
  22451. if (flipNormals === void 0) { flipNormals = false; }
  22452. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  22453. var i;
  22454. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22455. for (i = 0; i < vertex_data.normals.length; i++) {
  22456. vertex_data.normals[i] *= -1;
  22457. }
  22458. }
  22459. var temp;
  22460. for (i = 0; i < vertex_data.indices.length; i += 3) {
  22461. // reassign indices
  22462. temp = vertex_data.indices[i + 1];
  22463. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  22464. vertex_data.indices[i + 2] = temp;
  22465. }
  22466. vertex_data.applyToMesh(this);
  22467. return this;
  22468. };
  22469. // Instances
  22470. /**
  22471. * Creates a new InstancedMesh object from the mesh model.
  22472. * An instance shares the same properties and the same material than its model.
  22473. * Only these properties of each instance can then be set individually :
  22474. * - position
  22475. * - rotation
  22476. * - rotationQuaternion
  22477. * - setPivotMatrix
  22478. * - scaling
  22479. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  22480. * Warning : this method is not supported for Line mesh and LineSystem
  22481. */
  22482. Mesh.prototype.createInstance = function (name) {
  22483. return new BABYLON.InstancedMesh(name, this);
  22484. };
  22485. /**
  22486. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  22487. * After this call, all the mesh instances have the same submeshes than the current mesh.
  22488. * This method returns the Mesh.
  22489. */
  22490. Mesh.prototype.synchronizeInstances = function () {
  22491. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  22492. var instance = this.instances[instanceIndex];
  22493. instance._syncSubMeshes();
  22494. }
  22495. return this;
  22496. };
  22497. /**
  22498. * Simplify the mesh according to the given array of settings.
  22499. * Function will return immediately and will simplify async. It returns the Mesh.
  22500. * @param settings a collection of simplification settings.
  22501. * @param parallelProcessing should all levels calculate parallel or one after the other.
  22502. * @param type the type of simplification to run.
  22503. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  22504. */
  22505. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  22506. if (parallelProcessing === void 0) { parallelProcessing = true; }
  22507. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  22508. this.getScene().simplificationQueue.addTask({
  22509. settings: settings,
  22510. parallelProcessing: parallelProcessing,
  22511. mesh: this,
  22512. simplificationType: simplificationType,
  22513. successCallback: successCallback
  22514. });
  22515. return this;
  22516. };
  22517. /**
  22518. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  22519. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  22520. * This should be used together with the simplification to avoid disappearing triangles.
  22521. * Returns the Mesh.
  22522. * @param successCallback an optional success callback to be called after the optimization finished.
  22523. */
  22524. Mesh.prototype.optimizeIndices = function (successCallback) {
  22525. var _this = this;
  22526. var indices = this.getIndices();
  22527. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22528. var vectorPositions = [];
  22529. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  22530. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  22531. }
  22532. var dupes = [];
  22533. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  22534. var realPos = vectorPositions.length - 1 - iteration;
  22535. var testedPosition = vectorPositions[realPos];
  22536. for (var j = 0; j < realPos; ++j) {
  22537. var againstPosition = vectorPositions[j];
  22538. if (testedPosition.equals(againstPosition)) {
  22539. dupes[realPos] = j;
  22540. break;
  22541. }
  22542. }
  22543. }, function () {
  22544. for (var i = 0; i < indices.length; ++i) {
  22545. indices[i] = dupes[indices[i]] || indices[i];
  22546. }
  22547. //indices are now reordered
  22548. var originalSubMeshes = _this.subMeshes.slice(0);
  22549. _this.setIndices(indices);
  22550. _this.subMeshes = originalSubMeshes;
  22551. if (successCallback) {
  22552. successCallback(_this);
  22553. }
  22554. });
  22555. return this;
  22556. };
  22557. Mesh.prototype.serialize = function (serializationObject) {
  22558. serializationObject.name = this.name;
  22559. serializationObject.id = this.id;
  22560. serializationObject.type = this.getClassName();
  22561. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  22562. serializationObject.tags = BABYLON.Tags.GetTags(this);
  22563. }
  22564. serializationObject.position = this.position.asArray();
  22565. if (this.rotationQuaternion) {
  22566. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  22567. }
  22568. else if (this.rotation) {
  22569. serializationObject.rotation = this.rotation.asArray();
  22570. }
  22571. serializationObject.scaling = this.scaling.asArray();
  22572. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  22573. serializationObject.isEnabled = this.isEnabled();
  22574. serializationObject.isVisible = this.isVisible;
  22575. serializationObject.infiniteDistance = this.infiniteDistance;
  22576. serializationObject.pickable = this.isPickable;
  22577. serializationObject.receiveShadows = this.receiveShadows;
  22578. serializationObject.billboardMode = this.billboardMode;
  22579. serializationObject.visibility = this.visibility;
  22580. serializationObject.checkCollisions = this.checkCollisions;
  22581. serializationObject.isBlocker = this.isBlocker;
  22582. // Parent
  22583. if (this.parent) {
  22584. serializationObject.parentId = this.parent.id;
  22585. }
  22586. // Geometry
  22587. var geometry = this._geometry;
  22588. if (geometry) {
  22589. var geometryId = geometry.id;
  22590. serializationObject.geometryId = geometryId;
  22591. // SubMeshes
  22592. serializationObject.subMeshes = [];
  22593. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  22594. var subMesh = this.subMeshes[subIndex];
  22595. serializationObject.subMeshes.push({
  22596. materialIndex: subMesh.materialIndex,
  22597. verticesStart: subMesh.verticesStart,
  22598. verticesCount: subMesh.verticesCount,
  22599. indexStart: subMesh.indexStart,
  22600. indexCount: subMesh.indexCount
  22601. });
  22602. }
  22603. }
  22604. // Material
  22605. if (this.material) {
  22606. serializationObject.materialId = this.material.id;
  22607. }
  22608. else {
  22609. this.material = null;
  22610. }
  22611. // Morph targets
  22612. if (this.morphTargetManager) {
  22613. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  22614. }
  22615. // Skeleton
  22616. if (this.skeleton) {
  22617. serializationObject.skeletonId = this.skeleton.id;
  22618. }
  22619. // Physics
  22620. //TODO implement correct serialization for physics impostors.
  22621. if (this.getPhysicsImpostor()) {
  22622. var impostor = this.getPhysicsImpostor();
  22623. serializationObject.physicsMass = impostor.getParam("mass");
  22624. serializationObject.physicsFriction = impostor.getParam("friction");
  22625. serializationObject.physicsRestitution = impostor.getParam("mass");
  22626. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  22627. }
  22628. // Metadata
  22629. if (this.metadata) {
  22630. serializationObject.metadata = this.metadata;
  22631. }
  22632. // Instances
  22633. serializationObject.instances = [];
  22634. for (var index = 0; index < this.instances.length; index++) {
  22635. var instance = this.instances[index];
  22636. var serializationInstance = {
  22637. name: instance.name,
  22638. position: instance.position.asArray(),
  22639. scaling: instance.scaling.asArray()
  22640. };
  22641. if (instance.rotationQuaternion) {
  22642. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  22643. }
  22644. else if (instance.rotation) {
  22645. serializationInstance.rotation = instance.rotation.asArray();
  22646. }
  22647. serializationObject.instances.push(serializationInstance);
  22648. // Animations
  22649. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  22650. serializationInstance.ranges = instance.serializeAnimationRanges();
  22651. }
  22652. //
  22653. // Animations
  22654. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22655. serializationObject.ranges = this.serializeAnimationRanges();
  22656. // Layer mask
  22657. serializationObject.layerMask = this.layerMask;
  22658. // Alpha
  22659. serializationObject.alphaIndex = this.alphaIndex;
  22660. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  22661. // Overlay
  22662. serializationObject.overlayAlpha = this.overlayAlpha;
  22663. serializationObject.overlayColor = this.overlayColor.asArray();
  22664. serializationObject.renderOverlay = this.renderOverlay;
  22665. // Fog
  22666. serializationObject.applyFog = this.applyFog;
  22667. // Action Manager
  22668. if (this.actionManager) {
  22669. serializationObject.actions = this.actionManager.serialize(this.name);
  22670. }
  22671. };
  22672. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  22673. if (!this.geometry) {
  22674. return;
  22675. }
  22676. this._markSubMeshesAsAttributesDirty();
  22677. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  22678. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  22679. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  22680. this.morphTargetManager = undefined;
  22681. return;
  22682. }
  22683. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  22684. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  22685. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  22686. if (morphTarget.hasNormals) {
  22687. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  22688. }
  22689. if (morphTarget.hasTangents) {
  22690. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  22691. }
  22692. }
  22693. }
  22694. else {
  22695. var index = 0;
  22696. // Positions
  22697. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  22698. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  22699. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  22700. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  22701. }
  22702. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  22703. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  22704. }
  22705. index++;
  22706. }
  22707. }
  22708. };
  22709. // Statics
  22710. /**
  22711. * Returns a new Mesh object what is a deep copy of the passed mesh.
  22712. * The parameter `parsedMesh` is the mesh to be copied.
  22713. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  22714. */
  22715. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  22716. var mesh;
  22717. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  22718. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  22719. }
  22720. else {
  22721. mesh = new Mesh(parsedMesh.name, scene);
  22722. }
  22723. mesh.id = parsedMesh.id;
  22724. if (BABYLON.Tags) {
  22725. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  22726. }
  22727. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  22728. if (parsedMesh.metadata !== undefined) {
  22729. mesh.metadata = parsedMesh.metadata;
  22730. }
  22731. if (parsedMesh.rotationQuaternion) {
  22732. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  22733. }
  22734. else if (parsedMesh.rotation) {
  22735. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  22736. }
  22737. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  22738. if (parsedMesh.localMatrix) {
  22739. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  22740. }
  22741. else if (parsedMesh.pivotMatrix) {
  22742. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  22743. }
  22744. mesh.setEnabled(parsedMesh.isEnabled);
  22745. mesh.isVisible = parsedMesh.isVisible;
  22746. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  22747. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  22748. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  22749. if (parsedMesh.applyFog !== undefined) {
  22750. mesh.applyFog = parsedMesh.applyFog;
  22751. }
  22752. if (parsedMesh.pickable !== undefined) {
  22753. mesh.isPickable = parsedMesh.pickable;
  22754. }
  22755. if (parsedMesh.alphaIndex !== undefined) {
  22756. mesh.alphaIndex = parsedMesh.alphaIndex;
  22757. }
  22758. mesh.receiveShadows = parsedMesh.receiveShadows;
  22759. mesh.billboardMode = parsedMesh.billboardMode;
  22760. if (parsedMesh.visibility !== undefined) {
  22761. mesh.visibility = parsedMesh.visibility;
  22762. }
  22763. mesh.checkCollisions = parsedMesh.checkCollisions;
  22764. if (parsedMesh.isBlocker !== undefined) {
  22765. mesh.isBlocker = parsedMesh.isBlocker;
  22766. }
  22767. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  22768. // freezeWorldMatrix
  22769. if (parsedMesh.freezeWorldMatrix) {
  22770. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  22771. }
  22772. // Parent
  22773. if (parsedMesh.parentId) {
  22774. mesh._waitingParentId = parsedMesh.parentId;
  22775. }
  22776. // Actions
  22777. if (parsedMesh.actions !== undefined) {
  22778. mesh._waitingActions = parsedMesh.actions;
  22779. }
  22780. // Overlay
  22781. if (parsedMesh.overlayAlpha !== undefined) {
  22782. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  22783. }
  22784. if (parsedMesh.overlayColor !== undefined) {
  22785. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  22786. }
  22787. if (parsedMesh.renderOverlay !== undefined) {
  22788. mesh.renderOverlay = parsedMesh.renderOverlay;
  22789. }
  22790. // Geometry
  22791. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  22792. if (parsedMesh.delayLoadingFile) {
  22793. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22794. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  22795. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  22796. if (parsedMesh._binaryInfo) {
  22797. mesh._binaryInfo = parsedMesh._binaryInfo;
  22798. }
  22799. mesh._delayInfo = [];
  22800. if (parsedMesh.hasUVs) {
  22801. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  22802. }
  22803. if (parsedMesh.hasUVs2) {
  22804. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  22805. }
  22806. if (parsedMesh.hasUVs3) {
  22807. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  22808. }
  22809. if (parsedMesh.hasUVs4) {
  22810. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  22811. }
  22812. if (parsedMesh.hasUVs5) {
  22813. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  22814. }
  22815. if (parsedMesh.hasUVs6) {
  22816. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  22817. }
  22818. if (parsedMesh.hasColors) {
  22819. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  22820. }
  22821. if (parsedMesh.hasMatricesIndices) {
  22822. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  22823. }
  22824. if (parsedMesh.hasMatricesWeights) {
  22825. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  22826. }
  22827. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  22828. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  22829. mesh._checkDelayState();
  22830. }
  22831. }
  22832. else {
  22833. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  22834. }
  22835. // Material
  22836. if (parsedMesh.materialId) {
  22837. mesh.setMaterialByID(parsedMesh.materialId);
  22838. }
  22839. else {
  22840. mesh.material = null;
  22841. }
  22842. // Morph targets
  22843. if (parsedMesh.morphTargetManagerId > -1) {
  22844. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  22845. }
  22846. // Skeleton
  22847. if (parsedMesh.skeletonId > -1) {
  22848. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  22849. if (parsedMesh.numBoneInfluencers) {
  22850. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  22851. }
  22852. }
  22853. // Animations
  22854. if (parsedMesh.animations) {
  22855. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  22856. var parsedAnimation = parsedMesh.animations[animationIndex];
  22857. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22858. }
  22859. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  22860. }
  22861. if (parsedMesh.autoAnimate) {
  22862. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  22863. }
  22864. // Layer Mask
  22865. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  22866. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  22867. }
  22868. else {
  22869. mesh.layerMask = 0x0FFFFFFF;
  22870. }
  22871. // Physics
  22872. if (parsedMesh.physicsImpostor) {
  22873. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  22874. mass: parsedMesh.physicsMass,
  22875. friction: parsedMesh.physicsFriction,
  22876. restitution: parsedMesh.physicsRestitution
  22877. }, scene);
  22878. }
  22879. // Instances
  22880. if (parsedMesh.instances) {
  22881. for (var index = 0; index < parsedMesh.instances.length; index++) {
  22882. var parsedInstance = parsedMesh.instances[index];
  22883. var instance = mesh.createInstance(parsedInstance.name);
  22884. if (BABYLON.Tags) {
  22885. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  22886. }
  22887. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  22888. if (parsedInstance.parentId) {
  22889. instance._waitingParentId = parsedInstance.parentId;
  22890. }
  22891. if (parsedInstance.rotationQuaternion) {
  22892. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  22893. }
  22894. else if (parsedInstance.rotation) {
  22895. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  22896. }
  22897. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  22898. instance.checkCollisions = mesh.checkCollisions;
  22899. if (parsedMesh.animations) {
  22900. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  22901. parsedAnimation = parsedMesh.animations[animationIndex];
  22902. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22903. }
  22904. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  22905. }
  22906. }
  22907. }
  22908. return mesh;
  22909. };
  22910. /**
  22911. * Creates a ribbon mesh.
  22912. * Please consider using the same method from the MeshBuilder class instead.
  22913. * 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.
  22914. *
  22915. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  22916. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  22917. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  22918. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  22919. * 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.
  22920. * 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.
  22921. * 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
  22922. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22923. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22924. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22925. */
  22926. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  22927. return BABYLON.MeshBuilder.CreateRibbon(name, {
  22928. pathArray: pathArray,
  22929. closeArray: closeArray,
  22930. closePath: closePath,
  22931. offset: offset,
  22932. updatable: updatable,
  22933. sideOrientation: sideOrientation,
  22934. instance: instance
  22935. }, scene);
  22936. };
  22937. /**
  22938. * Creates a plane polygonal mesh. By default, this is a disc.
  22939. * Please consider using the same method from the MeshBuilder class instead.
  22940. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  22941. * 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.
  22942. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22943. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22944. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22945. */
  22946. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  22947. var options = {
  22948. radius: radius,
  22949. tessellation: tessellation,
  22950. sideOrientation: sideOrientation,
  22951. updatable: updatable
  22952. };
  22953. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  22954. };
  22955. /**
  22956. * Creates a box mesh.
  22957. * Please consider using the same method from the MeshBuilder class instead.
  22958. * The parameter `size` sets the size (float) of each box side (default 1).
  22959. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22960. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22961. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22962. */
  22963. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  22964. var options = {
  22965. size: size,
  22966. sideOrientation: sideOrientation,
  22967. updatable: updatable
  22968. };
  22969. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  22970. };
  22971. /**
  22972. * Creates a sphere mesh.
  22973. * Please consider using the same method from the MeshBuilder class instead.
  22974. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  22975. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  22976. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22977. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22978. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22979. */
  22980. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  22981. var options = {
  22982. segments: segments,
  22983. diameterX: diameter,
  22984. diameterY: diameter,
  22985. diameterZ: diameter,
  22986. sideOrientation: sideOrientation,
  22987. updatable: updatable
  22988. };
  22989. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  22990. };
  22991. /**
  22992. * Creates a cylinder or a cone mesh.
  22993. * Please consider using the same method from the MeshBuilder class instead.
  22994. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  22995. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  22996. * 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.
  22997. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  22998. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  22999. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23000. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23001. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23002. */
  23003. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  23004. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  23005. if (scene !== undefined) {
  23006. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  23007. updatable = scene;
  23008. }
  23009. scene = subdivisions;
  23010. subdivisions = 1;
  23011. }
  23012. var options = {
  23013. height: height,
  23014. diameterTop: diameterTop,
  23015. diameterBottom: diameterBottom,
  23016. tessellation: tessellation,
  23017. subdivisions: subdivisions,
  23018. sideOrientation: sideOrientation,
  23019. updatable: updatable
  23020. };
  23021. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  23022. };
  23023. // Torus (Code from SharpDX.org)
  23024. /**
  23025. * Creates a torus mesh.
  23026. * Please consider using the same method from the MeshBuilder class instead.
  23027. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  23028. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  23029. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  23030. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23031. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23032. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23033. */
  23034. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  23035. var options = {
  23036. diameter: diameter,
  23037. thickness: thickness,
  23038. tessellation: tessellation,
  23039. sideOrientation: sideOrientation,
  23040. updatable: updatable
  23041. };
  23042. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  23043. };
  23044. /**
  23045. * Creates a torus knot mesh.
  23046. * Please consider using the same method from the MeshBuilder class instead.
  23047. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  23048. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  23049. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  23050. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  23051. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23052. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23053. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23054. */
  23055. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  23056. var options = {
  23057. radius: radius,
  23058. tube: tube,
  23059. radialSegments: radialSegments,
  23060. tubularSegments: tubularSegments,
  23061. p: p,
  23062. q: q,
  23063. sideOrientation: sideOrientation,
  23064. updatable: updatable
  23065. };
  23066. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  23067. };
  23068. /**
  23069. * Creates a line mesh.
  23070. * Please consider using the same method from the MeshBuilder class instead.
  23071. * 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.
  23072. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23073. * The parameter `points` is an array successive Vector3.
  23074. * 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
  23075. * When updating an instance, remember that only point positions can change, not the number of points.
  23076. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23077. */
  23078. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  23079. var options = {
  23080. points: points,
  23081. updatable: updatable,
  23082. instance: instance
  23083. };
  23084. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  23085. };
  23086. /**
  23087. * Creates a dashed line mesh.
  23088. * Please consider using the same method from the MeshBuilder class instead.
  23089. * 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.
  23090. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23091. * The parameter `points` is an array successive Vector3.
  23092. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  23093. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  23094. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  23095. * 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
  23096. * When updating an instance, remember that only point positions can change, not the number of points.
  23097. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23098. */
  23099. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  23100. var options = {
  23101. points: points,
  23102. dashSize: dashSize,
  23103. gapSize: gapSize,
  23104. dashNb: dashNb,
  23105. updatable: updatable,
  23106. instance: instance
  23107. };
  23108. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  23109. };
  23110. /**
  23111. * Creates a polygon mesh.
  23112. * Please consider using the same method from the MeshBuilder class instead.
  23113. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  23114. * 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.
  23115. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23116. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23117. * Remember you can only change the shape positions, not their number when updating a polygon.
  23118. */
  23119. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  23120. var options = {
  23121. shape: shape,
  23122. holes: holes,
  23123. updatable: updatable,
  23124. sideOrientation: sideOrientation
  23125. };
  23126. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  23127. };
  23128. /**
  23129. * Creates an extruded polygon mesh, with depth in the Y direction.
  23130. * Please consider using the same method from the MeshBuilder class instead.
  23131. */
  23132. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  23133. var options = {
  23134. shape: shape,
  23135. holes: holes,
  23136. depth: depth,
  23137. updatable: updatable,
  23138. sideOrientation: sideOrientation
  23139. };
  23140. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  23141. };
  23142. /**
  23143. * Creates an extruded shape mesh.
  23144. * 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.
  23145. * Please consider using the same method from the MeshBuilder class instead.
  23146. *
  23147. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23148. * 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
  23149. * extruded along the Z axis.
  23150. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23151. * 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.
  23152. * The parameter `scale` (float, default 1) is the value to scale the shape.
  23153. * 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
  23154. * 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
  23155. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23156. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23157. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23158. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23159. */
  23160. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  23161. var options = {
  23162. shape: shape,
  23163. path: path,
  23164. scale: scale,
  23165. rotation: rotation,
  23166. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  23167. sideOrientation: sideOrientation,
  23168. instance: instance,
  23169. updatable: updatable
  23170. };
  23171. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  23172. };
  23173. /**
  23174. * Creates an custom extruded shape mesh.
  23175. * 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.
  23176. * Please consider using the same method from the MeshBuilder class instead.
  23177. *
  23178. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23179. * 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
  23180. * extruded along the Z axis.
  23181. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23182. * 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
  23183. * and the distance of this point from the begining of the path :
  23184. * ```javascript
  23185. * var rotationFunction = function(i, distance) {
  23186. * // do things
  23187. * return rotationValue; }
  23188. * ```
  23189. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  23190. * 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
  23191. * and the distance of this point from the begining of the path :
  23192. * ```javascript
  23193. * var scaleFunction = function(i, distance) {
  23194. * // do things
  23195. * return scaleValue;}
  23196. * ```
  23197. * It must returns a float value that will be the scale value applied to the shape on each path point.
  23198. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  23199. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  23200. * 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
  23201. * 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
  23202. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23203. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23204. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23205. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23206. */
  23207. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  23208. var options = {
  23209. shape: shape,
  23210. path: path,
  23211. scaleFunction: scaleFunction,
  23212. rotationFunction: rotationFunction,
  23213. ribbonCloseArray: ribbonCloseArray,
  23214. ribbonClosePath: ribbonClosePath,
  23215. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  23216. sideOrientation: sideOrientation,
  23217. instance: instance,
  23218. updatable: updatable
  23219. };
  23220. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  23221. };
  23222. /**
  23223. * Creates lathe mesh.
  23224. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  23225. * Please consider using the same method from the MeshBuilder class instead.
  23226. * 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
  23227. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  23228. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  23229. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  23230. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23231. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23232. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23233. */
  23234. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  23235. var options = {
  23236. shape: shape,
  23237. radius: radius,
  23238. tessellation: tessellation,
  23239. sideOrientation: sideOrientation,
  23240. updatable: updatable
  23241. };
  23242. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  23243. };
  23244. /**
  23245. * Creates a plane mesh.
  23246. * Please consider using the same method from the MeshBuilder class instead.
  23247. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  23248. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23249. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23250. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23251. */
  23252. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  23253. var options = {
  23254. size: size,
  23255. width: size,
  23256. height: size,
  23257. sideOrientation: sideOrientation,
  23258. updatable: updatable
  23259. };
  23260. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  23261. };
  23262. /**
  23263. * Creates a ground mesh.
  23264. * Please consider using the same method from the MeshBuilder class instead.
  23265. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  23266. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  23267. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23268. */
  23269. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  23270. var options = {
  23271. width: width,
  23272. height: height,
  23273. subdivisions: subdivisions,
  23274. updatable: updatable
  23275. };
  23276. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  23277. };
  23278. /**
  23279. * Creates a tiled ground mesh.
  23280. * Please consider using the same method from the MeshBuilder class instead.
  23281. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  23282. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  23283. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  23284. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  23285. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  23286. * numbers of subdivisions on the ground width and height of each tile.
  23287. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23288. */
  23289. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  23290. var options = {
  23291. xmin: xmin,
  23292. zmin: zmin,
  23293. xmax: xmax,
  23294. zmax: zmax,
  23295. subdivisions: subdivisions,
  23296. precision: precision,
  23297. updatable: updatable
  23298. };
  23299. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  23300. };
  23301. /**
  23302. * Creates a ground mesh from a height map.
  23303. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  23304. * Please consider using the same method from the MeshBuilder class instead.
  23305. * The parameter `url` sets the URL of the height map image resource.
  23306. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  23307. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  23308. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  23309. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  23310. * 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).
  23311. * This function is passed the newly built mesh :
  23312. * ```javascript
  23313. * function(mesh) { // do things
  23314. * return; }
  23315. * ```
  23316. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23317. */
  23318. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  23319. var options = {
  23320. width: width,
  23321. height: height,
  23322. subdivisions: subdivisions,
  23323. minHeight: minHeight,
  23324. maxHeight: maxHeight,
  23325. updatable: updatable,
  23326. onReady: onReady
  23327. };
  23328. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  23329. };
  23330. /**
  23331. * Creates a tube mesh.
  23332. * 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.
  23333. * Please consider using the same method from the MeshBuilder class instead.
  23334. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  23335. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  23336. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  23337. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  23338. * 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.
  23339. * It must return a radius value (positive float) :
  23340. * ```javascript
  23341. * var radiusFunction = function(i, distance) {
  23342. * // do things
  23343. * return radius; }
  23344. * ```
  23345. * 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
  23346. * 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
  23347. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23348. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23349. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23350. */
  23351. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  23352. var options = {
  23353. path: path,
  23354. radius: radius,
  23355. tessellation: tessellation,
  23356. radiusFunction: radiusFunction,
  23357. arc: 1,
  23358. cap: cap,
  23359. updatable: updatable,
  23360. sideOrientation: sideOrientation,
  23361. instance: instance
  23362. };
  23363. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  23364. };
  23365. /**
  23366. * Creates a polyhedron mesh.
  23367. * Please consider using the same method from the MeshBuilder class instead.
  23368. * 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
  23369. * to choose the wanted type.
  23370. * The parameter `size` (positive float, default 1) sets the polygon size.
  23371. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  23372. * 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`.
  23373. * 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
  23374. * 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)`).
  23375. * 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
  23376. * 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.
  23377. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23378. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23379. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23380. */
  23381. Mesh.CreatePolyhedron = function (name, options, scene) {
  23382. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  23383. };
  23384. /**
  23385. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  23386. * Please consider using the same method from the MeshBuilder class instead.
  23387. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  23388. * 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`).
  23389. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  23390. * 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.
  23391. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23392. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23393. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23394. */
  23395. Mesh.CreateIcoSphere = function (name, options, scene) {
  23396. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  23397. };
  23398. /**
  23399. * Creates a decal mesh.
  23400. * Please consider using the same method from the MeshBuilder class instead.
  23401. * 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.
  23402. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  23403. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  23404. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  23405. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  23406. */
  23407. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  23408. var options = {
  23409. position: position,
  23410. normal: normal,
  23411. size: size,
  23412. angle: angle
  23413. };
  23414. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  23415. };
  23416. // Skeletons
  23417. /**
  23418. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  23419. */
  23420. Mesh.prototype.setPositionsForCPUSkinning = function () {
  23421. var source;
  23422. if (!this._sourcePositions) {
  23423. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23424. this._sourcePositions = new Float32Array(source);
  23425. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  23426. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  23427. }
  23428. }
  23429. return this._sourcePositions;
  23430. };
  23431. /**
  23432. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  23433. */
  23434. Mesh.prototype.setNormalsForCPUSkinning = function () {
  23435. var source;
  23436. if (!this._sourceNormals) {
  23437. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23438. this._sourceNormals = new Float32Array(source);
  23439. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  23440. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  23441. }
  23442. }
  23443. return this._sourceNormals;
  23444. };
  23445. /**
  23446. * Updates the vertex buffer by applying transformation from the bones.
  23447. * Returns the Mesh.
  23448. *
  23449. * @param {skeleton} skeleton to apply
  23450. */
  23451. Mesh.prototype.applySkeleton = function (skeleton) {
  23452. if (!this.geometry) {
  23453. return this;
  23454. }
  23455. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  23456. return this;
  23457. }
  23458. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  23459. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23460. return this;
  23461. }
  23462. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23463. return this;
  23464. }
  23465. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23466. return this;
  23467. }
  23468. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23469. return this;
  23470. }
  23471. if (!this._sourcePositions) {
  23472. var submeshes = this.subMeshes.slice();
  23473. this.setPositionsForCPUSkinning();
  23474. this.subMeshes = submeshes;
  23475. }
  23476. if (!this._sourceNormals) {
  23477. this.setNormalsForCPUSkinning();
  23478. }
  23479. // positionsData checks for not being Float32Array will only pass at most once
  23480. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23481. if (!(positionsData instanceof Float32Array)) {
  23482. positionsData = new Float32Array(positionsData);
  23483. }
  23484. // normalsData checks for not being Float32Array will only pass at most once
  23485. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23486. if (!(normalsData instanceof Float32Array)) {
  23487. normalsData = new Float32Array(normalsData);
  23488. }
  23489. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  23490. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  23491. var needExtras = this.numBoneInfluencers > 4;
  23492. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  23493. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  23494. var skeletonMatrices = skeleton.getTransformMatrices(this);
  23495. var tempVector3 = BABYLON.Vector3.Zero();
  23496. var finalMatrix = new BABYLON.Matrix();
  23497. var tempMatrix = new BABYLON.Matrix();
  23498. var matWeightIdx = 0;
  23499. var inf;
  23500. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  23501. var weight;
  23502. for (inf = 0; inf < 4; inf++) {
  23503. weight = matricesWeightsData[matWeightIdx + inf];
  23504. if (weight > 0) {
  23505. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23506. finalMatrix.addToSelf(tempMatrix);
  23507. }
  23508. else
  23509. break;
  23510. }
  23511. if (needExtras) {
  23512. for (inf = 0; inf < 4; inf++) {
  23513. weight = matricesWeightsExtraData[matWeightIdx + inf];
  23514. if (weight > 0) {
  23515. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23516. finalMatrix.addToSelf(tempMatrix);
  23517. }
  23518. else
  23519. break;
  23520. }
  23521. }
  23522. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  23523. tempVector3.toArray(positionsData, index);
  23524. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  23525. tempVector3.toArray(normalsData, index);
  23526. finalMatrix.reset();
  23527. }
  23528. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  23529. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  23530. return this;
  23531. };
  23532. // Tools
  23533. /**
  23534. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  23535. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  23536. */
  23537. Mesh.MinMax = function (meshes) {
  23538. var minVector = null;
  23539. var maxVector = null;
  23540. meshes.forEach(function (mesh, index, array) {
  23541. var boundingBox = mesh.getBoundingInfo().boundingBox;
  23542. if (!minVector) {
  23543. minVector = boundingBox.minimumWorld;
  23544. maxVector = boundingBox.maximumWorld;
  23545. }
  23546. else {
  23547. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  23548. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  23549. }
  23550. });
  23551. return {
  23552. min: minVector,
  23553. max: maxVector
  23554. };
  23555. };
  23556. /**
  23557. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  23558. */
  23559. Mesh.Center = function (meshesOrMinMaxVector) {
  23560. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  23561. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  23562. };
  23563. /**
  23564. * Merge the array of meshes into a single mesh for performance reasons.
  23565. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  23566. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  23567. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  23568. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  23569. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  23570. */
  23571. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  23572. if (disposeSource === void 0) { disposeSource = true; }
  23573. var index;
  23574. if (!allow32BitsIndices) {
  23575. var totalVertices = 0;
  23576. // Counting vertices
  23577. for (index = 0; index < meshes.length; index++) {
  23578. if (meshes[index]) {
  23579. totalVertices += meshes[index].getTotalVertices();
  23580. if (totalVertices > 65536) {
  23581. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  23582. return null;
  23583. }
  23584. }
  23585. }
  23586. }
  23587. // Merge
  23588. var vertexData;
  23589. var otherVertexData;
  23590. var indiceArray = new Array();
  23591. var source;
  23592. for (index = 0; index < meshes.length; index++) {
  23593. if (meshes[index]) {
  23594. meshes[index].computeWorldMatrix(true);
  23595. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  23596. otherVertexData.transform(meshes[index].getWorldMatrix());
  23597. if (vertexData) {
  23598. vertexData.merge(otherVertexData);
  23599. }
  23600. else {
  23601. vertexData = otherVertexData;
  23602. source = meshes[index];
  23603. }
  23604. if (subdivideWithSubMeshes) {
  23605. indiceArray.push(meshes[index].getTotalIndices());
  23606. }
  23607. }
  23608. }
  23609. if (!meshSubclass) {
  23610. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  23611. }
  23612. vertexData.applyToMesh(meshSubclass);
  23613. // Setting properties
  23614. meshSubclass.material = source.material;
  23615. meshSubclass.checkCollisions = source.checkCollisions;
  23616. // Cleaning
  23617. if (disposeSource) {
  23618. for (index = 0; index < meshes.length; index++) {
  23619. if (meshes[index]) {
  23620. meshes[index].dispose();
  23621. }
  23622. }
  23623. }
  23624. // Subdivide
  23625. if (subdivideWithSubMeshes) {
  23626. //-- Suppresions du submesh global
  23627. meshSubclass.releaseSubMeshes();
  23628. index = 0;
  23629. var offset = 0;
  23630. //-- aplique la subdivision en fonction du tableau d'indices
  23631. while (index < indiceArray.length) {
  23632. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  23633. offset += indiceArray[index];
  23634. index++;
  23635. }
  23636. }
  23637. return meshSubclass;
  23638. };
  23639. // Consts
  23640. Mesh._FRONTSIDE = 0;
  23641. Mesh._BACKSIDE = 1;
  23642. Mesh._DOUBLESIDE = 2;
  23643. Mesh._DEFAULTSIDE = 0;
  23644. Mesh._NO_CAP = 0;
  23645. Mesh._CAP_START = 1;
  23646. Mesh._CAP_END = 2;
  23647. Mesh._CAP_ALL = 3;
  23648. return Mesh;
  23649. }(BABYLON.AbstractMesh));
  23650. BABYLON.Mesh = Mesh;
  23651. })(BABYLON || (BABYLON = {}));
  23652. //# sourceMappingURL=babylon.mesh.js.map
  23653. var BABYLON;
  23654. (function (BABYLON) {
  23655. var BaseSubMesh = (function () {
  23656. function BaseSubMesh() {
  23657. }
  23658. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  23659. get: function () {
  23660. return this._materialEffect;
  23661. },
  23662. enumerable: true,
  23663. configurable: true
  23664. });
  23665. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  23666. if (this._materialEffect === effect) {
  23667. if (!effect) {
  23668. this._materialDefines = undefined;
  23669. }
  23670. return;
  23671. }
  23672. this._materialDefines = defines;
  23673. this._materialEffect = effect;
  23674. };
  23675. return BaseSubMesh;
  23676. }());
  23677. BABYLON.BaseSubMesh = BaseSubMesh;
  23678. var SubMesh = (function (_super) {
  23679. __extends(SubMesh, _super);
  23680. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  23681. if (createBoundingBox === void 0) { createBoundingBox = true; }
  23682. var _this = _super.call(this) || this;
  23683. _this.materialIndex = materialIndex;
  23684. _this.verticesStart = verticesStart;
  23685. _this.verticesCount = verticesCount;
  23686. _this.indexStart = indexStart;
  23687. _this.indexCount = indexCount;
  23688. _this._renderId = 0;
  23689. _this._mesh = mesh;
  23690. _this._renderingMesh = renderingMesh || mesh;
  23691. mesh.subMeshes.push(_this);
  23692. _this._trianglePlanes = [];
  23693. _this._id = mesh.subMeshes.length - 1;
  23694. if (createBoundingBox) {
  23695. _this.refreshBoundingInfo();
  23696. mesh.computeWorldMatrix(true);
  23697. }
  23698. return _this;
  23699. }
  23700. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  23701. get: function () {
  23702. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  23703. },
  23704. enumerable: true,
  23705. configurable: true
  23706. });
  23707. /**
  23708. * Returns the submesh BoudingInfo object.
  23709. */
  23710. SubMesh.prototype.getBoundingInfo = function () {
  23711. if (this.IsGlobal) {
  23712. return this._mesh.getBoundingInfo();
  23713. }
  23714. return this._boundingInfo;
  23715. };
  23716. /**
  23717. * Sets the submesh BoundingInfo.
  23718. * Return the SubMesh.
  23719. */
  23720. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  23721. this._boundingInfo = boundingInfo;
  23722. return this;
  23723. };
  23724. /**
  23725. * Returns the mesh of the current submesh.
  23726. */
  23727. SubMesh.prototype.getMesh = function () {
  23728. return this._mesh;
  23729. };
  23730. /**
  23731. * Returns the rendering mesh of the submesh.
  23732. */
  23733. SubMesh.prototype.getRenderingMesh = function () {
  23734. return this._renderingMesh;
  23735. };
  23736. /**
  23737. * Returns the submesh material.
  23738. */
  23739. SubMesh.prototype.getMaterial = function () {
  23740. var rootMaterial = this._renderingMesh.material;
  23741. if (rootMaterial && rootMaterial.getSubMaterial) {
  23742. var multiMaterial = rootMaterial;
  23743. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  23744. if (this._currentMaterial !== effectiveMaterial) {
  23745. this._currentMaterial = effectiveMaterial;
  23746. this._materialDefines = undefined;
  23747. }
  23748. return effectiveMaterial;
  23749. }
  23750. if (!rootMaterial) {
  23751. return this._mesh.getScene().defaultMaterial;
  23752. }
  23753. return rootMaterial;
  23754. };
  23755. // Methods
  23756. /**
  23757. * Sets a new updated BoundingInfo object to the submesh.
  23758. * Returns the SubMesh.
  23759. */
  23760. SubMesh.prototype.refreshBoundingInfo = function () {
  23761. this._lastColliderWorldVertices = null;
  23762. if (this.IsGlobal) {
  23763. return;
  23764. }
  23765. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23766. if (!data) {
  23767. this._boundingInfo = this._mesh._boundingInfo;
  23768. return;
  23769. }
  23770. var indices = this._renderingMesh.getIndices();
  23771. var extend;
  23772. //is this the only submesh?
  23773. if (this.indexStart === 0 && this.indexCount === indices.length) {
  23774. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  23775. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  23776. }
  23777. else {
  23778. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  23779. }
  23780. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23781. return this;
  23782. };
  23783. SubMesh.prototype._checkCollision = function (collider) {
  23784. return this.getBoundingInfo()._checkCollision(collider);
  23785. };
  23786. /**
  23787. * Updates the submesh BoundingInfo.
  23788. * Returns the Submesh.
  23789. */
  23790. SubMesh.prototype.updateBoundingInfo = function (world) {
  23791. if (!this.getBoundingInfo()) {
  23792. this.refreshBoundingInfo();
  23793. }
  23794. this.getBoundingInfo().update(world);
  23795. return this;
  23796. };
  23797. /**
  23798. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  23799. * Boolean returned.
  23800. */
  23801. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  23802. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  23803. };
  23804. /**
  23805. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  23806. * Boolean returned.
  23807. */
  23808. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  23809. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  23810. };
  23811. /**
  23812. * Renders the submesh.
  23813. * Returns it.
  23814. */
  23815. SubMesh.prototype.render = function (enableAlphaMode) {
  23816. this._renderingMesh.render(this, enableAlphaMode);
  23817. return this;
  23818. };
  23819. /**
  23820. * Returns a new Index Buffer.
  23821. * Type returned : WebGLBuffer.
  23822. */
  23823. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  23824. if (!this._linesIndexBuffer) {
  23825. var linesIndices = [];
  23826. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  23827. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  23828. }
  23829. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  23830. this.linesIndexCount = linesIndices.length;
  23831. }
  23832. return this._linesIndexBuffer;
  23833. };
  23834. /**
  23835. * True is the passed Ray intersects the submesh bounding box.
  23836. * Boolean returned.
  23837. */
  23838. SubMesh.prototype.canIntersects = function (ray) {
  23839. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  23840. };
  23841. /**
  23842. * Returns an object IntersectionInfo.
  23843. */
  23844. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  23845. var intersectInfo = null;
  23846. // LineMesh first as it's also a Mesh...
  23847. if (this._mesh instanceof BABYLON.LinesMesh) {
  23848. var lineMesh = this._mesh;
  23849. // Line test
  23850. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  23851. var p0 = positions[indices[index]];
  23852. var p1 = positions[indices[index + 1]];
  23853. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  23854. if (length < 0) {
  23855. continue;
  23856. }
  23857. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  23858. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  23859. if (fastCheck) {
  23860. break;
  23861. }
  23862. }
  23863. }
  23864. }
  23865. else {
  23866. // Triangles test
  23867. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  23868. var p0 = positions[indices[index]];
  23869. var p1 = positions[indices[index + 1]];
  23870. var p2 = positions[indices[index + 2]];
  23871. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  23872. if (currentIntersectInfo) {
  23873. if (currentIntersectInfo.distance < 0) {
  23874. continue;
  23875. }
  23876. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  23877. intersectInfo = currentIntersectInfo;
  23878. intersectInfo.faceId = index / 3;
  23879. if (fastCheck) {
  23880. break;
  23881. }
  23882. }
  23883. }
  23884. }
  23885. }
  23886. return intersectInfo;
  23887. };
  23888. SubMesh.prototype._rebuild = function () {
  23889. if (this._linesIndexBuffer) {
  23890. this._linesIndexBuffer = null;
  23891. }
  23892. };
  23893. // Clone
  23894. /**
  23895. * Creates a new Submesh from the passed Mesh.
  23896. */
  23897. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  23898. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  23899. if (!this.IsGlobal) {
  23900. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  23901. }
  23902. return result;
  23903. };
  23904. // Dispose
  23905. /**
  23906. * Disposes the Submesh.
  23907. * Returns nothing.
  23908. */
  23909. SubMesh.prototype.dispose = function () {
  23910. if (this._linesIndexBuffer) {
  23911. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  23912. this._linesIndexBuffer = null;
  23913. }
  23914. // Remove from mesh
  23915. var index = this._mesh.subMeshes.indexOf(this);
  23916. this._mesh.subMeshes.splice(index, 1);
  23917. };
  23918. // Statics
  23919. /**
  23920. * Creates a new Submesh from the passed parameters :
  23921. * - materialIndex (integer) : the index of the main mesh material.
  23922. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  23923. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  23924. * - mesh (Mesh) : the main mesh to create the submesh from.
  23925. * - renderingMesh (optional Mesh) : rendering mesh.
  23926. */
  23927. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  23928. var minVertexIndex = Number.MAX_VALUE;
  23929. var maxVertexIndex = -Number.MAX_VALUE;
  23930. renderingMesh = renderingMesh || mesh;
  23931. var indices = renderingMesh.getIndices();
  23932. for (var index = startIndex; index < startIndex + indexCount; index++) {
  23933. var vertexIndex = indices[index];
  23934. if (vertexIndex < minVertexIndex)
  23935. minVertexIndex = vertexIndex;
  23936. if (vertexIndex > maxVertexIndex)
  23937. maxVertexIndex = vertexIndex;
  23938. }
  23939. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  23940. };
  23941. return SubMesh;
  23942. }(BaseSubMesh));
  23943. BABYLON.SubMesh = SubMesh;
  23944. })(BABYLON || (BABYLON = {}));
  23945. //# sourceMappingURL=babylon.subMesh.js.map
  23946. var BABYLON;
  23947. (function (BABYLON) {
  23948. var EffectFallbacks = (function () {
  23949. function EffectFallbacks() {
  23950. this._defines = {};
  23951. this._currentRank = 32;
  23952. this._maxRank = -1;
  23953. }
  23954. EffectFallbacks.prototype.unBindMesh = function () {
  23955. this._mesh = null;
  23956. };
  23957. EffectFallbacks.prototype.addFallback = function (rank, define) {
  23958. if (!this._defines[rank]) {
  23959. if (rank < this._currentRank) {
  23960. this._currentRank = rank;
  23961. }
  23962. if (rank > this._maxRank) {
  23963. this._maxRank = rank;
  23964. }
  23965. this._defines[rank] = new Array();
  23966. }
  23967. this._defines[rank].push(define);
  23968. };
  23969. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  23970. this._meshRank = rank;
  23971. this._mesh = mesh;
  23972. if (rank < this._currentRank) {
  23973. this._currentRank = rank;
  23974. }
  23975. if (rank > this._maxRank) {
  23976. this._maxRank = rank;
  23977. }
  23978. };
  23979. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  23980. get: function () {
  23981. return this._currentRank <= this._maxRank;
  23982. },
  23983. enumerable: true,
  23984. configurable: true
  23985. });
  23986. EffectFallbacks.prototype.reduce = function (currentDefines) {
  23987. // First we try to switch to CPU skinning
  23988. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  23989. this._mesh.computeBonesUsingShaders = false;
  23990. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  23991. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  23992. var scene = this._mesh.getScene();
  23993. for (var index = 0; index < scene.meshes.length; index++) {
  23994. var otherMesh = scene.meshes[index];
  23995. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  23996. otherMesh.computeBonesUsingShaders = false;
  23997. }
  23998. }
  23999. }
  24000. else {
  24001. var currentFallbacks = this._defines[this._currentRank];
  24002. if (currentFallbacks) {
  24003. for (var index = 0; index < currentFallbacks.length; index++) {
  24004. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  24005. }
  24006. }
  24007. this._currentRank++;
  24008. }
  24009. return currentDefines;
  24010. };
  24011. return EffectFallbacks;
  24012. }());
  24013. BABYLON.EffectFallbacks = EffectFallbacks;
  24014. var EffectCreationOptions = (function () {
  24015. function EffectCreationOptions() {
  24016. }
  24017. return EffectCreationOptions;
  24018. }());
  24019. BABYLON.EffectCreationOptions = EffectCreationOptions;
  24020. var Effect = (function () {
  24021. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  24022. var _this = this;
  24023. this.uniqueId = 0;
  24024. this.onCompileObservable = new BABYLON.Observable();
  24025. this.onErrorObservable = new BABYLON.Observable();
  24026. this.onBindObservable = new BABYLON.Observable();
  24027. this._uniformBuffersNames = {};
  24028. this._isReady = false;
  24029. this._compilationError = "";
  24030. this.name = baseName;
  24031. if (attributesNamesOrOptions.attributes) {
  24032. var options = attributesNamesOrOptions;
  24033. this._engine = uniformsNamesOrEngine;
  24034. this._attributesNames = options.attributes;
  24035. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  24036. this._samplers = options.samplers;
  24037. this.defines = options.defines;
  24038. this.onError = options.onError;
  24039. this.onCompiled = options.onCompiled;
  24040. this._fallbacks = options.fallbacks;
  24041. this._indexParameters = options.indexParameters;
  24042. if (options.uniformBuffersNames) {
  24043. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  24044. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  24045. }
  24046. }
  24047. }
  24048. else {
  24049. this._engine = engine;
  24050. this.defines = defines;
  24051. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  24052. this._samplers = samplers;
  24053. this._attributesNames = attributesNamesOrOptions;
  24054. this.onError = onError;
  24055. this.onCompiled = onCompiled;
  24056. this._indexParameters = indexParameters;
  24057. this._fallbacks = fallbacks;
  24058. }
  24059. this.uniqueId = Effect._uniqueIdSeed++;
  24060. var vertexSource;
  24061. var fragmentSource;
  24062. if (baseName.vertexElement) {
  24063. vertexSource = document.getElementById(baseName.vertexElement);
  24064. if (!vertexSource) {
  24065. vertexSource = baseName.vertexElement;
  24066. }
  24067. }
  24068. else {
  24069. vertexSource = baseName.vertex || baseName;
  24070. }
  24071. if (baseName.fragmentElement) {
  24072. fragmentSource = document.getElementById(baseName.fragmentElement);
  24073. if (!fragmentSource) {
  24074. fragmentSource = baseName.fragmentElement;
  24075. }
  24076. }
  24077. else {
  24078. fragmentSource = baseName.fragment || baseName;
  24079. }
  24080. this._loadVertexShader(vertexSource, function (vertexCode) {
  24081. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  24082. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  24083. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  24084. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  24085. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  24086. if (baseName) {
  24087. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + baseName + "\n" + migratedVertexCode;
  24088. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + baseName + "\n" + migratedFragmentCode;
  24089. }
  24090. else {
  24091. _this._vertexSourceCode = migratedVertexCode;
  24092. _this._fragmentSourceCode = migratedFragmentCode;
  24093. }
  24094. _this._prepareEffect();
  24095. });
  24096. });
  24097. });
  24098. });
  24099. });
  24100. });
  24101. }
  24102. Object.defineProperty(Effect.prototype, "key", {
  24103. get: function () {
  24104. return this._key;
  24105. },
  24106. enumerable: true,
  24107. configurable: true
  24108. });
  24109. // Properties
  24110. Effect.prototype.isReady = function () {
  24111. return this._isReady;
  24112. };
  24113. Effect.prototype.getEngine = function () {
  24114. return this._engine;
  24115. };
  24116. Effect.prototype.getProgram = function () {
  24117. return this._program;
  24118. };
  24119. Effect.prototype.getAttributesNames = function () {
  24120. return this._attributesNames;
  24121. };
  24122. Effect.prototype.getAttributeLocation = function (index) {
  24123. return this._attributes[index];
  24124. };
  24125. Effect.prototype.getAttributeLocationByName = function (name) {
  24126. var index = this._attributesNames.indexOf(name);
  24127. return this._attributes[index];
  24128. };
  24129. Effect.prototype.getAttributesCount = function () {
  24130. return this._attributes.length;
  24131. };
  24132. Effect.prototype.getUniformIndex = function (uniformName) {
  24133. return this._uniformsNames.indexOf(uniformName);
  24134. };
  24135. Effect.prototype.getUniform = function (uniformName) {
  24136. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  24137. };
  24138. Effect.prototype.getSamplers = function () {
  24139. return this._samplers;
  24140. };
  24141. Effect.prototype.getCompilationError = function () {
  24142. return this._compilationError;
  24143. };
  24144. // Methods
  24145. Effect.prototype.executeWhenCompiled = function (func) {
  24146. if (this.isReady()) {
  24147. func(this);
  24148. return;
  24149. }
  24150. this.onCompileObservable.add(function (effect) {
  24151. func(effect);
  24152. });
  24153. };
  24154. Effect.prototype._loadVertexShader = function (vertex, callback) {
  24155. // DOM element ?
  24156. if (vertex instanceof HTMLElement) {
  24157. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  24158. callback(vertexCode);
  24159. return;
  24160. }
  24161. // Base64 encoded ?
  24162. if (vertex.substr(0, 7) === "base64:") {
  24163. var vertexBinary = window.atob(vertex.substr(7));
  24164. callback(vertexBinary);
  24165. return;
  24166. }
  24167. // Is in local store ?
  24168. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  24169. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  24170. return;
  24171. }
  24172. var vertexShaderUrl;
  24173. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  24174. vertexShaderUrl = vertex;
  24175. }
  24176. else {
  24177. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  24178. }
  24179. // Vertex shader
  24180. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  24181. };
  24182. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  24183. // DOM element ?
  24184. if (fragment instanceof HTMLElement) {
  24185. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  24186. callback(fragmentCode);
  24187. return;
  24188. }
  24189. // Base64 encoded ?
  24190. if (fragment.substr(0, 7) === "base64:") {
  24191. var fragmentBinary = window.atob(fragment.substr(7));
  24192. callback(fragmentBinary);
  24193. return;
  24194. }
  24195. // Is in local store ?
  24196. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  24197. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  24198. return;
  24199. }
  24200. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  24201. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  24202. return;
  24203. }
  24204. var fragmentShaderUrl;
  24205. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  24206. fragmentShaderUrl = fragment;
  24207. }
  24208. else {
  24209. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  24210. }
  24211. // Fragment shader
  24212. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  24213. };
  24214. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  24215. // Rebuild shaders source code
  24216. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  24217. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  24218. vertexCode = prefix + vertexCode;
  24219. fragmentCode = prefix + fragmentCode;
  24220. // Number lines of shaders source code
  24221. var i = 2;
  24222. var regex = /\n/gm;
  24223. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  24224. i = 2;
  24225. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  24226. // Dump shaders name and formatted source code
  24227. if (this.name.vertexElement) {
  24228. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  24229. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  24230. }
  24231. else if (this.name.vertex) {
  24232. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  24233. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  24234. }
  24235. else {
  24236. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  24237. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  24238. }
  24239. };
  24240. ;
  24241. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  24242. var preparedSourceCode = this._processPrecision(sourceCode);
  24243. if (this._engine.webGLVersion == 1) {
  24244. callback(preparedSourceCode);
  24245. return;
  24246. }
  24247. // Already converted
  24248. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  24249. callback(preparedSourceCode.replace("#version 300 es", ""));
  24250. return;
  24251. }
  24252. // Remove extensions
  24253. // #extension GL_OES_standard_derivatives : enable
  24254. // #extension GL_EXT_shader_texture_lod : enable
  24255. // #extension GL_EXT_frag_depth : enable
  24256. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  24257. var result = preparedSourceCode.replace(regex, "");
  24258. // Migrate to GLSL v300
  24259. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  24260. result = result.replace(/attribute[ \t]/g, "in ");
  24261. result = result.replace(/[ \t]attribute/g, " in");
  24262. if (isFragment) {
  24263. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  24264. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  24265. result = result.replace(/texture2D\(/g, "texture(");
  24266. result = result.replace(/textureCube\(/g, "texture(");
  24267. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  24268. result = result.replace(/gl_FragColor/g, "glFragColor");
  24269. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  24270. }
  24271. callback(result);
  24272. };
  24273. Effect.prototype._processIncludes = function (sourceCode, callback) {
  24274. var _this = this;
  24275. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  24276. var match = regex.exec(sourceCode);
  24277. var returnValue = new String(sourceCode);
  24278. while (match != null) {
  24279. var includeFile = match[1];
  24280. // Uniform declaration
  24281. if (includeFile.indexOf("__decl__") !== -1) {
  24282. includeFile = includeFile.replace(/__decl__/, "");
  24283. if (this._engine.webGLVersion != 1) {
  24284. includeFile = includeFile.replace(/Vertex/, "Ubo");
  24285. includeFile = includeFile.replace(/Fragment/, "Ubo");
  24286. }
  24287. includeFile = includeFile + "Declaration";
  24288. }
  24289. if (Effect.IncludesShadersStore[includeFile]) {
  24290. // Substitution
  24291. var includeContent = Effect.IncludesShadersStore[includeFile];
  24292. if (match[2]) {
  24293. var splits = match[3].split(",");
  24294. for (var index = 0; index < splits.length; index += 2) {
  24295. var source = new RegExp(splits[index], "g");
  24296. var dest = splits[index + 1];
  24297. includeContent = includeContent.replace(source, dest);
  24298. }
  24299. }
  24300. if (match[4]) {
  24301. var indexString = match[5];
  24302. if (indexString.indexOf("..") !== -1) {
  24303. var indexSplits = indexString.split("..");
  24304. var minIndex = parseInt(indexSplits[0]);
  24305. var maxIndex = parseInt(indexSplits[1]);
  24306. var sourceIncludeContent = includeContent.slice(0);
  24307. includeContent = "";
  24308. if (isNaN(maxIndex)) {
  24309. maxIndex = this._indexParameters[indexSplits[1]];
  24310. }
  24311. for (var i = minIndex; i < maxIndex; i++) {
  24312. if (this._engine.webGLVersion === 1) {
  24313. // Ubo replacement
  24314. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  24315. return p1 + "{X}";
  24316. });
  24317. }
  24318. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  24319. }
  24320. }
  24321. else {
  24322. if (this._engine.webGLVersion === 1) {
  24323. // Ubo replacement
  24324. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  24325. return p1 + "{X}";
  24326. });
  24327. }
  24328. includeContent = includeContent.replace(/\{X\}/g, indexString);
  24329. }
  24330. }
  24331. // Replace
  24332. returnValue = returnValue.replace(match[0], includeContent);
  24333. }
  24334. else {
  24335. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  24336. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  24337. Effect.IncludesShadersStore[includeFile] = fileContent;
  24338. _this._processIncludes(returnValue, callback);
  24339. });
  24340. return;
  24341. }
  24342. match = regex.exec(sourceCode);
  24343. }
  24344. callback(returnValue);
  24345. };
  24346. Effect.prototype._processPrecision = function (source) {
  24347. if (source.indexOf("precision highp float") === -1) {
  24348. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24349. source = "precision mediump float;\n" + source;
  24350. }
  24351. else {
  24352. source = "precision highp float;\n" + source;
  24353. }
  24354. }
  24355. else {
  24356. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24357. source = source.replace("precision highp float", "precision mediump float");
  24358. }
  24359. }
  24360. return source;
  24361. };
  24362. Effect.prototype._prepareEffect = function () {
  24363. var attributesNames = this._attributesNames;
  24364. var defines = this.defines;
  24365. var fallbacks = this._fallbacks;
  24366. this._valueCache = {};
  24367. try {
  24368. var engine = this._engine;
  24369. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines);
  24370. if (engine.webGLVersion > 1) {
  24371. for (var name in this._uniformBuffersNames) {
  24372. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  24373. }
  24374. }
  24375. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  24376. this._attributes = engine.getAttributes(this._program, attributesNames);
  24377. var index;
  24378. for (index = 0; index < this._samplers.length; index++) {
  24379. var sampler = this.getUniform(this._samplers[index]);
  24380. if (sampler == null) {
  24381. this._samplers.splice(index, 1);
  24382. index--;
  24383. }
  24384. }
  24385. engine.bindSamplers(this);
  24386. this._compilationError = "";
  24387. this._isReady = true;
  24388. if (this.onCompiled) {
  24389. this.onCompiled(this);
  24390. }
  24391. this.onCompileObservable.notifyObservers(this);
  24392. this.onCompileObservable.clear();
  24393. // Unbind mesh reference in fallbacks
  24394. if (this._fallbacks) {
  24395. this._fallbacks.unBindMesh();
  24396. }
  24397. }
  24398. catch (e) {
  24399. this._compilationError = e.message;
  24400. // Let's go through fallbacks then
  24401. BABYLON.Tools.Error("Unable to compile effect:");
  24402. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  24403. return " " + uniform;
  24404. }));
  24405. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  24406. return " " + attribute;
  24407. }));
  24408. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  24409. BABYLON.Tools.Error("Error: " + this._compilationError);
  24410. if (fallbacks && fallbacks.isMoreFallbacks) {
  24411. BABYLON.Tools.Error("Trying next fallback.");
  24412. this.defines = fallbacks.reduce(this.defines);
  24413. this._prepareEffect();
  24414. }
  24415. else {
  24416. if (this.onError) {
  24417. this.onError(this, this._compilationError);
  24418. }
  24419. this.onErrorObservable.notifyObservers(this);
  24420. this.onErrorObservable.clear();
  24421. // Unbind mesh reference in fallbacks
  24422. if (this._fallbacks) {
  24423. this._fallbacks.unBindMesh();
  24424. }
  24425. }
  24426. }
  24427. };
  24428. Object.defineProperty(Effect.prototype, "isSupported", {
  24429. get: function () {
  24430. return this._compilationError === "";
  24431. },
  24432. enumerable: true,
  24433. configurable: true
  24434. });
  24435. Effect.prototype._bindTexture = function (channel, texture) {
  24436. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  24437. };
  24438. Effect.prototype.setTexture = function (channel, texture) {
  24439. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  24440. };
  24441. Effect.prototype.setTextureArray = function (channel, textures) {
  24442. if (this._samplers.indexOf(channel + "Ex") === -1) {
  24443. var initialPos = this._samplers.indexOf(channel);
  24444. for (var index = 1; index < textures.length; index++) {
  24445. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  24446. }
  24447. }
  24448. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  24449. };
  24450. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  24451. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  24452. };
  24453. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  24454. var cache = this._valueCache[uniformName];
  24455. var flag = matrix.updateFlag;
  24456. if (cache !== undefined && cache === flag) {
  24457. return false;
  24458. }
  24459. this._valueCache[uniformName] = flag;
  24460. return true;
  24461. };
  24462. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  24463. var cache = this._valueCache[uniformName];
  24464. if (!cache) {
  24465. cache = [x, y];
  24466. this._valueCache[uniformName] = cache;
  24467. return true;
  24468. }
  24469. var changed = false;
  24470. if (cache[0] !== x) {
  24471. cache[0] = x;
  24472. changed = true;
  24473. }
  24474. if (cache[1] !== y) {
  24475. cache[1] = y;
  24476. changed = true;
  24477. }
  24478. return changed;
  24479. };
  24480. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  24481. var cache = this._valueCache[uniformName];
  24482. if (!cache) {
  24483. cache = [x, y, z];
  24484. this._valueCache[uniformName] = cache;
  24485. return true;
  24486. }
  24487. var changed = false;
  24488. if (cache[0] !== x) {
  24489. cache[0] = x;
  24490. changed = true;
  24491. }
  24492. if (cache[1] !== y) {
  24493. cache[1] = y;
  24494. changed = true;
  24495. }
  24496. if (cache[2] !== z) {
  24497. cache[2] = z;
  24498. changed = true;
  24499. }
  24500. return changed;
  24501. };
  24502. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  24503. var cache = this._valueCache[uniformName];
  24504. if (!cache) {
  24505. cache = [x, y, z, w];
  24506. this._valueCache[uniformName] = cache;
  24507. return true;
  24508. }
  24509. var changed = false;
  24510. if (cache[0] !== x) {
  24511. cache[0] = x;
  24512. changed = true;
  24513. }
  24514. if (cache[1] !== y) {
  24515. cache[1] = y;
  24516. changed = true;
  24517. }
  24518. if (cache[2] !== z) {
  24519. cache[2] = z;
  24520. changed = true;
  24521. }
  24522. if (cache[3] !== w) {
  24523. cache[3] = w;
  24524. changed = true;
  24525. }
  24526. return changed;
  24527. };
  24528. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  24529. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  24530. return;
  24531. }
  24532. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  24533. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  24534. };
  24535. Effect.prototype.bindUniformBlock = function (blockName, index) {
  24536. this._engine.bindUniformBlock(this._program, blockName, index);
  24537. };
  24538. Effect.prototype.setIntArray = function (uniformName, array) {
  24539. this._valueCache[uniformName] = null;
  24540. this._engine.setIntArray(this.getUniform(uniformName), array);
  24541. return this;
  24542. };
  24543. Effect.prototype.setIntArray2 = function (uniformName, array) {
  24544. this._valueCache[uniformName] = null;
  24545. this._engine.setIntArray2(this.getUniform(uniformName), array);
  24546. return this;
  24547. };
  24548. Effect.prototype.setIntArray3 = function (uniformName, array) {
  24549. this._valueCache[uniformName] = null;
  24550. this._engine.setIntArray3(this.getUniform(uniformName), array);
  24551. return this;
  24552. };
  24553. Effect.prototype.setIntArray4 = function (uniformName, array) {
  24554. this._valueCache[uniformName] = null;
  24555. this._engine.setIntArray4(this.getUniform(uniformName), array);
  24556. return this;
  24557. };
  24558. Effect.prototype.setFloatArray = function (uniformName, array) {
  24559. this._valueCache[uniformName] = null;
  24560. this._engine.setFloatArray(this.getUniform(uniformName), array);
  24561. return this;
  24562. };
  24563. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  24564. this._valueCache[uniformName] = null;
  24565. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  24566. return this;
  24567. };
  24568. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  24569. this._valueCache[uniformName] = null;
  24570. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  24571. return this;
  24572. };
  24573. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  24574. this._valueCache[uniformName] = null;
  24575. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  24576. return this;
  24577. };
  24578. Effect.prototype.setArray = function (uniformName, array) {
  24579. this._valueCache[uniformName] = null;
  24580. this._engine.setArray(this.getUniform(uniformName), array);
  24581. return this;
  24582. };
  24583. Effect.prototype.setArray2 = function (uniformName, array) {
  24584. this._valueCache[uniformName] = null;
  24585. this._engine.setArray2(this.getUniform(uniformName), array);
  24586. return this;
  24587. };
  24588. Effect.prototype.setArray3 = function (uniformName, array) {
  24589. this._valueCache[uniformName] = null;
  24590. this._engine.setArray3(this.getUniform(uniformName), array);
  24591. return this;
  24592. };
  24593. Effect.prototype.setArray4 = function (uniformName, array) {
  24594. this._valueCache[uniformName] = null;
  24595. this._engine.setArray4(this.getUniform(uniformName), array);
  24596. return this;
  24597. };
  24598. Effect.prototype.setMatrices = function (uniformName, matrices) {
  24599. if (!matrices) {
  24600. return;
  24601. }
  24602. this._valueCache[uniformName] = null;
  24603. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  24604. return this;
  24605. };
  24606. Effect.prototype.setMatrix = function (uniformName, matrix) {
  24607. if (this._cacheMatrix(uniformName, matrix)) {
  24608. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  24609. }
  24610. return this;
  24611. };
  24612. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  24613. this._valueCache[uniformName] = null;
  24614. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  24615. return this;
  24616. };
  24617. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  24618. this._valueCache[uniformName] = null;
  24619. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  24620. return this;
  24621. };
  24622. Effect.prototype.setFloat = function (uniformName, value) {
  24623. var cache = this._valueCache[uniformName];
  24624. if (cache !== undefined && cache === value)
  24625. return this;
  24626. this._valueCache[uniformName] = value;
  24627. this._engine.setFloat(this.getUniform(uniformName), value);
  24628. return this;
  24629. };
  24630. Effect.prototype.setBool = function (uniformName, bool) {
  24631. var cache = this._valueCache[uniformName];
  24632. if (cache !== undefined && cache === bool)
  24633. return this;
  24634. this._valueCache[uniformName] = bool;
  24635. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  24636. return this;
  24637. };
  24638. Effect.prototype.setVector2 = function (uniformName, vector2) {
  24639. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  24640. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  24641. }
  24642. return this;
  24643. };
  24644. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  24645. if (this._cacheFloat2(uniformName, x, y)) {
  24646. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  24647. }
  24648. return this;
  24649. };
  24650. Effect.prototype.setVector3 = function (uniformName, vector3) {
  24651. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  24652. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  24653. }
  24654. return this;
  24655. };
  24656. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  24657. if (this._cacheFloat3(uniformName, x, y, z)) {
  24658. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  24659. }
  24660. return this;
  24661. };
  24662. Effect.prototype.setVector4 = function (uniformName, vector4) {
  24663. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  24664. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  24665. }
  24666. return this;
  24667. };
  24668. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  24669. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  24670. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  24671. }
  24672. return this;
  24673. };
  24674. Effect.prototype.setColor3 = function (uniformName, color3) {
  24675. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  24676. this._engine.setColor3(this.getUniform(uniformName), color3);
  24677. }
  24678. return this;
  24679. };
  24680. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  24681. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  24682. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  24683. }
  24684. return this;
  24685. };
  24686. Effect.ResetCache = function () {
  24687. Effect._baseCache = {};
  24688. };
  24689. Effect._uniqueIdSeed = 0;
  24690. Effect._baseCache = {};
  24691. // Statics
  24692. Effect.ShadersStore = {};
  24693. Effect.IncludesShadersStore = {};
  24694. return Effect;
  24695. }());
  24696. BABYLON.Effect = Effect;
  24697. })(BABYLON || (BABYLON = {}));
  24698. //# sourceMappingURL=babylon.effect.js.map
  24699. var BABYLON;
  24700. (function (BABYLON) {
  24701. var MaterialHelper = (function () {
  24702. function MaterialHelper() {
  24703. }
  24704. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  24705. defines._needUVs = true;
  24706. defines[key] = true;
  24707. if (texture.getTextureMatrix().isIdentity(true)) {
  24708. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  24709. if (texture.coordinatesIndex === 0) {
  24710. defines["MAINUV1"] = true;
  24711. }
  24712. else {
  24713. defines["MAINUV2"] = true;
  24714. }
  24715. }
  24716. else {
  24717. defines[key + "DIRECTUV"] = 0;
  24718. }
  24719. };
  24720. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  24721. var matrix = texture.getTextureMatrix();
  24722. if (!matrix.isIdentity(true)) {
  24723. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  24724. }
  24725. };
  24726. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  24727. if (defines._areMiscDirty) {
  24728. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  24729. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  24730. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  24731. defines["USERIGHTHANDEDSYSTEM"] = scene.useRightHandedSystem;
  24732. }
  24733. };
  24734. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  24735. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  24736. var changed = false;
  24737. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  24738. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  24739. changed = true;
  24740. }
  24741. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  24742. defines["ALPHATEST"] = !defines["ALPHATEST"];
  24743. changed = true;
  24744. }
  24745. if (defines["INSTANCES"] !== useInstances) {
  24746. defines["INSTANCES"] = useInstances;
  24747. changed = true;
  24748. }
  24749. if (changed) {
  24750. defines.markAsUnprocessed();
  24751. }
  24752. };
  24753. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  24754. if (useMorphTargets === void 0) { useMorphTargets = false; }
  24755. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  24756. return false;
  24757. }
  24758. defines._normals = defines._needNormals;
  24759. defines._uvs = defines._needUVs;
  24760. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  24761. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  24762. defines["TANGENT"] = true;
  24763. }
  24764. if (defines._needUVs) {
  24765. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  24766. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  24767. }
  24768. else {
  24769. defines["UV1"] = false;
  24770. defines["UV2"] = false;
  24771. }
  24772. if (useVertexColor) {
  24773. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  24774. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  24775. }
  24776. if (useBones) {
  24777. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  24778. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  24779. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  24780. }
  24781. else {
  24782. defines["NUM_BONE_INFLUENCERS"] = 0;
  24783. defines["BonesPerMesh"] = 0;
  24784. }
  24785. }
  24786. if (useMorphTargets) {
  24787. if (mesh.morphTargetManager) {
  24788. var manager = mesh.morphTargetManager;
  24789. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  24790. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  24791. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  24792. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  24793. }
  24794. else {
  24795. defines["MORPHTARGETS_TANGENT"] = false;
  24796. defines["MORPHTARGETS_NORMAL"] = false;
  24797. defines["MORPHTARGETS"] = false;
  24798. defines["NUM_MORPH_INFLUENCERS"] = 0;
  24799. }
  24800. }
  24801. return true;
  24802. };
  24803. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  24804. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24805. if (disableLighting === void 0) { disableLighting = false; }
  24806. if (!defines._areLightsDirty) {
  24807. return defines._needNormals;
  24808. }
  24809. var lightIndex = 0;
  24810. var needNormals = false;
  24811. var needRebuild = false;
  24812. var lightmapMode = false;
  24813. var shadowEnabled = false;
  24814. var specularEnabled = false;
  24815. if (scene.lightsEnabled && !disableLighting) {
  24816. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  24817. var light = _a[_i];
  24818. needNormals = true;
  24819. if (defines["LIGHT" + lightIndex] === undefined) {
  24820. needRebuild = true;
  24821. }
  24822. defines["LIGHT" + lightIndex] = true;
  24823. defines["SPOTLIGHT" + lightIndex] = false;
  24824. defines["HEMILIGHT" + lightIndex] = false;
  24825. defines["POINTLIGHT" + lightIndex] = false;
  24826. defines["DIRLIGHT" + lightIndex] = false;
  24827. var type;
  24828. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  24829. type = "SPOTLIGHT" + lightIndex;
  24830. }
  24831. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  24832. type = "HEMILIGHT" + lightIndex;
  24833. }
  24834. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  24835. type = "POINTLIGHT" + lightIndex;
  24836. }
  24837. else {
  24838. type = "DIRLIGHT" + lightIndex;
  24839. }
  24840. defines[type] = true;
  24841. // Specular
  24842. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  24843. specularEnabled = true;
  24844. }
  24845. // Shadows
  24846. defines["SHADOW" + lightIndex] = false;
  24847. defines["SHADOWPCF" + lightIndex] = false;
  24848. defines["SHADOWESM" + lightIndex] = false;
  24849. defines["SHADOWCUBE" + lightIndex] = false;
  24850. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  24851. var shadowGenerator = light.getShadowGenerator();
  24852. if (shadowGenerator) {
  24853. shadowEnabled = true;
  24854. shadowGenerator.prepareDefines(defines, lightIndex);
  24855. }
  24856. }
  24857. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  24858. lightmapMode = true;
  24859. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  24860. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  24861. }
  24862. else {
  24863. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  24864. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  24865. }
  24866. lightIndex++;
  24867. if (lightIndex === maxSimultaneousLights)
  24868. break;
  24869. }
  24870. }
  24871. defines["SPECULARTERM"] = specularEnabled;
  24872. defines["SHADOWS"] = shadowEnabled;
  24873. // Resetting all other lights if any
  24874. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  24875. if (defines["LIGHT" + index] !== undefined) {
  24876. defines["LIGHT" + index] = false;
  24877. defines["HEMILIGHT" + lightIndex] = false;
  24878. defines["POINTLIGHT" + lightIndex] = false;
  24879. defines["DIRLIGHT" + lightIndex] = false;
  24880. defines["SPOTLIGHT" + lightIndex] = false;
  24881. defines["SHADOW" + lightIndex] = false;
  24882. }
  24883. }
  24884. var caps = scene.getEngine().getCaps();
  24885. if (defines["SHADOWFLOAT"] === undefined) {
  24886. needRebuild = true;
  24887. }
  24888. defines["SHADOWFLOAT"] = shadowEnabled &&
  24889. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  24890. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  24891. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  24892. if (needRebuild) {
  24893. defines.rebuild();
  24894. }
  24895. return needNormals;
  24896. };
  24897. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  24898. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24899. var uniformsList, uniformBuffersList, samplersList, defines;
  24900. if (uniformsListOrOptions.uniformsNames) {
  24901. var options = uniformsListOrOptions;
  24902. uniformsList = options.uniformsNames;
  24903. uniformBuffersList = options.uniformBuffersNames;
  24904. samplersList = options.samplers;
  24905. defines = options.defines;
  24906. maxSimultaneousLights = options.maxSimultaneousLights;
  24907. }
  24908. else {
  24909. uniformsList = uniformsListOrOptions;
  24910. }
  24911. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24912. if (!defines["LIGHT" + lightIndex]) {
  24913. break;
  24914. }
  24915. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  24916. if (uniformBuffersList) {
  24917. uniformBuffersList.push("Light" + lightIndex);
  24918. }
  24919. samplersList.push("shadowSampler" + lightIndex);
  24920. }
  24921. if (defines["NUM_MORPH_INFLUENCERS"]) {
  24922. uniformsList.push("morphTargetInfluences");
  24923. }
  24924. };
  24925. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  24926. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24927. if (!defines["SHADOWS"]) {
  24928. return;
  24929. }
  24930. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24931. if (!defines["LIGHT" + lightIndex]) {
  24932. break;
  24933. }
  24934. if (lightIndex > 0) {
  24935. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  24936. }
  24937. if (defines["SHADOW" + lightIndex]) {
  24938. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  24939. }
  24940. if (defines["SHADOWPCF" + lightIndex]) {
  24941. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  24942. }
  24943. if (defines["SHADOWESM" + lightIndex]) {
  24944. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  24945. }
  24946. }
  24947. };
  24948. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  24949. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  24950. if (influencers > 0) {
  24951. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  24952. var manager = mesh.morphTargetManager;
  24953. var normal = manager.supportsNormals && defines["NORMAL"];
  24954. var tangent = manager.supportsTangents && defines["TANGENT"];
  24955. for (var index = 0; index < influencers; index++) {
  24956. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  24957. if (normal) {
  24958. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  24959. }
  24960. if (tangent) {
  24961. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  24962. }
  24963. if (attribs.length > maxAttributesCount) {
  24964. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  24965. }
  24966. }
  24967. }
  24968. };
  24969. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  24970. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  24971. fallbacks.addCPUSkinningFallback(0, mesh);
  24972. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24973. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24974. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  24975. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  24976. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  24977. }
  24978. }
  24979. };
  24980. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  24981. if (defines["INSTANCES"]) {
  24982. attribs.push("world0");
  24983. attribs.push("world1");
  24984. attribs.push("world2");
  24985. attribs.push("world3");
  24986. }
  24987. };
  24988. // Bindings
  24989. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  24990. if (light.shadowEnabled && mesh.receiveShadows) {
  24991. var shadowGenerator = light.getShadowGenerator();
  24992. if (shadowGenerator) {
  24993. shadowGenerator.bindShadowLight(lightIndex, effect);
  24994. }
  24995. }
  24996. };
  24997. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  24998. light.transferToEffect(effect, lightIndex + "");
  24999. };
  25000. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  25001. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25002. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  25003. var lightIndex = 0;
  25004. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  25005. var light = _a[_i];
  25006. var scaledIntensity = light.getScaledIntensity();
  25007. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  25008. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  25009. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  25010. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  25011. if (defines["SPECULARTERM"]) {
  25012. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  25013. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  25014. }
  25015. // Shadows
  25016. if (scene.shadowsEnabled) {
  25017. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  25018. }
  25019. light._uniformBuffer.update();
  25020. lightIndex++;
  25021. if (lightIndex === maxSimultaneousLights)
  25022. break;
  25023. }
  25024. };
  25025. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  25026. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  25027. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  25028. effect.setColor3("vFogColor", scene.fogColor);
  25029. }
  25030. };
  25031. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  25032. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25033. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  25034. if (matrices) {
  25035. effect.setMatrices("mBones", matrices);
  25036. }
  25037. }
  25038. };
  25039. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  25040. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  25041. return;
  25042. }
  25043. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  25044. };
  25045. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  25046. if (defines["LOGARITHMICDEPTH"]) {
  25047. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  25048. }
  25049. };
  25050. MaterialHelper.BindClipPlane = function (effect, scene) {
  25051. if (scene.clipPlane) {
  25052. var clipPlane = scene.clipPlane;
  25053. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  25054. }
  25055. };
  25056. return MaterialHelper;
  25057. }());
  25058. BABYLON.MaterialHelper = MaterialHelper;
  25059. })(BABYLON || (BABYLON = {}));
  25060. //# sourceMappingURL=babylon.materialHelper.js.map
  25061. var BABYLON;
  25062. (function (BABYLON) {
  25063. var MaterialDefines = (function () {
  25064. function MaterialDefines() {
  25065. this._isDirty = true;
  25066. this._areLightsDirty = true;
  25067. this._areAttributesDirty = true;
  25068. this._areTexturesDirty = true;
  25069. this._areFresnelDirty = true;
  25070. this._areMiscDirty = true;
  25071. this._areImageProcessingDirty = true;
  25072. this._normals = false;
  25073. this._uvs = false;
  25074. this._needNormals = false;
  25075. this._needUVs = false;
  25076. }
  25077. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  25078. get: function () {
  25079. return this._isDirty;
  25080. },
  25081. enumerable: true,
  25082. configurable: true
  25083. });
  25084. MaterialDefines.prototype.markAsProcessed = function () {
  25085. this._isDirty = false;
  25086. this._areAttributesDirty = false;
  25087. this._areTexturesDirty = false;
  25088. this._areFresnelDirty = false;
  25089. this._areLightsDirty = false;
  25090. this._areMiscDirty = false;
  25091. this._areImageProcessingDirty = false;
  25092. };
  25093. MaterialDefines.prototype.markAsUnprocessed = function () {
  25094. this._isDirty = true;
  25095. };
  25096. MaterialDefines.prototype.markAllAsDirty = function () {
  25097. this._areTexturesDirty = true;
  25098. this._areAttributesDirty = true;
  25099. this._areLightsDirty = true;
  25100. this._areFresnelDirty = true;
  25101. this._areMiscDirty = true;
  25102. this._areImageProcessingDirty = true;
  25103. this._isDirty = true;
  25104. };
  25105. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  25106. this._areImageProcessingDirty = true;
  25107. this._isDirty = true;
  25108. };
  25109. MaterialDefines.prototype.markAsLightDirty = function () {
  25110. this._areLightsDirty = true;
  25111. this._isDirty = true;
  25112. };
  25113. MaterialDefines.prototype.markAsAttributesDirty = function () {
  25114. this._areAttributesDirty = true;
  25115. this._isDirty = true;
  25116. };
  25117. MaterialDefines.prototype.markAsTexturesDirty = function () {
  25118. this._areTexturesDirty = true;
  25119. this._isDirty = true;
  25120. };
  25121. MaterialDefines.prototype.markAsFresnelDirty = function () {
  25122. this._areFresnelDirty = true;
  25123. this._isDirty = true;
  25124. };
  25125. MaterialDefines.prototype.markAsMiscDirty = function () {
  25126. this._areMiscDirty = true;
  25127. this._isDirty = true;
  25128. };
  25129. MaterialDefines.prototype.rebuild = function () {
  25130. if (this._keys) {
  25131. delete this._keys;
  25132. }
  25133. this._keys = [];
  25134. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  25135. var key = _a[_i];
  25136. if (key[0] === "_") {
  25137. continue;
  25138. }
  25139. this._keys.push(key);
  25140. }
  25141. };
  25142. MaterialDefines.prototype.isEqual = function (other) {
  25143. if (this._keys.length !== other._keys.length) {
  25144. return false;
  25145. }
  25146. for (var index = 0; index < this._keys.length; index++) {
  25147. var prop = this._keys[index];
  25148. if (this[prop] !== other[prop]) {
  25149. return false;
  25150. }
  25151. }
  25152. return true;
  25153. };
  25154. MaterialDefines.prototype.cloneTo = function (other) {
  25155. if (this._keys.length !== other._keys.length) {
  25156. other._keys = this._keys.slice(0);
  25157. }
  25158. for (var index = 0; index < this._keys.length; index++) {
  25159. var prop = this._keys[index];
  25160. other[prop] = this[prop];
  25161. }
  25162. };
  25163. MaterialDefines.prototype.reset = function () {
  25164. for (var index = 0; index < this._keys.length; index++) {
  25165. var prop = this._keys[index];
  25166. if (typeof (this[prop]) === "number") {
  25167. this[prop] = 0;
  25168. }
  25169. else {
  25170. this[prop] = false;
  25171. }
  25172. }
  25173. };
  25174. MaterialDefines.prototype.toString = function () {
  25175. var result = "";
  25176. for (var index = 0; index < this._keys.length; index++) {
  25177. var prop = this._keys[index];
  25178. var value = this[prop];
  25179. if (typeof (value) === "number") {
  25180. result += "#define " + prop + " " + this[prop] + "\n";
  25181. }
  25182. else if (value) {
  25183. result += "#define " + prop + "\n";
  25184. }
  25185. }
  25186. return result;
  25187. };
  25188. return MaterialDefines;
  25189. }());
  25190. BABYLON.MaterialDefines = MaterialDefines;
  25191. var Material = (function () {
  25192. function Material(name, scene, doNotAdd) {
  25193. this.checkReadyOnEveryCall = false;
  25194. this.checkReadyOnlyOnce = false;
  25195. this.state = "";
  25196. this.alpha = 1.0;
  25197. this._backFaceCulling = true;
  25198. this.doNotSerialize = false;
  25199. this.storeEffectOnSubMeshes = false;
  25200. /**
  25201. * An event triggered when the material is disposed.
  25202. * @type {BABYLON.Observable}
  25203. */
  25204. this.onDisposeObservable = new BABYLON.Observable();
  25205. /**
  25206. * An event triggered when the material is bound.
  25207. * @type {BABYLON.Observable}
  25208. */
  25209. this.onBindObservable = new BABYLON.Observable();
  25210. /**
  25211. * An event triggered when the material is unbound.
  25212. * @type {BABYLON.Observable}
  25213. */
  25214. this.onUnBindObservable = new BABYLON.Observable();
  25215. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  25216. this.disableDepthWrite = false;
  25217. this._fogEnabled = true;
  25218. this.pointSize = 1.0;
  25219. this.zOffset = 0;
  25220. this._wasPreviouslyReady = false;
  25221. this._fillMode = Material.TriangleFillMode;
  25222. this.name = name;
  25223. this.id = name || BABYLON.Tools.RandomId();
  25224. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  25225. if (this._scene.useRightHandedSystem) {
  25226. this.sideOrientation = Material.ClockWiseSideOrientation;
  25227. }
  25228. else {
  25229. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  25230. }
  25231. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  25232. this._useUBO = this.getScene().getEngine().webGLVersion > 1;
  25233. if (!doNotAdd) {
  25234. this._scene.materials.push(this);
  25235. }
  25236. }
  25237. Object.defineProperty(Material, "TriangleFillMode", {
  25238. get: function () {
  25239. return Material._TriangleFillMode;
  25240. },
  25241. enumerable: true,
  25242. configurable: true
  25243. });
  25244. Object.defineProperty(Material, "WireFrameFillMode", {
  25245. get: function () {
  25246. return Material._WireFrameFillMode;
  25247. },
  25248. enumerable: true,
  25249. configurable: true
  25250. });
  25251. Object.defineProperty(Material, "PointFillMode", {
  25252. get: function () {
  25253. return Material._PointFillMode;
  25254. },
  25255. enumerable: true,
  25256. configurable: true
  25257. });
  25258. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  25259. get: function () {
  25260. return Material._ClockWiseSideOrientation;
  25261. },
  25262. enumerable: true,
  25263. configurable: true
  25264. });
  25265. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  25266. get: function () {
  25267. return Material._CounterClockWiseSideOrientation;
  25268. },
  25269. enumerable: true,
  25270. configurable: true
  25271. });
  25272. Object.defineProperty(Material, "TextureDirtyFlag", {
  25273. get: function () {
  25274. return Material._TextureDirtyFlag;
  25275. },
  25276. enumerable: true,
  25277. configurable: true
  25278. });
  25279. Object.defineProperty(Material, "LightDirtyFlag", {
  25280. get: function () {
  25281. return Material._LightDirtyFlag;
  25282. },
  25283. enumerable: true,
  25284. configurable: true
  25285. });
  25286. Object.defineProperty(Material, "FresnelDirtyFlag", {
  25287. get: function () {
  25288. return Material._FresnelDirtyFlag;
  25289. },
  25290. enumerable: true,
  25291. configurable: true
  25292. });
  25293. Object.defineProperty(Material, "AttributesDirtyFlag", {
  25294. get: function () {
  25295. return Material._AttributesDirtyFlag;
  25296. },
  25297. enumerable: true,
  25298. configurable: true
  25299. });
  25300. Object.defineProperty(Material, "MiscDirtyFlag", {
  25301. get: function () {
  25302. return Material._MiscDirtyFlag;
  25303. },
  25304. enumerable: true,
  25305. configurable: true
  25306. });
  25307. Object.defineProperty(Material.prototype, "backFaceCulling", {
  25308. get: function () {
  25309. return this._backFaceCulling;
  25310. },
  25311. set: function (value) {
  25312. if (this._backFaceCulling === value) {
  25313. return;
  25314. }
  25315. this._backFaceCulling = value;
  25316. this.markAsDirty(Material.TextureDirtyFlag);
  25317. },
  25318. enumerable: true,
  25319. configurable: true
  25320. });
  25321. Object.defineProperty(Material.prototype, "onDispose", {
  25322. set: function (callback) {
  25323. if (this._onDisposeObserver) {
  25324. this.onDisposeObservable.remove(this._onDisposeObserver);
  25325. }
  25326. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25327. },
  25328. enumerable: true,
  25329. configurable: true
  25330. });
  25331. Object.defineProperty(Material.prototype, "onBind", {
  25332. set: function (callback) {
  25333. if (this._onBindObserver) {
  25334. this.onBindObservable.remove(this._onBindObserver);
  25335. }
  25336. this._onBindObserver = this.onBindObservable.add(callback);
  25337. },
  25338. enumerable: true,
  25339. configurable: true
  25340. });
  25341. Object.defineProperty(Material.prototype, "fogEnabled", {
  25342. get: function () {
  25343. return this._fogEnabled;
  25344. },
  25345. set: function (value) {
  25346. if (this._fogEnabled === value) {
  25347. return;
  25348. }
  25349. this._fogEnabled = value;
  25350. this.markAsDirty(Material.MiscDirtyFlag);
  25351. },
  25352. enumerable: true,
  25353. configurable: true
  25354. });
  25355. Object.defineProperty(Material.prototype, "wireframe", {
  25356. get: function () {
  25357. return this._fillMode === Material.WireFrameFillMode;
  25358. },
  25359. set: function (value) {
  25360. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  25361. },
  25362. enumerable: true,
  25363. configurable: true
  25364. });
  25365. Object.defineProperty(Material.prototype, "pointsCloud", {
  25366. get: function () {
  25367. return this._fillMode === Material.PointFillMode;
  25368. },
  25369. set: function (value) {
  25370. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  25371. },
  25372. enumerable: true,
  25373. configurable: true
  25374. });
  25375. Object.defineProperty(Material.prototype, "fillMode", {
  25376. get: function () {
  25377. return this._fillMode;
  25378. },
  25379. set: function (value) {
  25380. if (this._fillMode === value) {
  25381. return;
  25382. }
  25383. this._fillMode = value;
  25384. this.markAsDirty(Material.MiscDirtyFlag);
  25385. },
  25386. enumerable: true,
  25387. configurable: true
  25388. });
  25389. /**
  25390. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25391. * subclasses should override adding information pertainent to themselves
  25392. */
  25393. Material.prototype.toString = function (fullDetails) {
  25394. var ret = "Name: " + this.name;
  25395. if (fullDetails) {
  25396. }
  25397. return ret;
  25398. };
  25399. /**
  25400. * Child classes can use it to update shaders
  25401. */
  25402. Material.prototype.getClassName = function () {
  25403. return "Material";
  25404. };
  25405. Object.defineProperty(Material.prototype, "isFrozen", {
  25406. get: function () {
  25407. return this.checkReadyOnlyOnce;
  25408. },
  25409. enumerable: true,
  25410. configurable: true
  25411. });
  25412. Material.prototype.freeze = function () {
  25413. this.checkReadyOnlyOnce = true;
  25414. };
  25415. Material.prototype.unfreeze = function () {
  25416. this.checkReadyOnlyOnce = false;
  25417. };
  25418. Material.prototype.isReady = function (mesh, useInstances) {
  25419. return true;
  25420. };
  25421. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  25422. return false;
  25423. };
  25424. Material.prototype.getEffect = function () {
  25425. return this._effect;
  25426. };
  25427. Material.prototype.getScene = function () {
  25428. return this._scene;
  25429. };
  25430. Material.prototype.needAlphaBlending = function () {
  25431. return (this.alpha < 1.0);
  25432. };
  25433. Material.prototype.needAlphaTesting = function () {
  25434. return false;
  25435. };
  25436. Material.prototype.getAlphaTestTexture = function () {
  25437. return null;
  25438. };
  25439. Material.prototype.markDirty = function () {
  25440. this._wasPreviouslyReady = false;
  25441. };
  25442. Material.prototype._preBind = function (effect) {
  25443. var engine = this._scene.getEngine();
  25444. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  25445. engine.enableEffect(effect ? effect : this._effect);
  25446. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  25447. };
  25448. Material.prototype.bind = function (world, mesh) {
  25449. };
  25450. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  25451. };
  25452. Material.prototype.bindOnlyWorldMatrix = function (world) {
  25453. };
  25454. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  25455. sceneUbo.bindToEffect(effect, "Scene");
  25456. };
  25457. Material.prototype.bindView = function (effect) {
  25458. if (!this._useUBO) {
  25459. effect.setMatrix("view", this.getScene().getViewMatrix());
  25460. }
  25461. else {
  25462. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  25463. }
  25464. };
  25465. Material.prototype.bindViewProjection = function (effect) {
  25466. if (!this._useUBO) {
  25467. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  25468. }
  25469. else {
  25470. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  25471. }
  25472. };
  25473. Material.prototype._afterBind = function (mesh) {
  25474. this._scene._cachedMaterial = this;
  25475. if (mesh) {
  25476. this._scene._cachedVisibility = mesh.visibility;
  25477. }
  25478. else {
  25479. this._scene._cachedVisibility = 1;
  25480. }
  25481. this.onBindObservable.notifyObservers(mesh);
  25482. if (this.disableDepthWrite) {
  25483. var engine = this._scene.getEngine();
  25484. this._cachedDepthWriteState = engine.getDepthWrite();
  25485. engine.setDepthWrite(false);
  25486. }
  25487. };
  25488. Material.prototype.unbind = function () {
  25489. this.onUnBindObservable.notifyObservers(this);
  25490. if (this.disableDepthWrite) {
  25491. var engine = this._scene.getEngine();
  25492. engine.setDepthWrite(this._cachedDepthWriteState);
  25493. }
  25494. };
  25495. Material.prototype.getActiveTextures = function () {
  25496. return [];
  25497. };
  25498. Material.prototype.hasTexture = function (texture) {
  25499. return false;
  25500. };
  25501. Material.prototype.clone = function (name) {
  25502. return null;
  25503. };
  25504. Material.prototype.getBindedMeshes = function () {
  25505. var result = new Array();
  25506. for (var index = 0; index < this._scene.meshes.length; index++) {
  25507. var mesh = this._scene.meshes[index];
  25508. if (mesh.material === this) {
  25509. result.push(mesh);
  25510. }
  25511. }
  25512. return result;
  25513. };
  25514. /**
  25515. * Force shader compilation including textures ready check
  25516. */
  25517. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  25518. var _this = this;
  25519. var subMesh = new BABYLON.BaseSubMesh();
  25520. var scene = this.getScene();
  25521. var engine = scene.getEngine();
  25522. var checkReady = function () {
  25523. if (!_this._scene || !_this._scene.getEngine()) {
  25524. return;
  25525. }
  25526. if (subMesh._materialDefines) {
  25527. subMesh._materialDefines._renderId = -1;
  25528. }
  25529. var alphaTestState = engine.getAlphaTesting();
  25530. var clipPlaneState = scene.clipPlane;
  25531. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  25532. if (options && options.clipPlane) {
  25533. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  25534. }
  25535. if (_this.storeEffectOnSubMeshes) {
  25536. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  25537. if (onCompiled) {
  25538. onCompiled(_this);
  25539. }
  25540. }
  25541. else {
  25542. setTimeout(checkReady, 16);
  25543. }
  25544. }
  25545. else {
  25546. if (_this.isReady(mesh)) {
  25547. if (onCompiled) {
  25548. onCompiled(_this);
  25549. }
  25550. }
  25551. else {
  25552. setTimeout(checkReady, 16);
  25553. }
  25554. }
  25555. engine.setAlphaTesting(alphaTestState);
  25556. if (options && options.clipPlane) {
  25557. scene.clipPlane = clipPlaneState;
  25558. }
  25559. };
  25560. checkReady();
  25561. };
  25562. Material.prototype.markAsDirty = function (flag) {
  25563. if (flag & Material.TextureDirtyFlag) {
  25564. this._markAllSubMeshesAsTexturesDirty();
  25565. }
  25566. if (flag & Material.LightDirtyFlag) {
  25567. this._markAllSubMeshesAsLightsDirty();
  25568. }
  25569. if (flag & Material.FresnelDirtyFlag) {
  25570. this._markAllSubMeshesAsFresnelDirty();
  25571. }
  25572. if (flag & Material.AttributesDirtyFlag) {
  25573. this._markAllSubMeshesAsAttributesDirty();
  25574. }
  25575. if (flag & Material.MiscDirtyFlag) {
  25576. this._markAllSubMeshesAsMiscDirty();
  25577. }
  25578. this.getScene().resetCachedMaterial();
  25579. };
  25580. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  25581. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  25582. var mesh = _a[_i];
  25583. if (!mesh.subMeshes) {
  25584. continue;
  25585. }
  25586. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25587. var subMesh = _c[_b];
  25588. if (subMesh.getMaterial() !== this) {
  25589. continue;
  25590. }
  25591. if (!subMesh._materialDefines) {
  25592. continue;
  25593. }
  25594. func(subMesh._materialDefines);
  25595. }
  25596. }
  25597. };
  25598. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  25599. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  25600. };
  25601. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  25602. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  25603. };
  25604. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  25605. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  25606. };
  25607. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  25608. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  25609. };
  25610. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  25611. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  25612. };
  25613. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  25614. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  25615. };
  25616. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  25617. // Animations
  25618. this.getScene().stopAnimation(this);
  25619. // Remove from scene
  25620. var index = this._scene.materials.indexOf(this);
  25621. if (index >= 0) {
  25622. this._scene.materials.splice(index, 1);
  25623. }
  25624. // Remove from meshes
  25625. for (index = 0; index < this._scene.meshes.length; index++) {
  25626. var mesh = this._scene.meshes[index];
  25627. if (mesh.material === this) {
  25628. mesh.material = null;
  25629. if (mesh.geometry) {
  25630. var geometry = mesh.geometry;
  25631. if (this.storeEffectOnSubMeshes) {
  25632. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  25633. var subMesh = _a[_i];
  25634. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  25635. }
  25636. }
  25637. else {
  25638. geometry._releaseVertexArrayObject(this._effect);
  25639. }
  25640. }
  25641. }
  25642. }
  25643. this._uniformBuffer.dispose();
  25644. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  25645. if (forceDisposeEffect && this._effect) {
  25646. if (this.storeEffectOnSubMeshes) {
  25647. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25648. var subMesh = _c[_b];
  25649. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  25650. }
  25651. }
  25652. else {
  25653. this._scene.getEngine()._releaseEffect(this._effect);
  25654. }
  25655. this._effect = null;
  25656. }
  25657. // Callback
  25658. this.onDisposeObservable.notifyObservers(this);
  25659. this.onDisposeObservable.clear();
  25660. this.onBindObservable.clear();
  25661. this.onUnBindObservable.clear();
  25662. };
  25663. Material.prototype.serialize = function () {
  25664. return BABYLON.SerializationHelper.Serialize(this);
  25665. };
  25666. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  25667. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  25668. multiMaterial.id = parsedMultiMaterial.id;
  25669. if (BABYLON.Tags) {
  25670. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  25671. }
  25672. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  25673. var subMatId = parsedMultiMaterial.materials[matIndex];
  25674. if (subMatId) {
  25675. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  25676. }
  25677. else {
  25678. multiMaterial.subMaterials.push(null);
  25679. }
  25680. }
  25681. return multiMaterial;
  25682. };
  25683. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  25684. if (!parsedMaterial.customType) {
  25685. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  25686. }
  25687. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  25688. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  25689. if (!BABYLON.LegacyPBRMaterial) {
  25690. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  25691. return;
  25692. }
  25693. }
  25694. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  25695. return materialType.Parse(parsedMaterial, scene, rootUrl);
  25696. ;
  25697. };
  25698. Material._TriangleFillMode = 0;
  25699. Material._WireFrameFillMode = 1;
  25700. Material._PointFillMode = 2;
  25701. Material._ClockWiseSideOrientation = 0;
  25702. Material._CounterClockWiseSideOrientation = 1;
  25703. Material._TextureDirtyFlag = 1;
  25704. Material._LightDirtyFlag = 2;
  25705. Material._FresnelDirtyFlag = 4;
  25706. Material._AttributesDirtyFlag = 8;
  25707. Material._MiscDirtyFlag = 16;
  25708. __decorate([
  25709. BABYLON.serialize()
  25710. ], Material.prototype, "id", void 0);
  25711. __decorate([
  25712. BABYLON.serialize()
  25713. ], Material.prototype, "name", void 0);
  25714. __decorate([
  25715. BABYLON.serialize()
  25716. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  25717. __decorate([
  25718. BABYLON.serialize()
  25719. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  25720. __decorate([
  25721. BABYLON.serialize()
  25722. ], Material.prototype, "state", void 0);
  25723. __decorate([
  25724. BABYLON.serialize()
  25725. ], Material.prototype, "alpha", void 0);
  25726. __decorate([
  25727. BABYLON.serialize("backFaceCulling")
  25728. ], Material.prototype, "_backFaceCulling", void 0);
  25729. __decorate([
  25730. BABYLON.serialize()
  25731. ], Material.prototype, "sideOrientation", void 0);
  25732. __decorate([
  25733. BABYLON.serialize()
  25734. ], Material.prototype, "alphaMode", void 0);
  25735. __decorate([
  25736. BABYLON.serialize()
  25737. ], Material.prototype, "disableDepthWrite", void 0);
  25738. __decorate([
  25739. BABYLON.serialize("fogEnabled")
  25740. ], Material.prototype, "_fogEnabled", void 0);
  25741. __decorate([
  25742. BABYLON.serialize()
  25743. ], Material.prototype, "pointSize", void 0);
  25744. __decorate([
  25745. BABYLON.serialize()
  25746. ], Material.prototype, "zOffset", void 0);
  25747. __decorate([
  25748. BABYLON.serialize()
  25749. ], Material.prototype, "wireframe", null);
  25750. __decorate([
  25751. BABYLON.serialize()
  25752. ], Material.prototype, "pointsCloud", null);
  25753. __decorate([
  25754. BABYLON.serialize()
  25755. ], Material.prototype, "fillMode", null);
  25756. return Material;
  25757. }());
  25758. BABYLON.Material = Material;
  25759. })(BABYLON || (BABYLON = {}));
  25760. //# sourceMappingURL=babylon.material.js.map
  25761. var BABYLON;
  25762. (function (BABYLON) {
  25763. var UniformBuffer = (function () {
  25764. /**
  25765. * Uniform buffer objects.
  25766. *
  25767. * Handles blocks of uniform on the GPU.
  25768. *
  25769. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  25770. *
  25771. * For more information, please refer to :
  25772. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  25773. */
  25774. function UniformBuffer(engine, data, dynamic) {
  25775. this._engine = engine;
  25776. this._noUBO = engine.webGLVersion === 1;
  25777. this._dynamic = dynamic;
  25778. this._data = data || [];
  25779. this._uniformLocations = {};
  25780. this._uniformSizes = {};
  25781. this._uniformLocationPointer = 0;
  25782. this._needSync = false;
  25783. if (this._noUBO) {
  25784. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  25785. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  25786. this.updateFloat = this._updateFloatForEffect;
  25787. this.updateFloat2 = this._updateFloat2ForEffect;
  25788. this.updateFloat3 = this._updateFloat3ForEffect;
  25789. this.updateFloat4 = this._updateFloat4ForEffect;
  25790. this.updateMatrix = this._updateMatrixForEffect;
  25791. this.updateVector3 = this._updateVector3ForEffect;
  25792. this.updateVector4 = this._updateVector4ForEffect;
  25793. this.updateColor3 = this._updateColor3ForEffect;
  25794. this.updateColor4 = this._updateColor4ForEffect;
  25795. }
  25796. else {
  25797. this._engine._uniformBuffers.push(this);
  25798. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  25799. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  25800. this.updateFloat = this._updateFloatForUniform;
  25801. this.updateFloat2 = this._updateFloat2ForUniform;
  25802. this.updateFloat3 = this._updateFloat3ForUniform;
  25803. this.updateFloat4 = this._updateFloat4ForUniform;
  25804. this.updateMatrix = this._updateMatrixForUniform;
  25805. this.updateVector3 = this._updateVector3ForUniform;
  25806. this.updateVector4 = this._updateVector4ForUniform;
  25807. this.updateColor3 = this._updateColor3ForUniform;
  25808. this.updateColor4 = this._updateColor4ForUniform;
  25809. }
  25810. }
  25811. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  25812. // Properties
  25813. /**
  25814. * Indicates if the buffer is using the WebGL2 UBO implementation,
  25815. * or just falling back on setUniformXXX calls.
  25816. */
  25817. get: function () {
  25818. return !this._noUBO;
  25819. },
  25820. enumerable: true,
  25821. configurable: true
  25822. });
  25823. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  25824. /**
  25825. * Indicates if the WebGL underlying uniform buffer is in sync
  25826. * with the javascript cache data.
  25827. */
  25828. get: function () {
  25829. return !this._needSync;
  25830. },
  25831. enumerable: true,
  25832. configurable: true
  25833. });
  25834. /**
  25835. * Indicates if the WebGL underlying uniform buffer is dynamic.
  25836. * Also, a dynamic UniformBuffer will disable cache verification and always
  25837. * update the underlying WebGL uniform buffer to the GPU.
  25838. */
  25839. UniformBuffer.prototype.isDynamic = function () {
  25840. return this._dynamic;
  25841. };
  25842. /**
  25843. * The data cache on JS side.
  25844. */
  25845. UniformBuffer.prototype.getData = function () {
  25846. return this._bufferData;
  25847. };
  25848. /**
  25849. * The underlying WebGL Uniform buffer.
  25850. */
  25851. UniformBuffer.prototype.getBuffer = function () {
  25852. return this._buffer;
  25853. };
  25854. /**
  25855. * std140 layout specifies how to align data within an UBO structure.
  25856. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  25857. * for specs.
  25858. */
  25859. UniformBuffer.prototype._fillAlignment = function (size) {
  25860. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  25861. // and 4x4 matrices
  25862. // TODO : change if other types are used
  25863. var alignment;
  25864. if (size <= 2) {
  25865. alignment = size;
  25866. }
  25867. else {
  25868. alignment = 4;
  25869. }
  25870. if ((this._uniformLocationPointer % alignment) !== 0) {
  25871. var oldPointer = this._uniformLocationPointer;
  25872. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  25873. var diff = this._uniformLocationPointer - oldPointer;
  25874. for (var i = 0; i < diff; i++) {
  25875. this._data.push(0);
  25876. }
  25877. }
  25878. };
  25879. /**
  25880. * Adds an uniform in the buffer.
  25881. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  25882. * for the layout to be correct !
  25883. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25884. * @param {number|number[]} size Data size, or data directly.
  25885. */
  25886. UniformBuffer.prototype.addUniform = function (name, size) {
  25887. if (this._noUBO) {
  25888. return;
  25889. }
  25890. if (this._uniformLocations[name] !== undefined) {
  25891. // Already existing uniform
  25892. return;
  25893. }
  25894. // This function must be called in the order of the shader layout !
  25895. // size can be the size of the uniform, or data directly
  25896. var data;
  25897. if (size instanceof Array) {
  25898. data = size;
  25899. size = data.length;
  25900. }
  25901. else {
  25902. size = size;
  25903. data = [];
  25904. // Fill with zeros
  25905. for (var i = 0; i < size; i++) {
  25906. data.push(0);
  25907. }
  25908. }
  25909. this._fillAlignment(size);
  25910. this._uniformSizes[name] = size;
  25911. this._uniformLocations[name] = this._uniformLocationPointer;
  25912. this._uniformLocationPointer += size;
  25913. for (var i = 0; i < size; i++) {
  25914. this._data.push(data[i]);
  25915. }
  25916. this._needSync = true;
  25917. };
  25918. /**
  25919. * Wrapper for addUniform.
  25920. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25921. * @param {Matrix} mat A 4x4 matrix.
  25922. */
  25923. UniformBuffer.prototype.addMatrix = function (name, mat) {
  25924. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  25925. };
  25926. /**
  25927. * Wrapper for addUniform.
  25928. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25929. * @param {number} x
  25930. * @param {number} y
  25931. */
  25932. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  25933. var temp = [x, y];
  25934. this.addUniform(name, temp);
  25935. };
  25936. /**
  25937. * Wrapper for addUniform.
  25938. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25939. * @param {number} x
  25940. * @param {number} y
  25941. * @param {number} z
  25942. */
  25943. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  25944. var temp = [x, y, z];
  25945. this.addUniform(name, temp);
  25946. };
  25947. /**
  25948. * Wrapper for addUniform.
  25949. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25950. * @param {Color3} color
  25951. */
  25952. UniformBuffer.prototype.addColor3 = function (name, color) {
  25953. var temp = [];
  25954. color.toArray(temp);
  25955. this.addUniform(name, temp);
  25956. };
  25957. /**
  25958. * Wrapper for addUniform.
  25959. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25960. * @param {Color3} color
  25961. * @param {number} alpha
  25962. */
  25963. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  25964. var temp = [];
  25965. color.toArray(temp);
  25966. temp.push(alpha);
  25967. this.addUniform(name, temp);
  25968. };
  25969. /**
  25970. * Wrapper for addUniform.
  25971. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25972. * @param {Vector3} vector
  25973. */
  25974. UniformBuffer.prototype.addVector3 = function (name, vector) {
  25975. var temp = [];
  25976. vector.toArray(temp);
  25977. this.addUniform(name, temp);
  25978. };
  25979. /**
  25980. * Wrapper for addUniform.
  25981. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25982. */
  25983. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  25984. this.addUniform(name, 12);
  25985. };
  25986. /**
  25987. * Wrapper for addUniform.
  25988. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25989. */
  25990. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  25991. this.addUniform(name, 8);
  25992. };
  25993. /**
  25994. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  25995. */
  25996. UniformBuffer.prototype.create = function () {
  25997. if (this._noUBO) {
  25998. return;
  25999. }
  26000. if (this._buffer) {
  26001. return; // nothing to do
  26002. }
  26003. // See spec, alignment must be filled as a vec4
  26004. this._fillAlignment(4);
  26005. this._bufferData = new Float32Array(this._data);
  26006. this._rebuild();
  26007. this._needSync = true;
  26008. };
  26009. UniformBuffer.prototype._rebuild = function () {
  26010. if (this._noUBO) {
  26011. return;
  26012. }
  26013. if (this._dynamic) {
  26014. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  26015. }
  26016. else {
  26017. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  26018. }
  26019. };
  26020. /**
  26021. * Updates the WebGL Uniform Buffer on the GPU.
  26022. * If the `dynamic` flag is set to true, no cache comparison is done.
  26023. * Otherwise, the buffer will be updated only if the cache differs.
  26024. */
  26025. UniformBuffer.prototype.update = function () {
  26026. if (!this._buffer) {
  26027. this.create();
  26028. return;
  26029. }
  26030. if (!this._dynamic && !this._needSync) {
  26031. return;
  26032. }
  26033. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  26034. this._needSync = false;
  26035. };
  26036. /**
  26037. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  26038. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  26039. * @param {number[]|Float32Array} data Flattened data
  26040. * @param {number} size Size of the data.
  26041. */
  26042. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  26043. var location = this._uniformLocations[uniformName];
  26044. if (location === undefined) {
  26045. if (this._buffer) {
  26046. // Cannot add an uniform if the buffer is already created
  26047. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  26048. return;
  26049. }
  26050. this.addUniform(uniformName, size);
  26051. location = this._uniformLocations[uniformName];
  26052. }
  26053. if (!this._buffer) {
  26054. this.create();
  26055. }
  26056. if (!this._dynamic) {
  26057. // Cache for static uniform buffers
  26058. var changed = false;
  26059. for (var i = 0; i < size; i++) {
  26060. if (this._bufferData[location + i] !== data[i]) {
  26061. changed = true;
  26062. this._bufferData[location + i] = data[i];
  26063. }
  26064. }
  26065. this._needSync = this._needSync || changed;
  26066. }
  26067. else {
  26068. // No cache for dynamic
  26069. for (var i = 0; i < size; i++) {
  26070. this._bufferData[location + i] = data[i];
  26071. }
  26072. }
  26073. };
  26074. // Update methods
  26075. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  26076. // To match std140, matrix must be realigned
  26077. for (var i = 0; i < 3; i++) {
  26078. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  26079. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  26080. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  26081. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  26082. }
  26083. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  26084. };
  26085. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  26086. this._currentEffect.setMatrix3x3(name, matrix);
  26087. };
  26088. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  26089. this._currentEffect.setMatrix2x2(name, matrix);
  26090. };
  26091. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  26092. // To match std140, matrix must be realigned
  26093. for (var i = 0; i < 2; i++) {
  26094. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  26095. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  26096. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  26097. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  26098. }
  26099. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  26100. };
  26101. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  26102. this._currentEffect.setFloat(name, x);
  26103. };
  26104. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  26105. UniformBuffer._tempBuffer[0] = x;
  26106. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  26107. };
  26108. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  26109. if (suffix === void 0) { suffix = ""; }
  26110. this._currentEffect.setFloat2(name + suffix, x, y);
  26111. };
  26112. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  26113. if (suffix === void 0) { suffix = ""; }
  26114. UniformBuffer._tempBuffer[0] = x;
  26115. UniformBuffer._tempBuffer[1] = y;
  26116. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  26117. };
  26118. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  26119. if (suffix === void 0) { suffix = ""; }
  26120. this._currentEffect.setFloat3(name + suffix, x, y, z);
  26121. };
  26122. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  26123. if (suffix === void 0) { suffix = ""; }
  26124. UniformBuffer._tempBuffer[0] = x;
  26125. UniformBuffer._tempBuffer[1] = y;
  26126. UniformBuffer._tempBuffer[2] = z;
  26127. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26128. };
  26129. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  26130. if (suffix === void 0) { suffix = ""; }
  26131. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  26132. };
  26133. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  26134. if (suffix === void 0) { suffix = ""; }
  26135. UniformBuffer._tempBuffer[0] = x;
  26136. UniformBuffer._tempBuffer[1] = y;
  26137. UniformBuffer._tempBuffer[2] = z;
  26138. UniformBuffer._tempBuffer[3] = w;
  26139. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26140. };
  26141. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  26142. this._currentEffect.setMatrix(name, mat);
  26143. };
  26144. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  26145. this.updateUniform(name, mat.toArray(), 16);
  26146. };
  26147. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  26148. this._currentEffect.setVector3(name, vector);
  26149. };
  26150. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  26151. vector.toArray(UniformBuffer._tempBuffer);
  26152. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26153. };
  26154. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  26155. this._currentEffect.setVector4(name, vector);
  26156. };
  26157. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  26158. vector.toArray(UniformBuffer._tempBuffer);
  26159. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26160. };
  26161. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  26162. if (suffix === void 0) { suffix = ""; }
  26163. this._currentEffect.setColor3(name + suffix, color);
  26164. };
  26165. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  26166. if (suffix === void 0) { suffix = ""; }
  26167. color.toArray(UniformBuffer._tempBuffer);
  26168. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26169. };
  26170. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  26171. if (suffix === void 0) { suffix = ""; }
  26172. this._currentEffect.setColor4(name + suffix, color, alpha);
  26173. };
  26174. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  26175. if (suffix === void 0) { suffix = ""; }
  26176. color.toArray(UniformBuffer._tempBuffer);
  26177. UniformBuffer._tempBuffer[3] = alpha;
  26178. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26179. };
  26180. /**
  26181. * Sets a sampler uniform on the effect.
  26182. * @param {string} name Name of the sampler.
  26183. * @param {Texture} texture
  26184. */
  26185. UniformBuffer.prototype.setTexture = function (name, texture) {
  26186. this._currentEffect.setTexture(name, texture);
  26187. };
  26188. /**
  26189. * Directly updates the value of the uniform in the cache AND on the GPU.
  26190. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  26191. * @param {number[]|Float32Array} data Flattened data
  26192. */
  26193. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  26194. this.updateUniform(uniformName, data, data.length);
  26195. this.update();
  26196. };
  26197. /**
  26198. * Binds this uniform buffer to an effect.
  26199. * @param {Effect} effect
  26200. * @param {string} name Name of the uniform block in the shader.
  26201. */
  26202. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  26203. this._currentEffect = effect;
  26204. if (this._noUBO) {
  26205. return;
  26206. }
  26207. effect.bindUniformBuffer(this._buffer, name);
  26208. };
  26209. /**
  26210. * Disposes the uniform buffer.
  26211. */
  26212. UniformBuffer.prototype.dispose = function () {
  26213. if (this._noUBO) {
  26214. return;
  26215. }
  26216. var index = this._engine._uniformBuffers.indexOf(this);
  26217. if (index !== -1) {
  26218. this._engine._uniformBuffers.splice(index, 1);
  26219. }
  26220. if (!this._buffer) {
  26221. return;
  26222. }
  26223. if (this._engine._releaseBuffer(this._buffer)) {
  26224. this._buffer = null;
  26225. }
  26226. };
  26227. // Pool for avoiding memory leaks
  26228. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  26229. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  26230. return UniformBuffer;
  26231. }());
  26232. BABYLON.UniformBuffer = UniformBuffer;
  26233. })(BABYLON || (BABYLON = {}));
  26234. //# sourceMappingURL=babylon.uniformBuffer.js.map
  26235. var BABYLON;
  26236. (function (BABYLON) {
  26237. var PushMaterial = (function (_super) {
  26238. __extends(PushMaterial, _super);
  26239. function PushMaterial(name, scene) {
  26240. var _this = _super.call(this, name, scene) || this;
  26241. _this.storeEffectOnSubMeshes = true;
  26242. return _this;
  26243. }
  26244. PushMaterial.prototype.getEffect = function () {
  26245. return this._activeEffect;
  26246. };
  26247. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  26248. if (!mesh) {
  26249. return false;
  26250. }
  26251. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  26252. return true;
  26253. }
  26254. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  26255. };
  26256. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  26257. this._activeEffect.setMatrix("world", world);
  26258. };
  26259. PushMaterial.prototype.bind = function (world, mesh) {
  26260. if (!mesh) {
  26261. return;
  26262. }
  26263. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  26264. };
  26265. PushMaterial.prototype._afterBind = function (mesh, effect) {
  26266. _super.prototype._afterBind.call(this, mesh);
  26267. this.getScene()._cachedEffect = effect;
  26268. };
  26269. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  26270. if (visibility === void 0) { visibility = 1; }
  26271. return scene.isCachedMaterialInvalid(this, effect, visibility);
  26272. };
  26273. return PushMaterial;
  26274. }(BABYLON.Material));
  26275. BABYLON.PushMaterial = PushMaterial;
  26276. })(BABYLON || (BABYLON = {}));
  26277. //# sourceMappingURL=babylon.pushMaterial.js.map
  26278. var BABYLON;
  26279. (function (BABYLON) {
  26280. var VertexData = (function () {
  26281. function VertexData() {
  26282. }
  26283. VertexData.prototype.set = function (data, kind) {
  26284. switch (kind) {
  26285. case BABYLON.VertexBuffer.PositionKind:
  26286. this.positions = data;
  26287. break;
  26288. case BABYLON.VertexBuffer.NormalKind:
  26289. this.normals = data;
  26290. break;
  26291. case BABYLON.VertexBuffer.TangentKind:
  26292. this.tangents = data;
  26293. break;
  26294. case BABYLON.VertexBuffer.UVKind:
  26295. this.uvs = data;
  26296. break;
  26297. case BABYLON.VertexBuffer.UV2Kind:
  26298. this.uvs2 = data;
  26299. break;
  26300. case BABYLON.VertexBuffer.UV3Kind:
  26301. this.uvs3 = data;
  26302. break;
  26303. case BABYLON.VertexBuffer.UV4Kind:
  26304. this.uvs4 = data;
  26305. break;
  26306. case BABYLON.VertexBuffer.UV5Kind:
  26307. this.uvs5 = data;
  26308. break;
  26309. case BABYLON.VertexBuffer.UV6Kind:
  26310. this.uvs6 = data;
  26311. break;
  26312. case BABYLON.VertexBuffer.ColorKind:
  26313. this.colors = data;
  26314. break;
  26315. case BABYLON.VertexBuffer.MatricesIndicesKind:
  26316. this.matricesIndices = data;
  26317. break;
  26318. case BABYLON.VertexBuffer.MatricesWeightsKind:
  26319. this.matricesWeights = data;
  26320. break;
  26321. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  26322. this.matricesIndicesExtra = data;
  26323. break;
  26324. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  26325. this.matricesWeightsExtra = data;
  26326. break;
  26327. }
  26328. };
  26329. /**
  26330. * Associates the vertexData to the passed Mesh.
  26331. * Sets it as updatable or not (default `false`).
  26332. * Returns the VertexData.
  26333. */
  26334. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  26335. this._applyTo(mesh, updatable);
  26336. return this;
  26337. };
  26338. /**
  26339. * Associates the vertexData to the passed Geometry.
  26340. * Sets it as updatable or not (default `false`).
  26341. * Returns the VertexData.
  26342. */
  26343. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  26344. this._applyTo(geometry, updatable);
  26345. return this;
  26346. };
  26347. /**
  26348. * Updates the associated mesh.
  26349. * Returns the VertexData.
  26350. */
  26351. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  26352. this._update(mesh);
  26353. return this;
  26354. };
  26355. /**
  26356. * Updates the associated geometry.
  26357. * Returns the VertexData.
  26358. */
  26359. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  26360. this._update(geometry);
  26361. return this;
  26362. };
  26363. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  26364. if (this.positions) {
  26365. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  26366. }
  26367. if (this.normals) {
  26368. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  26369. }
  26370. if (this.tangents) {
  26371. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  26372. }
  26373. if (this.uvs) {
  26374. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  26375. }
  26376. if (this.uvs2) {
  26377. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  26378. }
  26379. if (this.uvs3) {
  26380. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  26381. }
  26382. if (this.uvs4) {
  26383. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  26384. }
  26385. if (this.uvs5) {
  26386. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  26387. }
  26388. if (this.uvs6) {
  26389. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  26390. }
  26391. if (this.colors) {
  26392. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  26393. }
  26394. if (this.matricesIndices) {
  26395. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  26396. }
  26397. if (this.matricesWeights) {
  26398. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  26399. }
  26400. if (this.matricesIndicesExtra) {
  26401. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  26402. }
  26403. if (this.matricesWeightsExtra) {
  26404. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  26405. }
  26406. if (this.indices) {
  26407. meshOrGeometry.setIndices(this.indices);
  26408. }
  26409. return this;
  26410. };
  26411. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  26412. if (this.positions) {
  26413. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  26414. }
  26415. if (this.normals) {
  26416. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  26417. }
  26418. if (this.tangents) {
  26419. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  26420. }
  26421. if (this.uvs) {
  26422. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  26423. }
  26424. if (this.uvs2) {
  26425. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  26426. }
  26427. if (this.uvs3) {
  26428. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  26429. }
  26430. if (this.uvs4) {
  26431. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  26432. }
  26433. if (this.uvs5) {
  26434. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  26435. }
  26436. if (this.uvs6) {
  26437. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  26438. }
  26439. if (this.colors) {
  26440. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  26441. }
  26442. if (this.matricesIndices) {
  26443. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  26444. }
  26445. if (this.matricesWeights) {
  26446. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  26447. }
  26448. if (this.matricesIndicesExtra) {
  26449. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  26450. }
  26451. if (this.matricesWeightsExtra) {
  26452. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  26453. }
  26454. if (this.indices) {
  26455. meshOrGeometry.setIndices(this.indices);
  26456. }
  26457. return this;
  26458. };
  26459. /**
  26460. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  26461. * Returns the VertexData.
  26462. */
  26463. VertexData.prototype.transform = function (matrix) {
  26464. var transformed = BABYLON.Vector3.Zero();
  26465. var index;
  26466. if (this.positions) {
  26467. var position = BABYLON.Vector3.Zero();
  26468. for (index = 0; index < this.positions.length; index += 3) {
  26469. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  26470. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  26471. this.positions[index] = transformed.x;
  26472. this.positions[index + 1] = transformed.y;
  26473. this.positions[index + 2] = transformed.z;
  26474. }
  26475. }
  26476. if (this.normals) {
  26477. var normal = BABYLON.Vector3.Zero();
  26478. for (index = 0; index < this.normals.length; index += 3) {
  26479. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  26480. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  26481. this.normals[index] = transformed.x;
  26482. this.normals[index + 1] = transformed.y;
  26483. this.normals[index + 2] = transformed.z;
  26484. }
  26485. }
  26486. if (this.tangents) {
  26487. var tangent = BABYLON.Vector4.Zero();
  26488. var tangentTransformed = BABYLON.Vector4.Zero();
  26489. for (index = 0; index < this.tangents.length; index += 4) {
  26490. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  26491. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  26492. this.tangents[index] = tangentTransformed.x;
  26493. this.tangents[index + 1] = tangentTransformed.y;
  26494. this.tangents[index + 2] = tangentTransformed.z;
  26495. this.tangents[index + 3] = tangentTransformed.w;
  26496. }
  26497. }
  26498. return this;
  26499. };
  26500. /**
  26501. * Merges the passed VertexData into the current one.
  26502. * Returns the modified VertexData.
  26503. */
  26504. VertexData.prototype.merge = function (other) {
  26505. if (other.indices) {
  26506. if (!this.indices) {
  26507. this.indices = [];
  26508. }
  26509. var offset = this.positions ? this.positions.length / 3 : 0;
  26510. for (var index = 0; index < other.indices.length; index++) {
  26511. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  26512. this.indices.push(other.indices[index] + offset);
  26513. }
  26514. }
  26515. this.positions = this._mergeElement(this.positions, other.positions);
  26516. this.normals = this._mergeElement(this.normals, other.normals);
  26517. this.tangents = this._mergeElement(this.tangents, other.tangents);
  26518. this.uvs = this._mergeElement(this.uvs, other.uvs);
  26519. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  26520. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  26521. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  26522. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  26523. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  26524. this.colors = this._mergeElement(this.colors, other.colors);
  26525. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  26526. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  26527. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  26528. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  26529. return this;
  26530. };
  26531. VertexData.prototype._mergeElement = function (source, other) {
  26532. if (!other)
  26533. return source;
  26534. if (!source)
  26535. return other;
  26536. var len = other.length + source.length;
  26537. var isSrcTypedArray = source instanceof Float32Array;
  26538. var isOthTypedArray = other instanceof Float32Array;
  26539. // use non-loop method when the source is Float32Array
  26540. if (isSrcTypedArray) {
  26541. var ret32 = new Float32Array(len);
  26542. ret32.set(source);
  26543. ret32.set(other, source.length);
  26544. return ret32;
  26545. // source is number[], when other is also use concat
  26546. }
  26547. else if (!isOthTypedArray) {
  26548. return source.concat(other);
  26549. // source is a number[], but other is a Float32Array, loop required
  26550. }
  26551. else {
  26552. var ret = source.slice(0); // copy source to a separate array
  26553. for (var i = 0, len = other.length; i < len; i++) {
  26554. ret.push(other[i]);
  26555. }
  26556. return ret;
  26557. }
  26558. };
  26559. /**
  26560. * Serializes the VertexData.
  26561. * Returns a serialized object.
  26562. */
  26563. VertexData.prototype.serialize = function () {
  26564. var serializationObject = this.serialize();
  26565. if (this.positions) {
  26566. serializationObject.positions = this.positions;
  26567. }
  26568. if (this.normals) {
  26569. serializationObject.normals = this.normals;
  26570. }
  26571. if (this.tangents) {
  26572. serializationObject.tangents = this.tangents;
  26573. }
  26574. if (this.uvs) {
  26575. serializationObject.uvs = this.uvs;
  26576. }
  26577. if (this.uvs2) {
  26578. serializationObject.uvs2 = this.uvs2;
  26579. }
  26580. if (this.uvs3) {
  26581. serializationObject.uvs3 = this.uvs3;
  26582. }
  26583. if (this.uvs4) {
  26584. serializationObject.uvs4 = this.uvs4;
  26585. }
  26586. if (this.uvs5) {
  26587. serializationObject.uvs5 = this.uvs5;
  26588. }
  26589. if (this.uvs6) {
  26590. serializationObject.uvs6 = this.uvs6;
  26591. }
  26592. if (this.colors) {
  26593. serializationObject.colors = this.colors;
  26594. }
  26595. if (this.matricesIndices) {
  26596. serializationObject.matricesIndices = this.matricesIndices;
  26597. serializationObject.matricesIndices._isExpanded = true;
  26598. }
  26599. if (this.matricesWeights) {
  26600. serializationObject.matricesWeights = this.matricesWeights;
  26601. }
  26602. if (this.matricesIndicesExtra) {
  26603. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  26604. serializationObject.matricesIndicesExtra._isExpanded = true;
  26605. }
  26606. if (this.matricesWeightsExtra) {
  26607. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  26608. }
  26609. serializationObject.indices = this.indices;
  26610. return serializationObject;
  26611. };
  26612. // Statics
  26613. /**
  26614. * Returns the object VertexData associated to the passed mesh.
  26615. */
  26616. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  26617. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  26618. };
  26619. /**
  26620. * Returns the object VertexData associated to the passed geometry.
  26621. */
  26622. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  26623. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  26624. };
  26625. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  26626. var result = new VertexData();
  26627. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26628. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  26629. }
  26630. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26631. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  26632. }
  26633. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  26634. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  26635. }
  26636. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26637. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  26638. }
  26639. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26640. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  26641. }
  26642. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26643. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  26644. }
  26645. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26646. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  26647. }
  26648. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26649. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  26650. }
  26651. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26652. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  26653. }
  26654. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26655. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  26656. }
  26657. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26658. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  26659. }
  26660. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26661. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  26662. }
  26663. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  26664. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  26665. }
  26666. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  26667. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  26668. }
  26669. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  26670. return result;
  26671. };
  26672. /**
  26673. * Creates the vertexData of the Ribbon.
  26674. */
  26675. VertexData.CreateRibbon = function (options) {
  26676. var pathArray = options.pathArray;
  26677. var closeArray = options.closeArray || false;
  26678. var closePath = options.closePath || false;
  26679. var invertUV = options.invertUV || false;
  26680. var defaultOffset = Math.floor(pathArray[0].length / 2);
  26681. var offset = options.offset || defaultOffset;
  26682. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  26683. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26684. var customUV = options.uvs;
  26685. var customColors = options.colors;
  26686. var positions = [];
  26687. var indices = [];
  26688. var normals = [];
  26689. var uvs = [];
  26690. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  26691. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  26692. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  26693. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  26694. var minlg; // minimal length among all paths from pathArray
  26695. var lg = []; // array of path lengths : nb of vertex per path
  26696. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  26697. var p; // path iterator
  26698. var i; // point iterator
  26699. var j; // point iterator
  26700. // if single path in pathArray
  26701. if (pathArray.length < 2) {
  26702. var ar1 = [];
  26703. var ar2 = [];
  26704. for (i = 0; i < pathArray[0].length - offset; i++) {
  26705. ar1.push(pathArray[0][i]);
  26706. ar2.push(pathArray[0][i + offset]);
  26707. }
  26708. pathArray = [ar1, ar2];
  26709. }
  26710. // positions and horizontal distances (u)
  26711. var idc = 0;
  26712. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  26713. var path;
  26714. var l;
  26715. minlg = pathArray[0].length;
  26716. var vectlg;
  26717. var dist;
  26718. for (p = 0; p < pathArray.length; p++) {
  26719. uTotalDistance[p] = 0;
  26720. us[p] = [0];
  26721. path = pathArray[p];
  26722. l = path.length;
  26723. minlg = (minlg < l) ? minlg : l;
  26724. j = 0;
  26725. while (j < l) {
  26726. positions.push(path[j].x, path[j].y, path[j].z);
  26727. if (j > 0) {
  26728. vectlg = path[j].subtract(path[j - 1]).length();
  26729. dist = vectlg + uTotalDistance[p];
  26730. us[p].push(dist);
  26731. uTotalDistance[p] = dist;
  26732. }
  26733. j++;
  26734. }
  26735. if (closePath) {
  26736. j--;
  26737. positions.push(path[0].x, path[0].y, path[0].z);
  26738. vectlg = path[j].subtract(path[0]).length();
  26739. dist = vectlg + uTotalDistance[p];
  26740. us[p].push(dist);
  26741. uTotalDistance[p] = dist;
  26742. }
  26743. lg[p] = l + closePathCorr;
  26744. idx[p] = idc;
  26745. idc += (l + closePathCorr);
  26746. }
  26747. // vertical distances (v)
  26748. var path1;
  26749. var path2;
  26750. var vertex1;
  26751. var vertex2;
  26752. for (i = 0; i < minlg + closePathCorr; i++) {
  26753. vTotalDistance[i] = 0;
  26754. vs[i] = [0];
  26755. for (p = 0; p < pathArray.length - 1; p++) {
  26756. path1 = pathArray[p];
  26757. path2 = pathArray[p + 1];
  26758. if (i === minlg) {
  26759. vertex1 = path1[0];
  26760. vertex2 = path2[0];
  26761. }
  26762. else {
  26763. vertex1 = path1[i];
  26764. vertex2 = path2[i];
  26765. }
  26766. vectlg = vertex2.subtract(vertex1).length();
  26767. dist = vectlg + vTotalDistance[i];
  26768. vs[i].push(dist);
  26769. vTotalDistance[i] = dist;
  26770. }
  26771. if (closeArray) {
  26772. path1 = pathArray[p];
  26773. path2 = pathArray[0];
  26774. if (i === minlg) {
  26775. vertex2 = path2[0];
  26776. }
  26777. vectlg = vertex2.subtract(vertex1).length();
  26778. dist = vectlg + vTotalDistance[i];
  26779. vTotalDistance[i] = dist;
  26780. }
  26781. }
  26782. // uvs
  26783. var u;
  26784. var v;
  26785. if (customUV) {
  26786. for (p = 0; p < customUV.length; p++) {
  26787. uvs.push(customUV[p].x, customUV[p].y);
  26788. }
  26789. }
  26790. else {
  26791. for (p = 0; p < pathArray.length; p++) {
  26792. for (i = 0; i < minlg + closePathCorr; i++) {
  26793. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  26794. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  26795. if (invertUV) {
  26796. uvs.push(v, u);
  26797. }
  26798. else {
  26799. uvs.push(u, v);
  26800. }
  26801. }
  26802. }
  26803. }
  26804. // indices
  26805. p = 0; // path index
  26806. var pi = 0; // positions array index
  26807. var l1 = lg[p] - 1; // path1 length
  26808. var l2 = lg[p + 1] - 1; // path2 length
  26809. var min = (l1 < l2) ? l1 : l2; // current path stop index
  26810. var shft = idx[1] - idx[0]; // shift
  26811. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  26812. while (pi <= min && p < path1nb) {
  26813. // 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
  26814. indices.push(pi, pi + shft, pi + 1);
  26815. indices.push(pi + shft + 1, pi + 1, pi + shft);
  26816. pi += 1;
  26817. if (pi === min) {
  26818. p++;
  26819. if (p === lg.length - 1) {
  26820. shft = idx[0] - idx[p];
  26821. l1 = lg[p] - 1;
  26822. l2 = lg[0] - 1;
  26823. }
  26824. else {
  26825. shft = idx[p + 1] - idx[p];
  26826. l1 = lg[p] - 1;
  26827. l2 = lg[p + 1] - 1;
  26828. }
  26829. pi = idx[p];
  26830. min = (l1 < l2) ? l1 + pi : l2 + pi;
  26831. }
  26832. }
  26833. // normals
  26834. VertexData.ComputeNormals(positions, indices, normals);
  26835. if (closePath) {
  26836. var indexFirst = 0;
  26837. var indexLast = 0;
  26838. for (p = 0; p < pathArray.length; p++) {
  26839. indexFirst = idx[p] * 3;
  26840. if (p + 1 < pathArray.length) {
  26841. indexLast = (idx[p + 1] - 1) * 3;
  26842. }
  26843. else {
  26844. indexLast = normals.length - 3;
  26845. }
  26846. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  26847. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  26848. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  26849. normals[indexLast] = normals[indexFirst];
  26850. normals[indexLast + 1] = normals[indexFirst + 1];
  26851. normals[indexLast + 2] = normals[indexFirst + 2];
  26852. }
  26853. }
  26854. // sides
  26855. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26856. // Colors
  26857. if (customColors) {
  26858. var colors = new Float32Array(customColors.length * 4);
  26859. for (var c = 0; c < customColors.length; c++) {
  26860. colors[c * 4] = customColors[c].r;
  26861. colors[c * 4 + 1] = customColors[c].g;
  26862. colors[c * 4 + 2] = customColors[c].b;
  26863. colors[c * 4 + 3] = customColors[c].a;
  26864. }
  26865. }
  26866. // Result
  26867. var vertexData = new VertexData();
  26868. var positions32 = new Float32Array(positions);
  26869. var normals32 = new Float32Array(normals);
  26870. var uvs32 = new Float32Array(uvs);
  26871. vertexData.indices = indices;
  26872. vertexData.positions = positions32;
  26873. vertexData.normals = normals32;
  26874. vertexData.uvs = uvs32;
  26875. if (customColors) {
  26876. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  26877. }
  26878. if (closePath) {
  26879. vertexData._idx = idx;
  26880. }
  26881. return vertexData;
  26882. };
  26883. /**
  26884. * Creates the VertexData of the Box.
  26885. */
  26886. VertexData.CreateBox = function (options) {
  26887. var normalsSource = [
  26888. new BABYLON.Vector3(0, 0, 1),
  26889. new BABYLON.Vector3(0, 0, -1),
  26890. new BABYLON.Vector3(1, 0, 0),
  26891. new BABYLON.Vector3(-1, 0, 0),
  26892. new BABYLON.Vector3(0, 1, 0),
  26893. new BABYLON.Vector3(0, -1, 0)
  26894. ];
  26895. var indices = [];
  26896. var positions = [];
  26897. var normals = [];
  26898. var uvs = [];
  26899. var width = options.width || options.size || 1;
  26900. var height = options.height || options.size || 1;
  26901. var depth = options.depth || options.size || 1;
  26902. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26903. var faceUV = options.faceUV || new Array(6);
  26904. var faceColors = options.faceColors;
  26905. var colors = [];
  26906. // default face colors and UV if undefined
  26907. for (var f = 0; f < 6; f++) {
  26908. if (faceUV[f] === undefined) {
  26909. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26910. }
  26911. if (faceColors && faceColors[f] === undefined) {
  26912. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26913. }
  26914. }
  26915. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  26916. // Create each face in turn.
  26917. for (var index = 0; index < normalsSource.length; index++) {
  26918. var normal = normalsSource[index];
  26919. // Get two vectors perpendicular to the face normal and to each other.
  26920. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  26921. var side2 = BABYLON.Vector3.Cross(normal, side1);
  26922. // Six indices (two triangles) per face.
  26923. var verticesLength = positions.length / 3;
  26924. indices.push(verticesLength);
  26925. indices.push(verticesLength + 1);
  26926. indices.push(verticesLength + 2);
  26927. indices.push(verticesLength);
  26928. indices.push(verticesLength + 2);
  26929. indices.push(verticesLength + 3);
  26930. // Four vertices per face.
  26931. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  26932. positions.push(vertex.x, vertex.y, vertex.z);
  26933. normals.push(normal.x, normal.y, normal.z);
  26934. uvs.push(faceUV[index].z, faceUV[index].w);
  26935. if (faceColors) {
  26936. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26937. }
  26938. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  26939. positions.push(vertex.x, vertex.y, vertex.z);
  26940. normals.push(normal.x, normal.y, normal.z);
  26941. uvs.push(faceUV[index].x, faceUV[index].w);
  26942. if (faceColors) {
  26943. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26944. }
  26945. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  26946. positions.push(vertex.x, vertex.y, vertex.z);
  26947. normals.push(normal.x, normal.y, normal.z);
  26948. uvs.push(faceUV[index].x, faceUV[index].y);
  26949. if (faceColors) {
  26950. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26951. }
  26952. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  26953. positions.push(vertex.x, vertex.y, vertex.z);
  26954. normals.push(normal.x, normal.y, normal.z);
  26955. uvs.push(faceUV[index].z, faceUV[index].y);
  26956. if (faceColors) {
  26957. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26958. }
  26959. }
  26960. // sides
  26961. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26962. // Result
  26963. var vertexData = new VertexData();
  26964. vertexData.indices = indices;
  26965. vertexData.positions = positions;
  26966. vertexData.normals = normals;
  26967. vertexData.uvs = uvs;
  26968. if (faceColors) {
  26969. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  26970. vertexData.colors = totalColors;
  26971. }
  26972. return vertexData;
  26973. };
  26974. /**
  26975. * Creates the VertexData of the Sphere.
  26976. */
  26977. VertexData.CreateSphere = function (options) {
  26978. var segments = options.segments || 32;
  26979. var diameterX = options.diameterX || options.diameter || 1;
  26980. var diameterY = options.diameterY || options.diameter || 1;
  26981. var diameterZ = options.diameterZ || options.diameter || 1;
  26982. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  26983. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  26984. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26985. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  26986. var totalZRotationSteps = 2 + segments;
  26987. var totalYRotationSteps = 2 * totalZRotationSteps;
  26988. var indices = [];
  26989. var positions = [];
  26990. var normals = [];
  26991. var uvs = [];
  26992. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  26993. var normalizedZ = zRotationStep / totalZRotationSteps;
  26994. var angleZ = normalizedZ * Math.PI * slice;
  26995. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  26996. var normalizedY = yRotationStep / totalYRotationSteps;
  26997. var angleY = normalizedY * Math.PI * 2 * arc;
  26998. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  26999. var rotationY = BABYLON.Matrix.RotationY(angleY);
  27000. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  27001. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  27002. var vertex = complete.multiply(radius);
  27003. var normal = complete.divide(radius).normalize();
  27004. positions.push(vertex.x, vertex.y, vertex.z);
  27005. normals.push(normal.x, normal.y, normal.z);
  27006. uvs.push(normalizedY, normalizedZ);
  27007. }
  27008. if (zRotationStep > 0) {
  27009. var verticesCount = positions.length / 3;
  27010. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  27011. indices.push((firstIndex));
  27012. indices.push((firstIndex + 1));
  27013. indices.push(firstIndex + totalYRotationSteps + 1);
  27014. indices.push((firstIndex + totalYRotationSteps + 1));
  27015. indices.push((firstIndex + 1));
  27016. indices.push((firstIndex + totalYRotationSteps + 2));
  27017. }
  27018. }
  27019. }
  27020. // Sides
  27021. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27022. // Result
  27023. var vertexData = new VertexData();
  27024. vertexData.indices = indices;
  27025. vertexData.positions = positions;
  27026. vertexData.normals = normals;
  27027. vertexData.uvs = uvs;
  27028. return vertexData;
  27029. };
  27030. /**
  27031. * Creates the VertexData of the Cylinder or Cone.
  27032. */
  27033. VertexData.CreateCylinder = function (options) {
  27034. var height = options.height || 2;
  27035. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  27036. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  27037. var tessellation = options.tessellation || 24;
  27038. var subdivisions = options.subdivisions || 1;
  27039. var hasRings = options.hasRings;
  27040. var enclose = options.enclose;
  27041. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27042. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27043. var faceUV = options.faceUV || new Array(3);
  27044. var faceColors = options.faceColors;
  27045. // default face colors and UV if undefined
  27046. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  27047. var ringNb = (hasRings) ? subdivisions : 1;
  27048. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  27049. var f;
  27050. for (f = 0; f < surfaceNb; f++) {
  27051. if (faceColors && faceColors[f] === undefined) {
  27052. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27053. }
  27054. }
  27055. for (f = 0; f < surfaceNb; f++) {
  27056. if (faceUV && faceUV[f] === undefined) {
  27057. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27058. }
  27059. }
  27060. var indices = [];
  27061. var positions = [];
  27062. var normals = [];
  27063. var uvs = [];
  27064. var colors = [];
  27065. var angle_step = Math.PI * 2 * arc / tessellation;
  27066. var angle;
  27067. var h;
  27068. var radius;
  27069. var tan = (diameterBottom - diameterTop) / 2 / height;
  27070. var ringVertex = BABYLON.Vector3.Zero();
  27071. var ringNormal = BABYLON.Vector3.Zero();
  27072. var ringFirstVertex = BABYLON.Vector3.Zero();
  27073. var ringFirstNormal = BABYLON.Vector3.Zero();
  27074. var quadNormal = BABYLON.Vector3.Zero();
  27075. var Y = BABYLON.Axis.Y;
  27076. // positions, normals, uvs
  27077. var i;
  27078. var j;
  27079. var r;
  27080. var ringIdx = 1;
  27081. var s = 1; // surface index
  27082. var cs = 0;
  27083. var v = 0;
  27084. for (i = 0; i <= subdivisions; i++) {
  27085. h = i / subdivisions;
  27086. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  27087. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  27088. for (r = 0; r < ringIdx; r++) {
  27089. if (hasRings) {
  27090. s += r;
  27091. }
  27092. if (enclose) {
  27093. s += 2 * r;
  27094. }
  27095. for (j = 0; j <= tessellation; j++) {
  27096. angle = j * angle_step;
  27097. // position
  27098. ringVertex.x = Math.cos(-angle) * radius;
  27099. ringVertex.y = -height / 2 + h * height;
  27100. ringVertex.z = Math.sin(-angle) * radius;
  27101. // normal
  27102. if (diameterTop === 0 && i === subdivisions) {
  27103. // if no top cap, reuse former normals
  27104. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  27105. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  27106. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  27107. }
  27108. else {
  27109. ringNormal.x = ringVertex.x;
  27110. ringNormal.z = ringVertex.z;
  27111. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  27112. ringNormal.normalize();
  27113. }
  27114. // keep first ring vertex values for enclose
  27115. if (j === 0) {
  27116. ringFirstVertex.copyFrom(ringVertex);
  27117. ringFirstNormal.copyFrom(ringNormal);
  27118. }
  27119. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27120. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  27121. if (hasRings) {
  27122. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  27123. }
  27124. else {
  27125. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  27126. }
  27127. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  27128. if (faceColors) {
  27129. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  27130. }
  27131. }
  27132. // if enclose, add four vertices and their dedicated normals
  27133. if (arc !== 1 && enclose) {
  27134. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27135. positions.push(0, ringVertex.y, 0);
  27136. positions.push(0, ringVertex.y, 0);
  27137. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  27138. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  27139. quadNormal.normalize();
  27140. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  27141. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  27142. quadNormal.normalize();
  27143. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  27144. if (hasRings) {
  27145. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  27146. }
  27147. else {
  27148. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  27149. }
  27150. uvs.push(faceUV[s + 1].x, v);
  27151. uvs.push(faceUV[s + 1].z, v);
  27152. if (hasRings) {
  27153. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  27154. }
  27155. else {
  27156. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  27157. }
  27158. uvs.push(faceUV[s + 2].x, v);
  27159. uvs.push(faceUV[s + 2].z, v);
  27160. if (faceColors) {
  27161. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  27162. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  27163. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  27164. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  27165. }
  27166. }
  27167. if (cs !== s) {
  27168. cs = s;
  27169. }
  27170. }
  27171. }
  27172. // indices
  27173. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  27174. var s;
  27175. i = 0;
  27176. for (s = 0; s < subdivisions; s++) {
  27177. for (j = 0; j < tessellation; j++) {
  27178. var i0 = i * (e + 1) + j;
  27179. var i1 = (i + 1) * (e + 1) + j;
  27180. var i2 = i * (e + 1) + (j + 1);
  27181. var i3 = (i + 1) * (e + 1) + (j + 1);
  27182. indices.push(i0, i1, i2);
  27183. indices.push(i3, i2, i1);
  27184. }
  27185. if (arc !== 1 && enclose) {
  27186. indices.push(i0 + 2, i1 + 2, i2 + 2);
  27187. indices.push(i3 + 2, i2 + 2, i1 + 2);
  27188. indices.push(i0 + 4, i1 + 4, i2 + 4);
  27189. indices.push(i3 + 4, i2 + 4, i1 + 4);
  27190. }
  27191. i = (hasRings) ? (i + 2) : (i + 1);
  27192. }
  27193. // Caps
  27194. var createCylinderCap = function (isTop) {
  27195. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  27196. if (radius === 0) {
  27197. return;
  27198. }
  27199. // Cap positions, normals & uvs
  27200. var angle;
  27201. var circleVector;
  27202. var i;
  27203. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  27204. var c;
  27205. if (faceColors) {
  27206. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  27207. }
  27208. // cap center
  27209. var vbase = positions.length / 3;
  27210. var offset = isTop ? height / 2 : -height / 2;
  27211. var center = new BABYLON.Vector3(0, offset, 0);
  27212. positions.push(center.x, center.y, center.z);
  27213. normals.push(0, isTop ? 1 : -1, 0);
  27214. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  27215. if (faceColors) {
  27216. colors.push(c.r, c.g, c.b, c.a);
  27217. }
  27218. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  27219. for (i = 0; i <= tessellation; i++) {
  27220. angle = Math.PI * 2 * i * arc / tessellation;
  27221. var cos = Math.cos(-angle);
  27222. var sin = Math.sin(-angle);
  27223. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  27224. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  27225. positions.push(circleVector.x, circleVector.y, circleVector.z);
  27226. normals.push(0, isTop ? 1 : -1, 0);
  27227. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  27228. if (faceColors) {
  27229. colors.push(c.r, c.g, c.b, c.a);
  27230. }
  27231. }
  27232. // Cap indices
  27233. for (i = 0; i < tessellation; i++) {
  27234. if (!isTop) {
  27235. indices.push(vbase);
  27236. indices.push(vbase + (i + 1));
  27237. indices.push(vbase + (i + 2));
  27238. }
  27239. else {
  27240. indices.push(vbase);
  27241. indices.push(vbase + (i + 2));
  27242. indices.push(vbase + (i + 1));
  27243. }
  27244. }
  27245. };
  27246. // add caps to geometry
  27247. createCylinderCap(false);
  27248. createCylinderCap(true);
  27249. // Sides
  27250. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27251. var vertexData = new VertexData();
  27252. vertexData.indices = indices;
  27253. vertexData.positions = positions;
  27254. vertexData.normals = normals;
  27255. vertexData.uvs = uvs;
  27256. if (faceColors) {
  27257. vertexData.colors = colors;
  27258. }
  27259. return vertexData;
  27260. };
  27261. /**
  27262. * Creates the VertexData of the Torus.
  27263. */
  27264. VertexData.CreateTorus = function (options) {
  27265. var indices = [];
  27266. var positions = [];
  27267. var normals = [];
  27268. var uvs = [];
  27269. var diameter = options.diameter || 1;
  27270. var thickness = options.thickness || 0.5;
  27271. var tessellation = options.tessellation || 16;
  27272. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27273. var stride = tessellation + 1;
  27274. for (var i = 0; i <= tessellation; i++) {
  27275. var u = i / tessellation;
  27276. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  27277. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  27278. for (var j = 0; j <= tessellation; j++) {
  27279. var v = 1 - j / tessellation;
  27280. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  27281. var dx = Math.cos(innerAngle);
  27282. var dy = Math.sin(innerAngle);
  27283. // Create a vertex.
  27284. var normal = new BABYLON.Vector3(dx, dy, 0);
  27285. var position = normal.scale(thickness / 2);
  27286. var textureCoordinate = new BABYLON.Vector2(u, v);
  27287. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  27288. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  27289. positions.push(position.x, position.y, position.z);
  27290. normals.push(normal.x, normal.y, normal.z);
  27291. uvs.push(textureCoordinate.x, textureCoordinate.y);
  27292. // And create indices for two triangles.
  27293. var nextI = (i + 1) % stride;
  27294. var nextJ = (j + 1) % stride;
  27295. indices.push(i * stride + j);
  27296. indices.push(i * stride + nextJ);
  27297. indices.push(nextI * stride + j);
  27298. indices.push(i * stride + nextJ);
  27299. indices.push(nextI * stride + nextJ);
  27300. indices.push(nextI * stride + j);
  27301. }
  27302. }
  27303. // Sides
  27304. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27305. // Result
  27306. var vertexData = new VertexData();
  27307. vertexData.indices = indices;
  27308. vertexData.positions = positions;
  27309. vertexData.normals = normals;
  27310. vertexData.uvs = uvs;
  27311. return vertexData;
  27312. };
  27313. /**
  27314. * Creates the VertexData of the LineSystem.
  27315. */
  27316. VertexData.CreateLineSystem = function (options) {
  27317. var indices = [];
  27318. var positions = [];
  27319. var lines = options.lines;
  27320. var idx = 0;
  27321. for (var l = 0; l < lines.length; l++) {
  27322. var points = lines[l];
  27323. for (var index = 0; index < points.length; index++) {
  27324. positions.push(points[index].x, points[index].y, points[index].z);
  27325. if (index > 0) {
  27326. indices.push(idx - 1);
  27327. indices.push(idx);
  27328. }
  27329. idx++;
  27330. }
  27331. }
  27332. var vertexData = new VertexData();
  27333. vertexData.indices = indices;
  27334. vertexData.positions = positions;
  27335. return vertexData;
  27336. };
  27337. /**
  27338. * Create the VertexData of the DashedLines.
  27339. */
  27340. VertexData.CreateDashedLines = function (options) {
  27341. var dashSize = options.dashSize || 3;
  27342. var gapSize = options.gapSize || 1;
  27343. var dashNb = options.dashNb || 200;
  27344. var points = options.points;
  27345. var positions = new Array();
  27346. var indices = new Array();
  27347. var curvect = BABYLON.Vector3.Zero();
  27348. var lg = 0;
  27349. var nb = 0;
  27350. var shft = 0;
  27351. var dashshft = 0;
  27352. var curshft = 0;
  27353. var idx = 0;
  27354. var i = 0;
  27355. for (i = 0; i < points.length - 1; i++) {
  27356. points[i + 1].subtractToRef(points[i], curvect);
  27357. lg += curvect.length();
  27358. }
  27359. shft = lg / dashNb;
  27360. dashshft = dashSize * shft / (dashSize + gapSize);
  27361. for (i = 0; i < points.length - 1; i++) {
  27362. points[i + 1].subtractToRef(points[i], curvect);
  27363. nb = Math.floor(curvect.length() / shft);
  27364. curvect.normalize();
  27365. for (var j = 0; j < nb; j++) {
  27366. curshft = shft * j;
  27367. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  27368. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  27369. indices.push(idx, idx + 1);
  27370. idx += 2;
  27371. }
  27372. }
  27373. // Result
  27374. var vertexData = new VertexData();
  27375. vertexData.positions = positions;
  27376. vertexData.indices = indices;
  27377. return vertexData;
  27378. };
  27379. /**
  27380. * Creates the VertexData of the Ground.
  27381. */
  27382. VertexData.CreateGround = function (options) {
  27383. var indices = [];
  27384. var positions = [];
  27385. var normals = [];
  27386. var uvs = [];
  27387. var row, col;
  27388. var width = options.width || 1;
  27389. var height = options.height || 1;
  27390. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  27391. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  27392. for (row = 0; row <= subdivisionsY; row++) {
  27393. for (col = 0; col <= subdivisionsX; col++) {
  27394. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  27395. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27396. positions.push(position.x, position.y, position.z);
  27397. normals.push(normal.x, normal.y, normal.z);
  27398. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  27399. }
  27400. }
  27401. for (row = 0; row < subdivisionsY; row++) {
  27402. for (col = 0; col < subdivisionsX; col++) {
  27403. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  27404. indices.push(col + 1 + row * (subdivisionsX + 1));
  27405. indices.push(col + row * (subdivisionsX + 1));
  27406. indices.push(col + (row + 1) * (subdivisionsX + 1));
  27407. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  27408. indices.push(col + row * (subdivisionsX + 1));
  27409. }
  27410. }
  27411. // Result
  27412. var vertexData = new VertexData();
  27413. vertexData.indices = indices;
  27414. vertexData.positions = positions;
  27415. vertexData.normals = normals;
  27416. vertexData.uvs = uvs;
  27417. return vertexData;
  27418. };
  27419. /**
  27420. * Creates the VertexData of the TiledGround.
  27421. */
  27422. VertexData.CreateTiledGround = function (options) {
  27423. var xmin = options.xmin || -1.0;
  27424. var zmin = options.zmin || -1.0;
  27425. var xmax = options.xmax || 1.0;
  27426. var zmax = options.zmax || 1.0;
  27427. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  27428. var precision = options.precision || { w: 1, h: 1 };
  27429. var indices = [];
  27430. var positions = [];
  27431. var normals = [];
  27432. var uvs = [];
  27433. var row, col, tileRow, tileCol;
  27434. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  27435. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  27436. precision.w = (precision.w < 1) ? 1 : precision.w;
  27437. precision.h = (precision.h < 1) ? 1 : precision.h;
  27438. var tileSize = {
  27439. 'w': (xmax - xmin) / subdivisions.w,
  27440. 'h': (zmax - zmin) / subdivisions.h
  27441. };
  27442. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  27443. // Indices
  27444. var base = positions.length / 3;
  27445. var rowLength = precision.w + 1;
  27446. for (row = 0; row < precision.h; row++) {
  27447. for (col = 0; col < precision.w; col++) {
  27448. var square = [
  27449. base + col + row * rowLength,
  27450. base + (col + 1) + row * rowLength,
  27451. base + (col + 1) + (row + 1) * rowLength,
  27452. base + col + (row + 1) * rowLength
  27453. ];
  27454. indices.push(square[1]);
  27455. indices.push(square[2]);
  27456. indices.push(square[3]);
  27457. indices.push(square[0]);
  27458. indices.push(square[1]);
  27459. indices.push(square[3]);
  27460. }
  27461. }
  27462. // Position, normals and uvs
  27463. var position = BABYLON.Vector3.Zero();
  27464. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27465. for (row = 0; row <= precision.h; row++) {
  27466. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  27467. for (col = 0; col <= precision.w; col++) {
  27468. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  27469. position.y = 0;
  27470. positions.push(position.x, position.y, position.z);
  27471. normals.push(normal.x, normal.y, normal.z);
  27472. uvs.push(col / precision.w, row / precision.h);
  27473. }
  27474. }
  27475. }
  27476. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  27477. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  27478. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  27479. }
  27480. }
  27481. // Result
  27482. var vertexData = new VertexData();
  27483. vertexData.indices = indices;
  27484. vertexData.positions = positions;
  27485. vertexData.normals = normals;
  27486. vertexData.uvs = uvs;
  27487. return vertexData;
  27488. };
  27489. /**
  27490. * Creates the VertexData of the Ground designed from a heightmap.
  27491. */
  27492. VertexData.CreateGroundFromHeightMap = function (options) {
  27493. var indices = [];
  27494. var positions = [];
  27495. var normals = [];
  27496. var uvs = [];
  27497. var row, col;
  27498. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  27499. // Vertices
  27500. for (row = 0; row <= options.subdivisions; row++) {
  27501. for (col = 0; col <= options.subdivisions; col++) {
  27502. 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));
  27503. // Compute height
  27504. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  27505. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  27506. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  27507. var r = options.buffer[pos] / 255.0;
  27508. var g = options.buffer[pos + 1] / 255.0;
  27509. var b = options.buffer[pos + 2] / 255.0;
  27510. var gradient = r * filter.r + g * filter.g + b * filter.b;
  27511. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  27512. // Add vertex
  27513. positions.push(position.x, position.y, position.z);
  27514. normals.push(0, 0, 0);
  27515. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  27516. }
  27517. }
  27518. // Indices
  27519. for (row = 0; row < options.subdivisions; row++) {
  27520. for (col = 0; col < options.subdivisions; col++) {
  27521. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27522. indices.push(col + 1 + row * (options.subdivisions + 1));
  27523. indices.push(col + row * (options.subdivisions + 1));
  27524. indices.push(col + (row + 1) * (options.subdivisions + 1));
  27525. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27526. indices.push(col + row * (options.subdivisions + 1));
  27527. }
  27528. }
  27529. // Normals
  27530. VertexData.ComputeNormals(positions, indices, normals);
  27531. // Result
  27532. var vertexData = new VertexData();
  27533. vertexData.indices = indices;
  27534. vertexData.positions = positions;
  27535. vertexData.normals = normals;
  27536. vertexData.uvs = uvs;
  27537. return vertexData;
  27538. };
  27539. /**
  27540. * Creates the VertexData of the Plane.
  27541. */
  27542. VertexData.CreatePlane = function (options) {
  27543. var indices = [];
  27544. var positions = [];
  27545. var normals = [];
  27546. var uvs = [];
  27547. var width = options.width || options.size || 1;
  27548. var height = options.height || options.size || 1;
  27549. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27550. // Vertices
  27551. var halfWidth = width / 2.0;
  27552. var halfHeight = height / 2.0;
  27553. positions.push(-halfWidth, -halfHeight, 0);
  27554. normals.push(0, 0, -1.0);
  27555. uvs.push(0.0, 0.0);
  27556. positions.push(halfWidth, -halfHeight, 0);
  27557. normals.push(0, 0, -1.0);
  27558. uvs.push(1.0, 0.0);
  27559. positions.push(halfWidth, halfHeight, 0);
  27560. normals.push(0, 0, -1.0);
  27561. uvs.push(1.0, 1.0);
  27562. positions.push(-halfWidth, halfHeight, 0);
  27563. normals.push(0, 0, -1.0);
  27564. uvs.push(0.0, 1.0);
  27565. // Indices
  27566. indices.push(0);
  27567. indices.push(1);
  27568. indices.push(2);
  27569. indices.push(0);
  27570. indices.push(2);
  27571. indices.push(3);
  27572. // Sides
  27573. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27574. // Result
  27575. var vertexData = new VertexData();
  27576. vertexData.indices = indices;
  27577. vertexData.positions = positions;
  27578. vertexData.normals = normals;
  27579. vertexData.uvs = uvs;
  27580. return vertexData;
  27581. };
  27582. /**
  27583. * Creates the VertexData of the Disc or regular Polygon.
  27584. */
  27585. VertexData.CreateDisc = function (options) {
  27586. var positions = [];
  27587. var indices = [];
  27588. var normals = [];
  27589. var uvs = [];
  27590. var radius = options.radius || 0.5;
  27591. var tessellation = options.tessellation || 64;
  27592. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27593. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27594. // positions and uvs
  27595. positions.push(0, 0, 0); // disc center first
  27596. uvs.push(0.5, 0.5);
  27597. var theta = Math.PI * 2 * arc;
  27598. var step = theta / tessellation;
  27599. for (var a = 0; a < theta; a += step) {
  27600. var x = Math.cos(a);
  27601. var y = Math.sin(a);
  27602. var u = (x + 1) / 2;
  27603. var v = (1 - y) / 2;
  27604. positions.push(radius * x, radius * y, 0);
  27605. uvs.push(u, v);
  27606. }
  27607. if (arc === 1) {
  27608. positions.push(positions[3], positions[4], positions[5]); // close the circle
  27609. uvs.push(uvs[2], uvs[3]);
  27610. }
  27611. //indices
  27612. var vertexNb = positions.length / 3;
  27613. for (var i = 1; i < vertexNb - 1; i++) {
  27614. indices.push(i + 1, 0, i);
  27615. }
  27616. // result
  27617. VertexData.ComputeNormals(positions, indices, normals);
  27618. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27619. var vertexData = new VertexData();
  27620. vertexData.indices = indices;
  27621. vertexData.positions = positions;
  27622. vertexData.normals = normals;
  27623. vertexData.uvs = uvs;
  27624. return vertexData;
  27625. };
  27626. /**
  27627. * Re-creates the VertexData of the Polygon for sideOrientation.
  27628. */
  27629. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  27630. var faceUV = fUV || new Array(3);
  27631. var faceColors = fColors;
  27632. var colors = [];
  27633. // default face colors and UV if undefined
  27634. for (var f = 0; f < 3; f++) {
  27635. if (faceUV[f] === undefined) {
  27636. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27637. }
  27638. if (faceColors && faceColors[f] === undefined) {
  27639. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27640. }
  27641. }
  27642. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27643. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27644. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  27645. var indices = polygon.getIndices();
  27646. // set face colours and textures
  27647. var idx = 0;
  27648. var face = 0;
  27649. for (var index = 0; index < normals.length; index += 3) {
  27650. //Edge Face no. 1
  27651. if (Math.abs(normals[index + 1]) < 0.001) {
  27652. face = 1;
  27653. }
  27654. //Top Face no. 0
  27655. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  27656. face = 0;
  27657. }
  27658. //Bottom Face no. 2
  27659. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  27660. face = 2;
  27661. }
  27662. idx = index / 3;
  27663. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  27664. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  27665. if (faceColors) {
  27666. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  27667. }
  27668. }
  27669. // sides
  27670. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  27671. // Result
  27672. var vertexData = new VertexData();
  27673. vertexData.indices = indices;
  27674. vertexData.positions = positions;
  27675. vertexData.normals = normals;
  27676. vertexData.uvs = uvs;
  27677. if (faceColors) {
  27678. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  27679. vertexData.colors = totalColors;
  27680. }
  27681. return vertexData;
  27682. };
  27683. /**
  27684. * Creates the VertexData of the IcoSphere.
  27685. */
  27686. VertexData.CreateIcoSphere = function (options) {
  27687. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27688. var radius = options.radius || 1;
  27689. var flat = (options.flat === undefined) ? true : options.flat;
  27690. var subdivisions = options.subdivisions || 4;
  27691. var radiusX = options.radiusX || radius;
  27692. var radiusY = options.radiusY || radius;
  27693. var radiusZ = options.radiusZ || radius;
  27694. var t = (1 + Math.sqrt(5)) / 2;
  27695. // 12 vertex x,y,z
  27696. var ico_vertices = [
  27697. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  27698. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  27699. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  27700. ];
  27701. // index of 3 vertex makes a face of icopshere
  27702. var ico_indices = [
  27703. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  27704. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  27705. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  27706. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  27707. ];
  27708. // vertex for uv have aliased position, not for UV
  27709. var vertices_unalias_id = [
  27710. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  27711. // vertex alias
  27712. 0,
  27713. 2,
  27714. 3,
  27715. 3,
  27716. 3,
  27717. 4,
  27718. 7,
  27719. 8,
  27720. 9,
  27721. 9,
  27722. 10,
  27723. 11 // 23: B + 12
  27724. ];
  27725. // uv as integer step (not pixels !)
  27726. var ico_vertexuv = [
  27727. 5, 1, 3, 1, 6, 4, 0, 0,
  27728. 5, 3, 4, 2, 2, 2, 4, 0,
  27729. 2, 0, 1, 1, 6, 0, 6, 2,
  27730. // vertex alias (for same vertex on different faces)
  27731. 0, 4,
  27732. 3, 3,
  27733. 4, 4,
  27734. 3, 1,
  27735. 4, 2,
  27736. 4, 4,
  27737. 0, 2,
  27738. 1, 1,
  27739. 2, 2,
  27740. 3, 3,
  27741. 1, 3,
  27742. 2, 4 // 23: B + 12
  27743. ];
  27744. // Vertices[0, 1, ...9, A, B] : position on UV plane
  27745. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  27746. // First island of uv mapping
  27747. // v = 4h 3+ 2
  27748. // v = 3h 9+ 4
  27749. // v = 2h 9+ 5 B
  27750. // v = 1h 9 1 0
  27751. // v = 0h 3 8 7 A
  27752. // u = 0 1 2 3 4 5 6 *a
  27753. // Second island of uv mapping
  27754. // v = 4h 0+ B+ 4+
  27755. // v = 3h A+ 2+
  27756. // v = 2h 7+ 6 3+
  27757. // v = 1h 8+ 3+
  27758. // v = 0h
  27759. // u = 0 1 2 3 4 5 6 *a
  27760. // Face layout on texture UV mapping
  27761. // ============
  27762. // \ 4 /\ 16 / ======
  27763. // \ / \ / /\ 11 /
  27764. // \/ 7 \/ / \ /
  27765. // ======= / 10 \/
  27766. // /\ 17 /\ =======
  27767. // / \ / \ \ 15 /\
  27768. // / 8 \/ 12 \ \ / \
  27769. // ============ \/ 6 \
  27770. // \ 18 /\ ============
  27771. // \ / \ \ 5 /\ 0 /
  27772. // \/ 13 \ \ / \ /
  27773. // ======= \/ 1 \/
  27774. // =============
  27775. // /\ 19 /\ 2 /\
  27776. // / \ / \ / \
  27777. // / 14 \/ 9 \/ 3 \
  27778. // ===================
  27779. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  27780. var ustep = 138 / 1024;
  27781. var vstep = 239 / 1024;
  27782. var uoffset = 60 / 1024;
  27783. var voffset = 26 / 1024;
  27784. // Second island should have margin, not to touch the first island
  27785. // avoid any borderline artefact in pixel rounding
  27786. var island_u_offset = -40 / 1024;
  27787. var island_v_offset = +20 / 1024;
  27788. // face is either island 0 or 1 :
  27789. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  27790. var island = [
  27791. 0, 0, 0, 0, 1,
  27792. 0, 0, 1, 1, 0,
  27793. 0, 0, 1, 1, 0,
  27794. 0, 1, 1, 1, 0 // 15 - 19
  27795. ];
  27796. var indices = [];
  27797. var positions = [];
  27798. var normals = [];
  27799. var uvs = [];
  27800. var current_indice = 0;
  27801. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  27802. var face_vertex_pos = new Array(3);
  27803. var face_vertex_uv = new Array(3);
  27804. var v012;
  27805. for (v012 = 0; v012 < 3; v012++) {
  27806. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  27807. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  27808. }
  27809. // create all with normals
  27810. for (var face = 0; face < 20; face++) {
  27811. // 3 vertex per face
  27812. for (v012 = 0; v012 < 3; v012++) {
  27813. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  27814. var v_id = ico_indices[3 * face + v012];
  27815. // vertex have 3D position (x,y,z)
  27816. 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]);
  27817. // Normalize to get normal, then scale to radius
  27818. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  27819. // uv Coordinates from vertex ID
  27820. 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);
  27821. }
  27822. // Subdivide the face (interpolate pos, norm, uv)
  27823. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  27824. // - norm is linear interpolation of vertex corner normal
  27825. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  27826. // - uv is linear interpolation
  27827. //
  27828. // Topology is as below for sub-divide by 2
  27829. // vertex shown as v0,v1,v2
  27830. // interp index is i1 to progress in range [v0,v1[
  27831. // interp index is i2 to progress in range [v0,v2[
  27832. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  27833. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  27834. //
  27835. //
  27836. // i2 v2
  27837. // ^ ^
  27838. // / / \
  27839. // / / \
  27840. // / / \
  27841. // / / (0,1) \
  27842. // / #---------\
  27843. // / / \ (0,0)'/ \
  27844. // / / \ / \
  27845. // / / \ / \
  27846. // / / (0,0) \ / (1,0) \
  27847. // / #---------#---------\
  27848. // v0 v1
  27849. //
  27850. // --------------------> i1
  27851. //
  27852. // interp of (i1,i2):
  27853. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  27854. // along i1 : lerp(x0,x1, i1/(S-i2))
  27855. //
  27856. // centroid of triangle is needed to get help normal computation
  27857. // (c1,c2) are used for centroid location
  27858. var interp_vertex = function (i1, i2, c1, c2) {
  27859. // vertex is interpolated from
  27860. // - face_vertex_pos[0..2]
  27861. // - face_vertex_uv[0..2]
  27862. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  27863. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  27864. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  27865. pos_interp.normalize();
  27866. var vertex_normal;
  27867. if (flat) {
  27868. // in flat mode, recalculate normal as face centroid normal
  27869. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  27870. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  27871. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  27872. }
  27873. else {
  27874. // in smooth mode, recalculate normal from each single vertex position
  27875. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  27876. }
  27877. // Vertex normal need correction due to X,Y,Z radius scaling
  27878. vertex_normal.x /= radiusX;
  27879. vertex_normal.y /= radiusY;
  27880. vertex_normal.z /= radiusZ;
  27881. vertex_normal.normalize();
  27882. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  27883. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  27884. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  27885. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  27886. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  27887. uvs.push(uv_interp.x, uv_interp.y);
  27888. // push each vertex has member of a face
  27889. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  27890. indices.push(current_indice);
  27891. current_indice++;
  27892. };
  27893. for (var i2 = 0; i2 < subdivisions; i2++) {
  27894. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  27895. // face : (i1,i2) for /\ :
  27896. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  27897. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27898. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27899. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27900. if (i1 + i2 + 1 < subdivisions) {
  27901. // face : (i1,i2)' for \/ :
  27902. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  27903. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27904. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27905. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27906. }
  27907. }
  27908. }
  27909. }
  27910. // Sides
  27911. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27912. // Result
  27913. var vertexData = new VertexData();
  27914. vertexData.indices = indices;
  27915. vertexData.positions = positions;
  27916. vertexData.normals = normals;
  27917. vertexData.uvs = uvs;
  27918. return vertexData;
  27919. };
  27920. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  27921. /**
  27922. * Creates the VertexData of the Polyhedron.
  27923. */
  27924. VertexData.CreatePolyhedron = function (options) {
  27925. // provided polyhedron types :
  27926. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  27927. // 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)
  27928. var polyhedra = [];
  27929. 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]] };
  27930. 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]] };
  27931. polyhedra[2] = {
  27932. 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]],
  27933. 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]]
  27934. };
  27935. polyhedra[3] = {
  27936. 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]],
  27937. 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]]
  27938. };
  27939. polyhedra[4] = {
  27940. 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]],
  27941. 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]]
  27942. };
  27943. 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]] };
  27944. 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]] };
  27945. 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]] };
  27946. 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]] };
  27947. 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]] };
  27948. 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]] };
  27949. 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]] };
  27950. 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]] };
  27951. 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]] };
  27952. polyhedra[14] = {
  27953. 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]],
  27954. 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]]
  27955. };
  27956. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  27957. var size = options.size;
  27958. var sizeX = options.sizeX || size || 1;
  27959. var sizeY = options.sizeY || size || 1;
  27960. var sizeZ = options.sizeZ || size || 1;
  27961. var data = options.custom || polyhedra[type];
  27962. var nbfaces = data.face.length;
  27963. var faceUV = options.faceUV || new Array(nbfaces);
  27964. var faceColors = options.faceColors;
  27965. var flat = (options.flat === undefined) ? true : options.flat;
  27966. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27967. var positions = [];
  27968. var indices = [];
  27969. var normals = [];
  27970. var uvs = [];
  27971. var colors = [];
  27972. var index = 0;
  27973. var faceIdx = 0; // face cursor in the array "indexes"
  27974. var indexes = [];
  27975. var i = 0;
  27976. var f = 0;
  27977. var u, v, ang, x, y, tmp;
  27978. // default face colors and UV if undefined
  27979. if (flat) {
  27980. for (f = 0; f < nbfaces; f++) {
  27981. if (faceColors && faceColors[f] === undefined) {
  27982. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27983. }
  27984. if (faceUV && faceUV[f] === undefined) {
  27985. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27986. }
  27987. }
  27988. }
  27989. if (!flat) {
  27990. for (i = 0; i < data.vertex.length; i++) {
  27991. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  27992. uvs.push(0, 0);
  27993. }
  27994. for (f = 0; f < nbfaces; f++) {
  27995. for (i = 0; i < data.face[f].length - 2; i++) {
  27996. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  27997. }
  27998. }
  27999. }
  28000. else {
  28001. for (f = 0; f < nbfaces; f++) {
  28002. var fl = data.face[f].length; // number of vertices of the current face
  28003. ang = 2 * Math.PI / fl;
  28004. x = 0.5 * Math.tan(ang / 2);
  28005. y = 0.5;
  28006. // positions, uvs, colors
  28007. for (i = 0; i < fl; i++) {
  28008. // positions
  28009. 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);
  28010. indexes.push(index);
  28011. index++;
  28012. // uvs
  28013. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  28014. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  28015. uvs.push(u, v);
  28016. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  28017. y = x * Math.sin(ang) + y * Math.cos(ang);
  28018. x = tmp;
  28019. // colors
  28020. if (faceColors) {
  28021. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  28022. }
  28023. }
  28024. // indices from indexes
  28025. for (i = 0; i < fl - 2; i++) {
  28026. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  28027. }
  28028. faceIdx += fl;
  28029. }
  28030. }
  28031. VertexData.ComputeNormals(positions, indices, normals);
  28032. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28033. var vertexData = new VertexData();
  28034. vertexData.positions = positions;
  28035. vertexData.indices = indices;
  28036. vertexData.normals = normals;
  28037. vertexData.uvs = uvs;
  28038. if (faceColors && flat) {
  28039. vertexData.colors = colors;
  28040. }
  28041. return vertexData;
  28042. };
  28043. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  28044. /**
  28045. * Creates the VertexData of the Torus Knot.
  28046. */
  28047. VertexData.CreateTorusKnot = function (options) {
  28048. var indices = [];
  28049. var positions = [];
  28050. var normals = [];
  28051. var uvs = [];
  28052. var radius = options.radius || 2;
  28053. var tube = options.tube || 0.5;
  28054. var radialSegments = options.radialSegments || 32;
  28055. var tubularSegments = options.tubularSegments || 32;
  28056. var p = options.p || 2;
  28057. var q = options.q || 3;
  28058. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28059. // Helper
  28060. var getPos = function (angle) {
  28061. var cu = Math.cos(angle);
  28062. var su = Math.sin(angle);
  28063. var quOverP = q / p * angle;
  28064. var cs = Math.cos(quOverP);
  28065. var tx = radius * (2 + cs) * 0.5 * cu;
  28066. var ty = radius * (2 + cs) * su * 0.5;
  28067. var tz = radius * Math.sin(quOverP) * 0.5;
  28068. return new BABYLON.Vector3(tx, ty, tz);
  28069. };
  28070. // Vertices
  28071. var i;
  28072. var j;
  28073. for (i = 0; i <= radialSegments; i++) {
  28074. var modI = i % radialSegments;
  28075. var u = modI / radialSegments * 2 * p * Math.PI;
  28076. var p1 = getPos(u);
  28077. var p2 = getPos(u + 0.01);
  28078. var tang = p2.subtract(p1);
  28079. var n = p2.add(p1);
  28080. var bitan = BABYLON.Vector3.Cross(tang, n);
  28081. n = BABYLON.Vector3.Cross(bitan, tang);
  28082. bitan.normalize();
  28083. n.normalize();
  28084. for (j = 0; j < tubularSegments; j++) {
  28085. var modJ = j % tubularSegments;
  28086. var v = modJ / tubularSegments * 2 * Math.PI;
  28087. var cx = -tube * Math.cos(v);
  28088. var cy = tube * Math.sin(v);
  28089. positions.push(p1.x + cx * n.x + cy * bitan.x);
  28090. positions.push(p1.y + cx * n.y + cy * bitan.y);
  28091. positions.push(p1.z + cx * n.z + cy * bitan.z);
  28092. uvs.push(i / radialSegments);
  28093. uvs.push(j / tubularSegments);
  28094. }
  28095. }
  28096. for (i = 0; i < radialSegments; i++) {
  28097. for (j = 0; j < tubularSegments; j++) {
  28098. var jNext = (j + 1) % tubularSegments;
  28099. var a = i * tubularSegments + j;
  28100. var b = (i + 1) * tubularSegments + j;
  28101. var c = (i + 1) * tubularSegments + jNext;
  28102. var d = i * tubularSegments + jNext;
  28103. indices.push(d);
  28104. indices.push(b);
  28105. indices.push(a);
  28106. indices.push(d);
  28107. indices.push(c);
  28108. indices.push(b);
  28109. }
  28110. }
  28111. // Normals
  28112. VertexData.ComputeNormals(positions, indices, normals);
  28113. // Sides
  28114. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28115. // Result
  28116. var vertexData = new VertexData();
  28117. vertexData.indices = indices;
  28118. vertexData.positions = positions;
  28119. vertexData.normals = normals;
  28120. vertexData.uvs = uvs;
  28121. return vertexData;
  28122. };
  28123. // Tools
  28124. /**
  28125. * @param {any} - positions (number[] or Float32Array)
  28126. * @param {any} - indices (number[] or Uint16Array)
  28127. * @param {any} - normals (number[] or Float32Array)
  28128. * options (optional) :
  28129. * facetPositions : optional array of facet positions (vector3)
  28130. * facetNormals : optional array of facet normals (vector3)
  28131. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  28132. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  28133. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  28134. * bbSize : optional bounding box size data, required for facetPartitioning computation
  28135. * bInfo : optional bounding info, required for facetPartitioning computation
  28136. */
  28137. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  28138. // temporary scalar variables
  28139. var index = 0; // facet index
  28140. var p1p2x = 0.0; // p1p2 vector x coordinate
  28141. var p1p2y = 0.0; // p1p2 vector y coordinate
  28142. var p1p2z = 0.0; // p1p2 vector z coordinate
  28143. var p3p2x = 0.0; // p3p2 vector x coordinate
  28144. var p3p2y = 0.0; // p3p2 vector y coordinate
  28145. var p3p2z = 0.0; // p3p2 vector z coordinate
  28146. var faceNormalx = 0.0; // facet normal x coordinate
  28147. var faceNormaly = 0.0; // facet normal y coordinate
  28148. var faceNormalz = 0.0; // facet normal z coordinate
  28149. var length = 0.0; // facet normal length before normalization
  28150. var v1x = 0; // vector1 x index in the positions array
  28151. var v1y = 0; // vector1 y index in the positions array
  28152. var v1z = 0; // vector1 z index in the positions array
  28153. var v2x = 0; // vector2 x index in the positions array
  28154. var v2y = 0; // vector2 y index in the positions array
  28155. var v2z = 0; // vector2 z index in the positions array
  28156. var v3x = 0; // vector3 x index in the positions array
  28157. var v3y = 0; // vector3 y index in the positions array
  28158. var v3z = 0; // vector3 z index in the positions array
  28159. var computeFacetNormals = false;
  28160. var computeFacetPositions = false;
  28161. var computeFacetPartitioning = false;
  28162. var faceNormalSign = 1;
  28163. if (options) {
  28164. computeFacetNormals = (options.facetNormals) ? true : false;
  28165. computeFacetPositions = (options.facetPositions) ? true : false;
  28166. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  28167. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  28168. }
  28169. // facetPartitioning reinit if needed
  28170. if (computeFacetPartitioning) {
  28171. var ox = 0; // X partitioning index for facet position
  28172. var oy = 0; // Y partinioning index for facet position
  28173. var oz = 0; // Z partinioning index for facet position
  28174. var b1x = 0; // X partitioning index for facet v1 vertex
  28175. var b1y = 0; // Y partitioning index for facet v1 vertex
  28176. var b1z = 0; // z partitioning index for facet v1 vertex
  28177. var b2x = 0; // X partitioning index for facet v2 vertex
  28178. var b2y = 0; // Y partitioning index for facet v2 vertex
  28179. var b2z = 0; // Z partitioning index for facet v2 vertex
  28180. var b3x = 0; // X partitioning index for facet v3 vertex
  28181. var b3y = 0; // Y partitioning index for facet v3 vertex
  28182. var b3z = 0; // Z partitioning index for facet v3 vertex
  28183. var block_idx_o = 0; // facet barycenter block index
  28184. var block_idx_v1 = 0; // v1 vertex block index
  28185. var block_idx_v2 = 0; // v2 vertex block index
  28186. var block_idx_v3 = 0; // v3 vertex block index
  28187. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  28188. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  28189. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  28190. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  28191. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  28192. var subSq = options.subDiv.max * options.subDiv.max;
  28193. options.facetPartitioning.length = 0;
  28194. }
  28195. // reset the normals
  28196. for (index = 0; index < positions.length; index++) {
  28197. normals[index] = 0.0;
  28198. }
  28199. // Loop : 1 indice triplet = 1 facet
  28200. var nbFaces = indices.length / 3;
  28201. for (index = 0; index < nbFaces; index++) {
  28202. // get the indexes of the coordinates of each vertex of the facet
  28203. v1x = indices[index * 3] * 3;
  28204. v1y = v1x + 1;
  28205. v1z = v1x + 2;
  28206. v2x = indices[index * 3 + 1] * 3;
  28207. v2y = v2x + 1;
  28208. v2z = v2x + 2;
  28209. v3x = indices[index * 3 + 2] * 3;
  28210. v3y = v3x + 1;
  28211. v3z = v3x + 2;
  28212. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  28213. p1p2y = positions[v1y] - positions[v2y];
  28214. p1p2z = positions[v1z] - positions[v2z];
  28215. p3p2x = positions[v3x] - positions[v2x];
  28216. p3p2y = positions[v3y] - positions[v2y];
  28217. p3p2z = positions[v3z] - positions[v2z];
  28218. // compute the face normal with the cross product
  28219. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  28220. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  28221. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  28222. // normalize this normal and store it in the array facetData
  28223. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  28224. length = (length === 0) ? 1.0 : length;
  28225. faceNormalx /= length;
  28226. faceNormaly /= length;
  28227. faceNormalz /= length;
  28228. if (computeFacetNormals) {
  28229. options.facetNormals[index].x = faceNormalx;
  28230. options.facetNormals[index].y = faceNormaly;
  28231. options.facetNormals[index].z = faceNormalz;
  28232. }
  28233. if (computeFacetPositions) {
  28234. // compute and the facet barycenter coordinates in the array facetPositions
  28235. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  28236. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  28237. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  28238. }
  28239. if (computeFacetPartitioning) {
  28240. // store the facet indexes in arrays in the main facetPartitioning array :
  28241. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  28242. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28243. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28244. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28245. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28246. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28247. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28248. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28249. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28250. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28251. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28252. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28253. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28254. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  28255. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  28256. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  28257. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  28258. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  28259. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  28260. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  28261. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  28262. // push each facet index in each block containing the vertex
  28263. options.facetPartitioning[block_idx_v1].push(index);
  28264. if (block_idx_v2 != block_idx_v1) {
  28265. options.facetPartitioning[block_idx_v2].push(index);
  28266. }
  28267. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  28268. options.facetPartitioning[block_idx_v3].push(index);
  28269. }
  28270. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  28271. options.facetPartitioning[block_idx_o].push(index);
  28272. }
  28273. }
  28274. // compute the normals anyway
  28275. normals[v1x] += faceNormalx; // accumulate all the normals per face
  28276. normals[v1y] += faceNormaly;
  28277. normals[v1z] += faceNormalz;
  28278. normals[v2x] += faceNormalx;
  28279. normals[v2y] += faceNormaly;
  28280. normals[v2z] += faceNormalz;
  28281. normals[v3x] += faceNormalx;
  28282. normals[v3y] += faceNormaly;
  28283. normals[v3z] += faceNormalz;
  28284. }
  28285. // last normalization of each normal
  28286. for (index = 0; index < normals.length / 3; index++) {
  28287. faceNormalx = normals[index * 3];
  28288. faceNormaly = normals[index * 3 + 1];
  28289. faceNormalz = normals[index * 3 + 2];
  28290. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  28291. length = (length === 0) ? 1.0 : length;
  28292. faceNormalx /= length;
  28293. faceNormaly /= length;
  28294. faceNormalz /= length;
  28295. normals[index * 3] = faceNormalx;
  28296. normals[index * 3 + 1] = faceNormaly;
  28297. normals[index * 3 + 2] = faceNormalz;
  28298. }
  28299. };
  28300. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  28301. var li = indices.length;
  28302. var ln = normals.length;
  28303. var i;
  28304. var n;
  28305. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28306. switch (sideOrientation) {
  28307. case BABYLON.Mesh.FRONTSIDE:
  28308. // nothing changed
  28309. break;
  28310. case BABYLON.Mesh.BACKSIDE:
  28311. var tmp;
  28312. // indices
  28313. for (i = 0; i < li; i += 3) {
  28314. tmp = indices[i];
  28315. indices[i] = indices[i + 2];
  28316. indices[i + 2] = tmp;
  28317. }
  28318. // normals
  28319. for (n = 0; n < ln; n++) {
  28320. normals[n] = -normals[n];
  28321. }
  28322. break;
  28323. case BABYLON.Mesh.DOUBLESIDE:
  28324. // positions
  28325. var lp = positions.length;
  28326. var l = lp / 3;
  28327. for (var p = 0; p < lp; p++) {
  28328. positions[lp + p] = positions[p];
  28329. }
  28330. // indices
  28331. for (i = 0; i < li; i += 3) {
  28332. indices[i + li] = indices[i + 2] + l;
  28333. indices[i + 1 + li] = indices[i + 1] + l;
  28334. indices[i + 2 + li] = indices[i] + l;
  28335. }
  28336. // normals
  28337. for (n = 0; n < ln; n++) {
  28338. normals[ln + n] = -normals[n];
  28339. }
  28340. // uvs
  28341. var lu = uvs.length;
  28342. var u = 0;
  28343. for (u = 0; u < lu; u++) {
  28344. uvs[u + lu] = uvs[u];
  28345. }
  28346. var frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  28347. var backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  28348. u = 0;
  28349. for (i = 0; i < lu / 2; i++) {
  28350. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  28351. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  28352. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  28353. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  28354. u += 2;
  28355. }
  28356. break;
  28357. }
  28358. };
  28359. /**
  28360. * Creates a new VertexData from the imported parameters.
  28361. */
  28362. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  28363. var vertexData = new VertexData();
  28364. // positions
  28365. var positions = parsedVertexData.positions;
  28366. if (positions) {
  28367. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  28368. }
  28369. // normals
  28370. var normals = parsedVertexData.normals;
  28371. if (normals) {
  28372. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  28373. }
  28374. // tangents
  28375. var tangents = parsedVertexData.tangents;
  28376. if (tangents) {
  28377. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  28378. }
  28379. // uvs
  28380. var uvs = parsedVertexData.uvs;
  28381. if (uvs) {
  28382. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  28383. }
  28384. // uv2s
  28385. var uv2s = parsedVertexData.uv2s;
  28386. if (uv2s) {
  28387. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  28388. }
  28389. // uv3s
  28390. var uv3s = parsedVertexData.uv3s;
  28391. if (uv3s) {
  28392. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  28393. }
  28394. // uv4s
  28395. var uv4s = parsedVertexData.uv4s;
  28396. if (uv4s) {
  28397. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  28398. }
  28399. // uv5s
  28400. var uv5s = parsedVertexData.uv5s;
  28401. if (uv5s) {
  28402. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  28403. }
  28404. // uv6s
  28405. var uv6s = parsedVertexData.uv6s;
  28406. if (uv6s) {
  28407. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  28408. }
  28409. // colors
  28410. var colors = parsedVertexData.colors;
  28411. if (colors) {
  28412. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  28413. }
  28414. // matricesIndices
  28415. var matricesIndices = parsedVertexData.matricesIndices;
  28416. if (matricesIndices) {
  28417. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  28418. }
  28419. // matricesWeights
  28420. var matricesWeights = parsedVertexData.matricesWeights;
  28421. if (matricesWeights) {
  28422. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  28423. }
  28424. // indices
  28425. var indices = parsedVertexData.indices;
  28426. if (indices) {
  28427. vertexData.indices = indices;
  28428. }
  28429. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  28430. };
  28431. return VertexData;
  28432. }());
  28433. BABYLON.VertexData = VertexData;
  28434. })(BABYLON || (BABYLON = {}));
  28435. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  28436. var BABYLON;
  28437. (function (BABYLON) {
  28438. var Geometry = (function () {
  28439. function Geometry(id, scene, vertexData, updatable, mesh) {
  28440. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28441. this._totalVertices = 0;
  28442. this._isDisposed = false;
  28443. this.id = id;
  28444. this._engine = scene.getEngine();
  28445. this._meshes = [];
  28446. this._scene = scene;
  28447. //Init vertex buffer cache
  28448. this._vertexBuffers = {};
  28449. this._indices = [];
  28450. this._updatable = updatable;
  28451. // vertexData
  28452. if (vertexData) {
  28453. this.setAllVerticesData(vertexData, updatable);
  28454. }
  28455. else {
  28456. this._totalVertices = 0;
  28457. this._indices = [];
  28458. }
  28459. if (this._engine.getCaps().vertexArrayObject) {
  28460. this._vertexArrayObjects = {};
  28461. }
  28462. // applyToMesh
  28463. if (mesh) {
  28464. if (mesh.getClassName() === "LinesMesh") {
  28465. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  28466. this.updateExtend();
  28467. }
  28468. this.applyToMesh(mesh);
  28469. mesh.computeWorldMatrix(true);
  28470. }
  28471. }
  28472. Object.defineProperty(Geometry.prototype, "boundingBias", {
  28473. /**
  28474. * 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
  28475. * @returns The Bias Vector
  28476. */
  28477. get: function () {
  28478. return this._boundingBias;
  28479. },
  28480. set: function (value) {
  28481. if (this._boundingBias && this._boundingBias.equals(value)) {
  28482. return;
  28483. }
  28484. this._boundingBias = value.clone();
  28485. this.updateBoundingInfo(true, null);
  28486. },
  28487. enumerable: true,
  28488. configurable: true
  28489. });
  28490. Object.defineProperty(Geometry.prototype, "extend", {
  28491. get: function () {
  28492. return this._extend;
  28493. },
  28494. enumerable: true,
  28495. configurable: true
  28496. });
  28497. Geometry.prototype.getScene = function () {
  28498. return this._scene;
  28499. };
  28500. Geometry.prototype.getEngine = function () {
  28501. return this._engine;
  28502. };
  28503. Geometry.prototype.isReady = function () {
  28504. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  28505. };
  28506. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  28507. get: function () {
  28508. for (var index = 0; index < this._meshes.length; index++) {
  28509. if (!this._meshes[index].doNotSerialize) {
  28510. return false;
  28511. }
  28512. }
  28513. return true;
  28514. },
  28515. enumerable: true,
  28516. configurable: true
  28517. });
  28518. Geometry.prototype._rebuild = function () {
  28519. if (this._vertexArrayObjects) {
  28520. this._vertexArrayObjects = {};
  28521. }
  28522. // Index buffer
  28523. if (this._meshes.length !== 0 && this._indices) {
  28524. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28525. }
  28526. // Vertex buffers
  28527. for (var key in this._vertexBuffers) {
  28528. var vertexBuffer = this._vertexBuffers[key];
  28529. vertexBuffer._rebuild();
  28530. }
  28531. };
  28532. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  28533. vertexData.applyToGeometry(this, updatable);
  28534. this.notifyUpdate();
  28535. };
  28536. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28537. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  28538. this.setVerticesBuffer(buffer);
  28539. };
  28540. Geometry.prototype.removeVerticesData = function (kind) {
  28541. if (this._vertexBuffers[kind]) {
  28542. this._vertexBuffers[kind].dispose();
  28543. delete this._vertexBuffers[kind];
  28544. }
  28545. };
  28546. Geometry.prototype.setVerticesBuffer = function (buffer) {
  28547. var kind = buffer.getKind();
  28548. if (this._vertexBuffers[kind]) {
  28549. this._vertexBuffers[kind].dispose();
  28550. }
  28551. this._vertexBuffers[kind] = buffer;
  28552. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28553. var data = buffer.getData();
  28554. var stride = buffer.getStrideSize();
  28555. this._totalVertices = data.length / stride;
  28556. this.updateExtend(data, stride);
  28557. this._resetPointsArrayCache();
  28558. var meshes = this._meshes;
  28559. var numOfMeshes = meshes.length;
  28560. for (var index = 0; index < numOfMeshes; index++) {
  28561. var mesh = meshes[index];
  28562. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28563. mesh._createGlobalSubMesh(false);
  28564. mesh.computeWorldMatrix(true);
  28565. }
  28566. }
  28567. this.notifyUpdate(kind);
  28568. if (this._vertexArrayObjects) {
  28569. this._disposeVertexArrayObjects();
  28570. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  28571. }
  28572. };
  28573. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  28574. var vertexBuffer = this.getVertexBuffer(kind);
  28575. if (!vertexBuffer) {
  28576. return;
  28577. }
  28578. vertexBuffer.updateDirectly(data, offset);
  28579. this.notifyUpdate(kind);
  28580. };
  28581. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  28582. var vertexBuffer = this.getVertexBuffer(kind);
  28583. if (!vertexBuffer) {
  28584. return;
  28585. }
  28586. vertexBuffer.update(data);
  28587. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28588. var stride = vertexBuffer.getStrideSize();
  28589. this._totalVertices = data.length / stride;
  28590. this.updateBoundingInfo(updateExtends, data);
  28591. }
  28592. this.notifyUpdate(kind);
  28593. };
  28594. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  28595. if (updateExtends) {
  28596. this.updateExtend(data);
  28597. }
  28598. var meshes = this._meshes;
  28599. var numOfMeshes = meshes.length;
  28600. this._resetPointsArrayCache();
  28601. for (var index = 0; index < numOfMeshes; index++) {
  28602. var mesh = meshes[index];
  28603. if (updateExtends) {
  28604. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28605. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  28606. var subMesh = mesh.subMeshes[subIndex];
  28607. subMesh.refreshBoundingInfo();
  28608. }
  28609. }
  28610. }
  28611. };
  28612. Geometry.prototype._bind = function (effect, indexToBind) {
  28613. if (indexToBind === void 0) { indexToBind = undefined; }
  28614. if (indexToBind === undefined) {
  28615. indexToBind = this._indexBuffer;
  28616. }
  28617. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  28618. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  28619. return;
  28620. }
  28621. // Using VAO
  28622. if (!this._vertexArrayObjects[effect.key]) {
  28623. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  28624. }
  28625. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  28626. };
  28627. Geometry.prototype.getTotalVertices = function () {
  28628. if (!this.isReady()) {
  28629. return 0;
  28630. }
  28631. return this._totalVertices;
  28632. };
  28633. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  28634. var vertexBuffer = this.getVertexBuffer(kind);
  28635. if (!vertexBuffer) {
  28636. return null;
  28637. }
  28638. var orig = vertexBuffer.getData();
  28639. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  28640. return orig;
  28641. }
  28642. else {
  28643. var len = orig.length;
  28644. var copy = [];
  28645. for (var i = 0; i < len; i++) {
  28646. copy.push(orig[i]);
  28647. }
  28648. return copy;
  28649. }
  28650. };
  28651. Geometry.prototype.getVertexBuffer = function (kind) {
  28652. if (!this.isReady()) {
  28653. return null;
  28654. }
  28655. return this._vertexBuffers[kind];
  28656. };
  28657. Geometry.prototype.getVertexBuffers = function () {
  28658. if (!this.isReady()) {
  28659. return null;
  28660. }
  28661. return this._vertexBuffers;
  28662. };
  28663. Geometry.prototype.isVerticesDataPresent = function (kind) {
  28664. if (!this._vertexBuffers) {
  28665. if (this._delayInfo) {
  28666. return this._delayInfo.indexOf(kind) !== -1;
  28667. }
  28668. return false;
  28669. }
  28670. return this._vertexBuffers[kind] !== undefined;
  28671. };
  28672. Geometry.prototype.getVerticesDataKinds = function () {
  28673. var result = [];
  28674. var kind;
  28675. if (!this._vertexBuffers && this._delayInfo) {
  28676. for (kind in this._delayInfo) {
  28677. result.push(kind);
  28678. }
  28679. }
  28680. else {
  28681. for (kind in this._vertexBuffers) {
  28682. result.push(kind);
  28683. }
  28684. }
  28685. return result;
  28686. };
  28687. Geometry.prototype.setIndices = function (indices, totalVertices) {
  28688. if (this._indexBuffer) {
  28689. this._engine._releaseBuffer(this._indexBuffer);
  28690. }
  28691. this._disposeVertexArrayObjects();
  28692. this._indices = indices;
  28693. if (this._meshes.length !== 0 && this._indices) {
  28694. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28695. }
  28696. if (totalVertices !== undefined) {
  28697. this._totalVertices = totalVertices;
  28698. }
  28699. var meshes = this._meshes;
  28700. var numOfMeshes = meshes.length;
  28701. for (var index = 0; index < numOfMeshes; index++) {
  28702. meshes[index]._createGlobalSubMesh(true);
  28703. }
  28704. this.notifyUpdate();
  28705. };
  28706. Geometry.prototype.getTotalIndices = function () {
  28707. if (!this.isReady()) {
  28708. return 0;
  28709. }
  28710. return this._indices.length;
  28711. };
  28712. Geometry.prototype.getIndices = function (copyWhenShared) {
  28713. if (!this.isReady()) {
  28714. return null;
  28715. }
  28716. var orig = this._indices;
  28717. if (!copyWhenShared || this._meshes.length === 1) {
  28718. return orig;
  28719. }
  28720. else {
  28721. var len = orig.length;
  28722. var copy = [];
  28723. for (var i = 0; i < len; i++) {
  28724. copy.push(orig[i]);
  28725. }
  28726. return copy;
  28727. }
  28728. };
  28729. Geometry.prototype.getIndexBuffer = function () {
  28730. if (!this.isReady()) {
  28731. return null;
  28732. }
  28733. return this._indexBuffer;
  28734. };
  28735. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  28736. if (!effect || !this._vertexArrayObjects) {
  28737. return;
  28738. }
  28739. if (this._vertexArrayObjects[effect.key]) {
  28740. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  28741. delete this._vertexArrayObjects[effect.key];
  28742. }
  28743. };
  28744. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  28745. var meshes = this._meshes;
  28746. var index = meshes.indexOf(mesh);
  28747. if (index === -1) {
  28748. return;
  28749. }
  28750. meshes.splice(index, 1);
  28751. mesh._geometry = null;
  28752. if (meshes.length === 0 && shouldDispose) {
  28753. this.dispose();
  28754. }
  28755. };
  28756. Geometry.prototype.applyToMesh = function (mesh) {
  28757. if (mesh._geometry === this) {
  28758. return;
  28759. }
  28760. var previousGeometry = mesh._geometry;
  28761. if (previousGeometry) {
  28762. previousGeometry.releaseForMesh(mesh);
  28763. }
  28764. var meshes = this._meshes;
  28765. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  28766. mesh._geometry = this;
  28767. this._scene.pushGeometry(this);
  28768. meshes.push(mesh);
  28769. if (this.isReady()) {
  28770. this._applyToMesh(mesh);
  28771. }
  28772. else {
  28773. mesh._boundingInfo = this._boundingInfo;
  28774. }
  28775. };
  28776. Geometry.prototype.updateExtend = function (data, stride) {
  28777. if (data === void 0) { data = null; }
  28778. if (!data) {
  28779. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  28780. }
  28781. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  28782. };
  28783. Geometry.prototype._applyToMesh = function (mesh) {
  28784. var numOfMeshes = this._meshes.length;
  28785. // vertexBuffers
  28786. for (var kind in this._vertexBuffers) {
  28787. if (numOfMeshes === 1) {
  28788. this._vertexBuffers[kind].create();
  28789. }
  28790. var buffer = this._vertexBuffers[kind].getBuffer();
  28791. if (buffer)
  28792. buffer.references = numOfMeshes;
  28793. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28794. if (!this._extend) {
  28795. this.updateExtend(this._vertexBuffers[kind].getData());
  28796. }
  28797. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28798. mesh._createGlobalSubMesh(false);
  28799. //bounding info was just created again, world matrix should be applied again.
  28800. mesh._updateBoundingInfo();
  28801. }
  28802. }
  28803. // indexBuffer
  28804. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  28805. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28806. }
  28807. if (this._indexBuffer) {
  28808. this._indexBuffer.references = numOfMeshes;
  28809. }
  28810. };
  28811. Geometry.prototype.notifyUpdate = function (kind) {
  28812. if (this.onGeometryUpdated) {
  28813. this.onGeometryUpdated(this, kind);
  28814. }
  28815. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  28816. var mesh = _a[_i];
  28817. mesh._markSubMeshesAsAttributesDirty();
  28818. }
  28819. };
  28820. Geometry.prototype.load = function (scene, onLoaded) {
  28821. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28822. return;
  28823. }
  28824. if (this.isReady()) {
  28825. if (onLoaded) {
  28826. onLoaded();
  28827. }
  28828. return;
  28829. }
  28830. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28831. this._queueLoad(scene, onLoaded);
  28832. };
  28833. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  28834. var _this = this;
  28835. scene._addPendingData(this);
  28836. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28837. _this._delayLoadingFunction(JSON.parse(data), _this);
  28838. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28839. _this._delayInfo = [];
  28840. scene._removePendingData(_this);
  28841. var meshes = _this._meshes;
  28842. var numOfMeshes = meshes.length;
  28843. for (var index = 0; index < numOfMeshes; index++) {
  28844. _this._applyToMesh(meshes[index]);
  28845. }
  28846. if (onLoaded) {
  28847. onLoaded();
  28848. }
  28849. }, function () { }, scene.database);
  28850. };
  28851. /**
  28852. * Invert the geometry to move from a right handed system to a left handed one.
  28853. */
  28854. Geometry.prototype.toLeftHanded = function () {
  28855. // Flip faces
  28856. var tIndices = this.getIndices(false);
  28857. if (tIndices != null && tIndices.length > 0) {
  28858. for (var i = 0; i < tIndices.length; i += 3) {
  28859. var tTemp = tIndices[i + 0];
  28860. tIndices[i + 0] = tIndices[i + 2];
  28861. tIndices[i + 2] = tTemp;
  28862. }
  28863. this.setIndices(tIndices);
  28864. }
  28865. // Negate position.z
  28866. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  28867. if (tPositions != null && tPositions.length > 0) {
  28868. for (var i = 0; i < tPositions.length; i += 3) {
  28869. tPositions[i + 2] = -tPositions[i + 2];
  28870. }
  28871. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  28872. }
  28873. // Negate normal.z
  28874. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  28875. if (tNormals != null && tNormals.length > 0) {
  28876. for (var i = 0; i < tNormals.length; i += 3) {
  28877. tNormals[i + 2] = -tNormals[i + 2];
  28878. }
  28879. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  28880. }
  28881. };
  28882. // Cache
  28883. Geometry.prototype._resetPointsArrayCache = function () {
  28884. this._positions = null;
  28885. };
  28886. Geometry.prototype._generatePointsArray = function () {
  28887. if (this._positions)
  28888. return true;
  28889. this._positions = [];
  28890. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28891. if (!data) {
  28892. return false;
  28893. }
  28894. for (var index = 0; index < data.length; index += 3) {
  28895. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  28896. }
  28897. return true;
  28898. };
  28899. Geometry.prototype.isDisposed = function () {
  28900. return this._isDisposed;
  28901. };
  28902. Geometry.prototype._disposeVertexArrayObjects = function () {
  28903. if (this._vertexArrayObjects) {
  28904. for (var kind in this._vertexArrayObjects) {
  28905. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  28906. }
  28907. this._vertexArrayObjects = {};
  28908. }
  28909. };
  28910. Geometry.prototype.dispose = function () {
  28911. var meshes = this._meshes;
  28912. var numOfMeshes = meshes.length;
  28913. var index;
  28914. for (index = 0; index < numOfMeshes; index++) {
  28915. this.releaseForMesh(meshes[index]);
  28916. }
  28917. this._meshes = [];
  28918. this._disposeVertexArrayObjects();
  28919. for (var kind in this._vertexBuffers) {
  28920. this._vertexBuffers[kind].dispose();
  28921. }
  28922. this._vertexBuffers = {};
  28923. this._totalVertices = 0;
  28924. if (this._indexBuffer) {
  28925. this._engine._releaseBuffer(this._indexBuffer);
  28926. }
  28927. this._indexBuffer = null;
  28928. this._indices = [];
  28929. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28930. this.delayLoadingFile = null;
  28931. this._delayLoadingFunction = null;
  28932. this._delayInfo = [];
  28933. this._boundingInfo = null;
  28934. this._scene.removeGeometry(this);
  28935. this._isDisposed = true;
  28936. };
  28937. Geometry.prototype.copy = function (id) {
  28938. var vertexData = new BABYLON.VertexData();
  28939. vertexData.indices = [];
  28940. var indices = this.getIndices();
  28941. for (var index = 0; index < indices.length; index++) {
  28942. vertexData.indices.push(indices[index]);
  28943. }
  28944. var updatable = false;
  28945. var stopChecking = false;
  28946. var kind;
  28947. for (kind in this._vertexBuffers) {
  28948. // using slice() to make a copy of the array and not just reference it
  28949. var data = this.getVerticesData(kind);
  28950. if (data instanceof Float32Array) {
  28951. vertexData.set(new Float32Array(data), kind);
  28952. }
  28953. else {
  28954. vertexData.set(data.slice(0), kind);
  28955. }
  28956. if (!stopChecking) {
  28957. updatable = this.getVertexBuffer(kind).isUpdatable();
  28958. stopChecking = !updatable;
  28959. }
  28960. }
  28961. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  28962. geometry.delayLoadState = this.delayLoadState;
  28963. geometry.delayLoadingFile = this.delayLoadingFile;
  28964. geometry._delayLoadingFunction = this._delayLoadingFunction;
  28965. for (kind in this._delayInfo) {
  28966. geometry._delayInfo = geometry._delayInfo || [];
  28967. geometry._delayInfo.push(kind);
  28968. }
  28969. // Bounding info
  28970. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28971. return geometry;
  28972. };
  28973. Geometry.prototype.serialize = function () {
  28974. var serializationObject = {};
  28975. serializationObject.id = this.id;
  28976. serializationObject.updatable = this._updatable;
  28977. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  28978. serializationObject.tags = BABYLON.Tags.GetTags(this);
  28979. }
  28980. return serializationObject;
  28981. };
  28982. Geometry.prototype.toNumberArray = function (origin) {
  28983. if (Array.isArray(origin)) {
  28984. return origin;
  28985. }
  28986. else {
  28987. return Array.prototype.slice.call(origin);
  28988. }
  28989. };
  28990. Geometry.prototype.serializeVerticeData = function () {
  28991. var serializationObject = this.serialize();
  28992. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28993. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  28994. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  28995. serializationObject.positions._updatable = true;
  28996. }
  28997. }
  28998. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28999. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  29000. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  29001. serializationObject.normals._updatable = true;
  29002. }
  29003. }
  29004. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29005. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  29006. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  29007. serializationObject.uvs._updatable = true;
  29008. }
  29009. }
  29010. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29011. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  29012. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  29013. serializationObject.uv2s._updatable = true;
  29014. }
  29015. }
  29016. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29017. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  29018. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  29019. serializationObject.uv3s._updatable = true;
  29020. }
  29021. }
  29022. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29023. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  29024. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  29025. serializationObject.uv4s._updatable = true;
  29026. }
  29027. }
  29028. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29029. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  29030. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  29031. serializationObject.uv5s._updatable = true;
  29032. }
  29033. }
  29034. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29035. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  29036. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  29037. serializationObject.uv6s._updatable = true;
  29038. }
  29039. }
  29040. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29041. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  29042. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  29043. serializationObject.colors._updatable = true;
  29044. }
  29045. }
  29046. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29047. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  29048. serializationObject.matricesIndices._isExpanded = true;
  29049. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  29050. serializationObject.matricesIndices._updatable = true;
  29051. }
  29052. }
  29053. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29054. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  29055. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  29056. serializationObject.matricesWeights._updatable = true;
  29057. }
  29058. }
  29059. serializationObject.indices = this.toNumberArray(this.getIndices());
  29060. return serializationObject;
  29061. };
  29062. // Statics
  29063. Geometry.ExtractFromMesh = function (mesh, id) {
  29064. var geometry = mesh._geometry;
  29065. if (!geometry) {
  29066. return null;
  29067. }
  29068. return geometry.copy(id);
  29069. };
  29070. /**
  29071. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  29072. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  29073. * Be aware Math.random() could cause collisions, but:
  29074. * "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"
  29075. */
  29076. Geometry.RandomId = function () {
  29077. return BABYLON.Tools.RandomId();
  29078. };
  29079. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  29080. var scene = mesh.getScene();
  29081. // Geometry
  29082. var geometryId = parsedGeometry.geometryId;
  29083. if (geometryId) {
  29084. var geometry = scene.getGeometryByID(geometryId);
  29085. if (geometry) {
  29086. geometry.applyToMesh(mesh);
  29087. }
  29088. }
  29089. else if (parsedGeometry instanceof ArrayBuffer) {
  29090. var binaryInfo = mesh._binaryInfo;
  29091. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  29092. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  29093. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  29094. }
  29095. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  29096. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  29097. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  29098. }
  29099. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  29100. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  29101. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  29102. }
  29103. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  29104. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  29105. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  29106. }
  29107. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  29108. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  29109. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  29110. }
  29111. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  29112. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  29113. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  29114. }
  29115. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  29116. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  29117. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  29118. }
  29119. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  29120. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  29121. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  29122. }
  29123. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  29124. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  29125. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  29126. }
  29127. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  29128. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  29129. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  29130. }
  29131. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  29132. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  29133. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  29134. }
  29135. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  29136. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  29137. mesh.setIndices(indicesData);
  29138. }
  29139. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  29140. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  29141. mesh.subMeshes = [];
  29142. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  29143. var materialIndex = subMeshesData[(i * 5) + 0];
  29144. var verticesStart = subMeshesData[(i * 5) + 1];
  29145. var verticesCount = subMeshesData[(i * 5) + 2];
  29146. var indexStart = subMeshesData[(i * 5) + 3];
  29147. var indexCount = subMeshesData[(i * 5) + 4];
  29148. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  29149. }
  29150. }
  29151. }
  29152. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  29153. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  29154. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  29155. if (parsedGeometry.uvs) {
  29156. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  29157. }
  29158. if (parsedGeometry.uvs2) {
  29159. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  29160. }
  29161. if (parsedGeometry.uvs3) {
  29162. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  29163. }
  29164. if (parsedGeometry.uvs4) {
  29165. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  29166. }
  29167. if (parsedGeometry.uvs5) {
  29168. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  29169. }
  29170. if (parsedGeometry.uvs6) {
  29171. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  29172. }
  29173. if (parsedGeometry.colors) {
  29174. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  29175. }
  29176. if (parsedGeometry.matricesIndices) {
  29177. if (!parsedGeometry.matricesIndices._isExpanded) {
  29178. var floatIndices = [];
  29179. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  29180. var matricesIndex = parsedGeometry.matricesIndices[i];
  29181. floatIndices.push(matricesIndex & 0x000000FF);
  29182. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  29183. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  29184. floatIndices.push(matricesIndex >> 24);
  29185. }
  29186. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  29187. }
  29188. else {
  29189. delete parsedGeometry.matricesIndices._isExpanded;
  29190. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  29191. }
  29192. }
  29193. if (parsedGeometry.matricesIndicesExtra) {
  29194. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  29195. var floatIndices = [];
  29196. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  29197. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  29198. floatIndices.push(matricesIndex & 0x000000FF);
  29199. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  29200. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  29201. floatIndices.push(matricesIndex >> 24);
  29202. }
  29203. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  29204. }
  29205. else {
  29206. delete parsedGeometry.matricesIndices._isExpanded;
  29207. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  29208. }
  29209. }
  29210. if (parsedGeometry.matricesWeights) {
  29211. Geometry._CleanMatricesWeights(parsedGeometry.matricesWeights, parsedGeometry.numBoneInfluencers);
  29212. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  29213. }
  29214. if (parsedGeometry.matricesWeightsExtra) {
  29215. Geometry._CleanMatricesWeights(parsedGeometry.matricesWeightsExtra, parsedGeometry.numBoneInfluencers);
  29216. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  29217. }
  29218. mesh.setIndices(parsedGeometry.indices);
  29219. }
  29220. // SubMeshes
  29221. if (parsedGeometry.subMeshes) {
  29222. mesh.subMeshes = [];
  29223. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  29224. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  29225. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  29226. }
  29227. }
  29228. // Flat shading
  29229. if (mesh._shouldGenerateFlatShading) {
  29230. mesh.convertToFlatShadedMesh();
  29231. delete mesh._shouldGenerateFlatShading;
  29232. }
  29233. // Update
  29234. mesh.computeWorldMatrix(true);
  29235. // Octree
  29236. if (scene['_selectionOctree']) {
  29237. scene['_selectionOctree'].addMesh(mesh);
  29238. }
  29239. };
  29240. Geometry._CleanMatricesWeights = function (matricesWeights, influencers) {
  29241. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  29242. return;
  29243. }
  29244. var size = matricesWeights.length;
  29245. for (var i = 0; i < size; i += influencers) {
  29246. var weight = 0;
  29247. var biggerIndex = i;
  29248. var biggerWeight = 0;
  29249. for (var j = 0; j < influencers - 1; j++) {
  29250. weight += matricesWeights[i + j];
  29251. if (matricesWeights[i + j] > biggerWeight) {
  29252. biggerWeight = matricesWeights[i + j];
  29253. biggerIndex = i + j;
  29254. }
  29255. }
  29256. matricesWeights[biggerIndex] += Math.max(0, 1.0 - weight);
  29257. }
  29258. };
  29259. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  29260. if (scene.getGeometryByID(parsedVertexData.id)) {
  29261. return null; // null since geometry could be something else than a box...
  29262. }
  29263. var geometry = new Geometry(parsedVertexData.id, scene, null, parsedVertexData.updatable);
  29264. if (BABYLON.Tags) {
  29265. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  29266. }
  29267. if (parsedVertexData.delayLoadingFile) {
  29268. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29269. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  29270. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  29271. geometry._delayInfo = [];
  29272. if (parsedVertexData.hasUVs) {
  29273. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29274. }
  29275. if (parsedVertexData.hasUVs2) {
  29276. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29277. }
  29278. if (parsedVertexData.hasUVs3) {
  29279. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29280. }
  29281. if (parsedVertexData.hasUVs4) {
  29282. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29283. }
  29284. if (parsedVertexData.hasUVs5) {
  29285. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29286. }
  29287. if (parsedVertexData.hasUVs6) {
  29288. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29289. }
  29290. if (parsedVertexData.hasColors) {
  29291. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29292. }
  29293. if (parsedVertexData.hasMatricesIndices) {
  29294. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29295. }
  29296. if (parsedVertexData.hasMatricesWeights) {
  29297. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29298. }
  29299. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  29300. }
  29301. else {
  29302. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  29303. }
  29304. scene.pushGeometry(geometry, true);
  29305. return geometry;
  29306. };
  29307. return Geometry;
  29308. }());
  29309. BABYLON.Geometry = Geometry;
  29310. /////// Primitives //////////////////////////////////////////////
  29311. (function (Geometry) {
  29312. var Primitives;
  29313. (function (Primitives) {
  29314. /// Abstract class
  29315. var _Primitive = (function (_super) {
  29316. __extends(_Primitive, _super);
  29317. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  29318. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  29319. _this._canBeRegenerated = _canBeRegenerated;
  29320. _this._beingRegenerated = true;
  29321. _this.regenerate();
  29322. _this._beingRegenerated = false;
  29323. return _this;
  29324. }
  29325. _Primitive.prototype.canBeRegenerated = function () {
  29326. return this._canBeRegenerated;
  29327. };
  29328. _Primitive.prototype.regenerate = function () {
  29329. if (!this._canBeRegenerated) {
  29330. return;
  29331. }
  29332. this._beingRegenerated = true;
  29333. this.setAllVerticesData(this._regenerateVertexData(), false);
  29334. this._beingRegenerated = false;
  29335. };
  29336. _Primitive.prototype.asNewGeometry = function (id) {
  29337. return _super.prototype.copy.call(this, id);
  29338. };
  29339. // overrides
  29340. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  29341. if (!this._beingRegenerated) {
  29342. return;
  29343. }
  29344. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  29345. };
  29346. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  29347. if (!this._beingRegenerated) {
  29348. return;
  29349. }
  29350. _super.prototype.setVerticesData.call(this, kind, data, false);
  29351. };
  29352. // to override
  29353. // protected
  29354. _Primitive.prototype._regenerateVertexData = function () {
  29355. throw new Error("Abstract method");
  29356. };
  29357. _Primitive.prototype.copy = function (id) {
  29358. throw new Error("Must be overriden in sub-classes.");
  29359. };
  29360. _Primitive.prototype.serialize = function () {
  29361. var serializationObject = _super.prototype.serialize.call(this);
  29362. serializationObject.canBeRegenerated = this.canBeRegenerated();
  29363. return serializationObject;
  29364. };
  29365. return _Primitive;
  29366. }(Geometry));
  29367. Primitives._Primitive = _Primitive;
  29368. var Ribbon = (function (_super) {
  29369. __extends(Ribbon, _super);
  29370. // Members
  29371. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  29372. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29373. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29374. _this.pathArray = pathArray;
  29375. _this.closeArray = closeArray;
  29376. _this.closePath = closePath;
  29377. _this.offset = offset;
  29378. _this.side = side;
  29379. return _this;
  29380. }
  29381. Ribbon.prototype._regenerateVertexData = function () {
  29382. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  29383. };
  29384. Ribbon.prototype.copy = function (id) {
  29385. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  29386. };
  29387. return Ribbon;
  29388. }(_Primitive));
  29389. Primitives.Ribbon = Ribbon;
  29390. var Box = (function (_super) {
  29391. __extends(Box, _super);
  29392. // Members
  29393. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  29394. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29395. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29396. _this.size = size;
  29397. _this.side = side;
  29398. return _this;
  29399. }
  29400. Box.prototype._regenerateVertexData = function () {
  29401. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  29402. };
  29403. Box.prototype.copy = function (id) {
  29404. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29405. };
  29406. Box.prototype.serialize = function () {
  29407. var serializationObject = _super.prototype.serialize.call(this);
  29408. serializationObject.size = this.size;
  29409. return serializationObject;
  29410. };
  29411. Box.Parse = function (parsedBox, scene) {
  29412. if (scene.getGeometryByID(parsedBox.id)) {
  29413. return null; // null since geometry could be something else than a box...
  29414. }
  29415. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  29416. if (BABYLON.Tags) {
  29417. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  29418. }
  29419. scene.pushGeometry(box, true);
  29420. return box;
  29421. };
  29422. return Box;
  29423. }(_Primitive));
  29424. Primitives.Box = Box;
  29425. var Sphere = (function (_super) {
  29426. __extends(Sphere, _super);
  29427. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  29428. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29429. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29430. _this.segments = segments;
  29431. _this.diameter = diameter;
  29432. _this.side = side;
  29433. return _this;
  29434. }
  29435. Sphere.prototype._regenerateVertexData = function () {
  29436. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  29437. };
  29438. Sphere.prototype.copy = function (id) {
  29439. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  29440. };
  29441. Sphere.prototype.serialize = function () {
  29442. var serializationObject = _super.prototype.serialize.call(this);
  29443. serializationObject.segments = this.segments;
  29444. serializationObject.diameter = this.diameter;
  29445. return serializationObject;
  29446. };
  29447. Sphere.Parse = function (parsedSphere, scene) {
  29448. if (scene.getGeometryByID(parsedSphere.id)) {
  29449. return null; // null since geometry could be something else than a sphere...
  29450. }
  29451. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  29452. if (BABYLON.Tags) {
  29453. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  29454. }
  29455. scene.pushGeometry(sphere, true);
  29456. return sphere;
  29457. };
  29458. return Sphere;
  29459. }(_Primitive));
  29460. Primitives.Sphere = Sphere;
  29461. var Disc = (function (_super) {
  29462. __extends(Disc, _super);
  29463. // Members
  29464. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  29465. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29466. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29467. _this.radius = radius;
  29468. _this.tessellation = tessellation;
  29469. _this.side = side;
  29470. return _this;
  29471. }
  29472. Disc.prototype._regenerateVertexData = function () {
  29473. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  29474. };
  29475. Disc.prototype.copy = function (id) {
  29476. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  29477. };
  29478. return Disc;
  29479. }(_Primitive));
  29480. Primitives.Disc = Disc;
  29481. var Cylinder = (function (_super) {
  29482. __extends(Cylinder, _super);
  29483. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  29484. if (subdivisions === void 0) { subdivisions = 1; }
  29485. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29486. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29487. _this.height = height;
  29488. _this.diameterTop = diameterTop;
  29489. _this.diameterBottom = diameterBottom;
  29490. _this.tessellation = tessellation;
  29491. _this.subdivisions = subdivisions;
  29492. _this.side = side;
  29493. return _this;
  29494. }
  29495. Cylinder.prototype._regenerateVertexData = function () {
  29496. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  29497. };
  29498. Cylinder.prototype.copy = function (id) {
  29499. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  29500. };
  29501. Cylinder.prototype.serialize = function () {
  29502. var serializationObject = _super.prototype.serialize.call(this);
  29503. serializationObject.height = this.height;
  29504. serializationObject.diameterTop = this.diameterTop;
  29505. serializationObject.diameterBottom = this.diameterBottom;
  29506. serializationObject.tessellation = this.tessellation;
  29507. return serializationObject;
  29508. };
  29509. Cylinder.Parse = function (parsedCylinder, scene) {
  29510. if (scene.getGeometryByID(parsedCylinder.id)) {
  29511. return null; // null since geometry could be something else than a cylinder...
  29512. }
  29513. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  29514. if (BABYLON.Tags) {
  29515. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  29516. }
  29517. scene.pushGeometry(cylinder, true);
  29518. return cylinder;
  29519. };
  29520. return Cylinder;
  29521. }(_Primitive));
  29522. Primitives.Cylinder = Cylinder;
  29523. var Torus = (function (_super) {
  29524. __extends(Torus, _super);
  29525. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  29526. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29527. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29528. _this.diameter = diameter;
  29529. _this.thickness = thickness;
  29530. _this.tessellation = tessellation;
  29531. _this.side = side;
  29532. return _this;
  29533. }
  29534. Torus.prototype._regenerateVertexData = function () {
  29535. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  29536. };
  29537. Torus.prototype.copy = function (id) {
  29538. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  29539. };
  29540. Torus.prototype.serialize = function () {
  29541. var serializationObject = _super.prototype.serialize.call(this);
  29542. serializationObject.diameter = this.diameter;
  29543. serializationObject.thickness = this.thickness;
  29544. serializationObject.tessellation = this.tessellation;
  29545. return serializationObject;
  29546. };
  29547. Torus.Parse = function (parsedTorus, scene) {
  29548. if (scene.getGeometryByID(parsedTorus.id)) {
  29549. return null; // null since geometry could be something else than a torus...
  29550. }
  29551. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  29552. if (BABYLON.Tags) {
  29553. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  29554. }
  29555. scene.pushGeometry(torus, true);
  29556. return torus;
  29557. };
  29558. return Torus;
  29559. }(_Primitive));
  29560. Primitives.Torus = Torus;
  29561. var Ground = (function (_super) {
  29562. __extends(Ground, _super);
  29563. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  29564. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29565. _this.width = width;
  29566. _this.height = height;
  29567. _this.subdivisions = subdivisions;
  29568. return _this;
  29569. }
  29570. Ground.prototype._regenerateVertexData = function () {
  29571. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  29572. };
  29573. Ground.prototype.copy = function (id) {
  29574. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  29575. };
  29576. Ground.prototype.serialize = function () {
  29577. var serializationObject = _super.prototype.serialize.call(this);
  29578. serializationObject.width = this.width;
  29579. serializationObject.height = this.height;
  29580. serializationObject.subdivisions = this.subdivisions;
  29581. return serializationObject;
  29582. };
  29583. Ground.Parse = function (parsedGround, scene) {
  29584. if (scene.getGeometryByID(parsedGround.id)) {
  29585. return null; // null since geometry could be something else than a ground...
  29586. }
  29587. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  29588. if (BABYLON.Tags) {
  29589. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  29590. }
  29591. scene.pushGeometry(ground, true);
  29592. return ground;
  29593. };
  29594. return Ground;
  29595. }(_Primitive));
  29596. Primitives.Ground = Ground;
  29597. var TiledGround = (function (_super) {
  29598. __extends(TiledGround, _super);
  29599. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  29600. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29601. _this.xmin = xmin;
  29602. _this.zmin = zmin;
  29603. _this.xmax = xmax;
  29604. _this.zmax = zmax;
  29605. _this.subdivisions = subdivisions;
  29606. _this.precision = precision;
  29607. return _this;
  29608. }
  29609. TiledGround.prototype._regenerateVertexData = function () {
  29610. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  29611. };
  29612. TiledGround.prototype.copy = function (id) {
  29613. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  29614. };
  29615. return TiledGround;
  29616. }(_Primitive));
  29617. Primitives.TiledGround = TiledGround;
  29618. var Plane = (function (_super) {
  29619. __extends(Plane, _super);
  29620. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  29621. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29622. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29623. _this.size = size;
  29624. _this.side = side;
  29625. return _this;
  29626. }
  29627. Plane.prototype._regenerateVertexData = function () {
  29628. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  29629. };
  29630. Plane.prototype.copy = function (id) {
  29631. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29632. };
  29633. Plane.prototype.serialize = function () {
  29634. var serializationObject = _super.prototype.serialize.call(this);
  29635. serializationObject.size = this.size;
  29636. return serializationObject;
  29637. };
  29638. Plane.Parse = function (parsedPlane, scene) {
  29639. if (scene.getGeometryByID(parsedPlane.id)) {
  29640. return null; // null since geometry could be something else than a ground...
  29641. }
  29642. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  29643. if (BABYLON.Tags) {
  29644. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  29645. }
  29646. scene.pushGeometry(plane, true);
  29647. return plane;
  29648. };
  29649. return Plane;
  29650. }(_Primitive));
  29651. Primitives.Plane = Plane;
  29652. var TorusKnot = (function (_super) {
  29653. __extends(TorusKnot, _super);
  29654. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  29655. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29656. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29657. _this.radius = radius;
  29658. _this.tube = tube;
  29659. _this.radialSegments = radialSegments;
  29660. _this.tubularSegments = tubularSegments;
  29661. _this.p = p;
  29662. _this.q = q;
  29663. _this.side = side;
  29664. return _this;
  29665. }
  29666. TorusKnot.prototype._regenerateVertexData = function () {
  29667. 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 });
  29668. };
  29669. TorusKnot.prototype.copy = function (id) {
  29670. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  29671. };
  29672. TorusKnot.prototype.serialize = function () {
  29673. var serializationObject = _super.prototype.serialize.call(this);
  29674. serializationObject.radius = this.radius;
  29675. serializationObject.tube = this.tube;
  29676. serializationObject.radialSegments = this.radialSegments;
  29677. serializationObject.tubularSegments = this.tubularSegments;
  29678. serializationObject.p = this.p;
  29679. serializationObject.q = this.q;
  29680. return serializationObject;
  29681. };
  29682. ;
  29683. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  29684. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  29685. return null; // null since geometry could be something else than a ground...
  29686. }
  29687. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  29688. if (BABYLON.Tags) {
  29689. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  29690. }
  29691. scene.pushGeometry(torusKnot, true);
  29692. return torusKnot;
  29693. };
  29694. return TorusKnot;
  29695. }(_Primitive));
  29696. Primitives.TorusKnot = TorusKnot;
  29697. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  29698. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  29699. })(BABYLON || (BABYLON = {}));
  29700. //# sourceMappingURL=babylon.geometry.js.map
  29701. var BABYLON;
  29702. (function (BABYLON) {
  29703. var PostProcessManager = (function () {
  29704. function PostProcessManager(scene) {
  29705. this._vertexBuffers = {};
  29706. this._scene = scene;
  29707. }
  29708. PostProcessManager.prototype._prepareBuffers = function () {
  29709. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  29710. return;
  29711. }
  29712. // VBO
  29713. var vertices = [];
  29714. vertices.push(1, 1);
  29715. vertices.push(-1, 1);
  29716. vertices.push(-1, -1);
  29717. vertices.push(1, -1);
  29718. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  29719. this._buildIndexBuffer();
  29720. };
  29721. PostProcessManager.prototype._buildIndexBuffer = function () {
  29722. // Indices
  29723. var indices = [];
  29724. indices.push(0);
  29725. indices.push(1);
  29726. indices.push(2);
  29727. indices.push(0);
  29728. indices.push(2);
  29729. indices.push(3);
  29730. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  29731. };
  29732. PostProcessManager.prototype._rebuild = function () {
  29733. if (!this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  29734. return;
  29735. }
  29736. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  29737. this._buildIndexBuffer();
  29738. };
  29739. // Methods
  29740. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  29741. var postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  29742. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29743. return false;
  29744. }
  29745. postProcesses[0].activate(this._scene.activeCamera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  29746. return true;
  29747. };
  29748. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  29749. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  29750. var engine = this._scene.getEngine();
  29751. for (var index = 0; index < postProcesses.length; index++) {
  29752. if (index < postProcesses.length - 1) {
  29753. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29754. }
  29755. else {
  29756. if (targetTexture) {
  29757. engine.bindFramebuffer(targetTexture, 0, null, null, forceFullscreenViewport);
  29758. }
  29759. else {
  29760. engine.restoreDefaultFramebuffer();
  29761. }
  29762. }
  29763. var pp = postProcesses[index];
  29764. var effect = pp.apply();
  29765. if (effect) {
  29766. pp.onBeforeRenderObservable.notifyObservers(effect);
  29767. // VBOs
  29768. this._prepareBuffers();
  29769. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29770. // Draw order
  29771. engine.draw(true, 0, 6);
  29772. pp.onAfterRenderObservable.notifyObservers(effect);
  29773. }
  29774. }
  29775. // Restore depth buffer
  29776. engine.setDepthBuffer(true);
  29777. engine.setDepthWrite(true);
  29778. };
  29779. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  29780. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  29781. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29782. return;
  29783. }
  29784. var engine = this._scene.getEngine();
  29785. for (var index = 0, len = postProcesses.length; index < len; index++) {
  29786. if (index < len - 1) {
  29787. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29788. }
  29789. else {
  29790. if (targetTexture) {
  29791. engine.bindFramebuffer(targetTexture, faceIndex);
  29792. }
  29793. else {
  29794. engine.restoreDefaultFramebuffer();
  29795. }
  29796. }
  29797. if (doNotPresent) {
  29798. break;
  29799. }
  29800. var pp = postProcesses[index];
  29801. var effect = pp.apply();
  29802. if (effect) {
  29803. pp.onBeforeRenderObservable.notifyObservers(effect);
  29804. // VBOs
  29805. this._prepareBuffers();
  29806. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29807. // Draw order
  29808. engine.draw(true, 0, 6);
  29809. pp.onAfterRenderObservable.notifyObservers(effect);
  29810. }
  29811. }
  29812. // Restore states
  29813. engine.setDepthBuffer(true);
  29814. engine.setDepthWrite(true);
  29815. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29816. };
  29817. PostProcessManager.prototype.dispose = function () {
  29818. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  29819. if (buffer) {
  29820. buffer.dispose();
  29821. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  29822. }
  29823. if (this._indexBuffer) {
  29824. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  29825. this._indexBuffer = null;
  29826. }
  29827. };
  29828. return PostProcessManager;
  29829. }());
  29830. BABYLON.PostProcessManager = PostProcessManager;
  29831. })(BABYLON || (BABYLON = {}));
  29832. //# sourceMappingURL=babylon.postProcessManager.js.map
  29833. var BABYLON;
  29834. (function (BABYLON) {
  29835. /**
  29836. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  29837. */
  29838. var PerformanceMonitor = (function () {
  29839. /**
  29840. * constructor
  29841. * @param frameSampleSize The number of samples required to saturate the sliding window
  29842. */
  29843. function PerformanceMonitor(frameSampleSize) {
  29844. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  29845. this._enabled = true;
  29846. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  29847. }
  29848. /**
  29849. * Samples current frame
  29850. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  29851. */
  29852. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  29853. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  29854. if (!this._enabled)
  29855. return;
  29856. if (this._lastFrameTimeMs != null) {
  29857. var dt = timeMs - this._lastFrameTimeMs;
  29858. this._rollingFrameTime.add(dt);
  29859. }
  29860. this._lastFrameTimeMs = timeMs;
  29861. };
  29862. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  29863. /**
  29864. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  29865. * @return Average frame time in milliseconds
  29866. */
  29867. get: function () {
  29868. return this._rollingFrameTime.average;
  29869. },
  29870. enumerable: true,
  29871. configurable: true
  29872. });
  29873. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  29874. /**
  29875. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  29876. * @return Frame time variance in milliseconds squared
  29877. */
  29878. get: function () {
  29879. return this._rollingFrameTime.variance;
  29880. },
  29881. enumerable: true,
  29882. configurable: true
  29883. });
  29884. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  29885. /**
  29886. * Returns the frame time of the most recent frame
  29887. * @return Frame time in milliseconds
  29888. */
  29889. get: function () {
  29890. return this._rollingFrameTime.history(0);
  29891. },
  29892. enumerable: true,
  29893. configurable: true
  29894. });
  29895. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  29896. /**
  29897. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  29898. * @return Framerate in frames per second
  29899. */
  29900. get: function () {
  29901. return 1000.0 / this._rollingFrameTime.average;
  29902. },
  29903. enumerable: true,
  29904. configurable: true
  29905. });
  29906. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  29907. /**
  29908. * Returns the average framerate in frames per second using the most recent frame time
  29909. * @return Framerate in frames per second
  29910. */
  29911. get: function () {
  29912. return 1000.0 / this._rollingFrameTime.history(0);
  29913. },
  29914. enumerable: true,
  29915. configurable: true
  29916. });
  29917. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  29918. /**
  29919. * Returns true if enough samples have been taken to completely fill the sliding window
  29920. * @return true if saturated
  29921. */
  29922. get: function () {
  29923. return this._rollingFrameTime.isSaturated();
  29924. },
  29925. enumerable: true,
  29926. configurable: true
  29927. });
  29928. /**
  29929. * Enables contributions to the sliding window sample set
  29930. */
  29931. PerformanceMonitor.prototype.enable = function () {
  29932. this._enabled = true;
  29933. };
  29934. /**
  29935. * Disables contributions to the sliding window sample set
  29936. * Samples will not be interpolated over the disabled period
  29937. */
  29938. PerformanceMonitor.prototype.disable = function () {
  29939. this._enabled = false;
  29940. //clear last sample to avoid interpolating over the disabled period when next enabled
  29941. this._lastFrameTimeMs = null;
  29942. this._lastChangeTimeMs = null;
  29943. };
  29944. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  29945. /**
  29946. * Returns true if sampling is enabled
  29947. * @return true if enabled
  29948. */
  29949. get: function () {
  29950. return this._enabled;
  29951. },
  29952. enumerable: true,
  29953. configurable: true
  29954. });
  29955. /**
  29956. * Resets performance monitor
  29957. */
  29958. PerformanceMonitor.prototype.reset = function () {
  29959. //clear last sample to avoid interpolating over the disabled period when next enabled
  29960. this._lastFrameTimeMs = null;
  29961. this._lastChangeTimeMs = null;
  29962. //wipe record
  29963. this._rollingFrameTime.reset();
  29964. };
  29965. return PerformanceMonitor;
  29966. }());
  29967. BABYLON.PerformanceMonitor = PerformanceMonitor;
  29968. /**
  29969. * RollingAverage
  29970. *
  29971. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  29972. */
  29973. var RollingAverage = (function () {
  29974. /**
  29975. * constructor
  29976. * @param length The number of samples required to saturate the sliding window
  29977. */
  29978. function RollingAverage(length) {
  29979. this._samples = new Array(length);
  29980. this.reset();
  29981. }
  29982. /**
  29983. * Adds a sample to the sample set
  29984. * @param v The sample value
  29985. */
  29986. RollingAverage.prototype.add = function (v) {
  29987. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  29988. var delta;
  29989. //we need to check if we've already wrapped round
  29990. if (this.isSaturated()) {
  29991. //remove bottom of stack from mean
  29992. var bottomValue = this._samples[this._pos];
  29993. delta = bottomValue - this.average;
  29994. this.average -= delta / (this._sampleCount - 1);
  29995. this._m2 -= delta * (bottomValue - this.average);
  29996. }
  29997. else {
  29998. this._sampleCount++;
  29999. }
  30000. //add new value to mean
  30001. delta = v - this.average;
  30002. this.average += delta / (this._sampleCount);
  30003. this._m2 += delta * (v - this.average);
  30004. //set the new variance
  30005. this.variance = this._m2 / (this._sampleCount - 1);
  30006. this._samples[this._pos] = v;
  30007. this._pos++;
  30008. this._pos %= this._samples.length; //positive wrap around
  30009. };
  30010. /**
  30011. * Returns previously added values or null if outside of history or outside the sliding window domain
  30012. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  30013. * @return Value previously recorded with add() or null if outside of range
  30014. */
  30015. RollingAverage.prototype.history = function (i) {
  30016. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  30017. return null;
  30018. }
  30019. var i0 = this._wrapPosition(this._pos - 1.0);
  30020. return this._samples[this._wrapPosition(i0 - i)];
  30021. };
  30022. /**
  30023. * Returns true if enough samples have been taken to completely fill the sliding window
  30024. * @return true if sample-set saturated
  30025. */
  30026. RollingAverage.prototype.isSaturated = function () {
  30027. return this._sampleCount >= this._samples.length;
  30028. };
  30029. /**
  30030. * Resets the rolling average (equivalent to 0 samples taken so far)
  30031. */
  30032. RollingAverage.prototype.reset = function () {
  30033. this.average = 0;
  30034. this.variance = 0;
  30035. this._sampleCount = 0;
  30036. this._pos = 0;
  30037. this._m2 = 0;
  30038. };
  30039. /**
  30040. * Wraps a value around the sample range boundaries
  30041. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  30042. * @return Wrapped position in sample range
  30043. */
  30044. RollingAverage.prototype._wrapPosition = function (i) {
  30045. var max = this._samples.length;
  30046. return ((i % max) + max) % max;
  30047. };
  30048. return RollingAverage;
  30049. }());
  30050. BABYLON.RollingAverage = RollingAverage;
  30051. })(BABYLON || (BABYLON = {}));
  30052. //# sourceMappingURL=babylon.performanceMonitor.js.map
  30053. var BABYLON;
  30054. (function (BABYLON) {
  30055. var StandardMaterialDefines = (function (_super) {
  30056. __extends(StandardMaterialDefines, _super);
  30057. function StandardMaterialDefines() {
  30058. var _this = _super.call(this) || this;
  30059. _this.MAINUV1 = false;
  30060. _this.MAINUV2 = false;
  30061. _this.DIFFUSE = false;
  30062. _this.DIFFUSEDIRECTUV = 0;
  30063. _this.AMBIENT = false;
  30064. _this.AMBIENTDIRECTUV = 0;
  30065. _this.OPACITY = false;
  30066. _this.OPACITYDIRECTUV = 0;
  30067. _this.OPACITYRGB = false;
  30068. _this.REFLECTION = false;
  30069. _this.EMISSIVE = false;
  30070. _this.EMISSIVEDIRECTUV = 0;
  30071. _this.SPECULAR = false;
  30072. _this.SPECULARDIRECTUV = 0;
  30073. _this.BUMP = false;
  30074. _this.BUMPDIRECTUV = 0;
  30075. _this.PARALLAX = false;
  30076. _this.PARALLAXOCCLUSION = false;
  30077. _this.SPECULAROVERALPHA = false;
  30078. _this.CLIPPLANE = false;
  30079. _this.ALPHATEST = false;
  30080. _this.ALPHAFROMDIFFUSE = false;
  30081. _this.POINTSIZE = false;
  30082. _this.FOG = false;
  30083. _this.SPECULARTERM = false;
  30084. _this.DIFFUSEFRESNEL = false;
  30085. _this.OPACITYFRESNEL = false;
  30086. _this.REFLECTIONFRESNEL = false;
  30087. _this.REFRACTIONFRESNEL = false;
  30088. _this.EMISSIVEFRESNEL = false;
  30089. _this.FRESNEL = false;
  30090. _this.NORMAL = false;
  30091. _this.UV1 = false;
  30092. _this.UV2 = false;
  30093. _this.VERTEXCOLOR = false;
  30094. _this.VERTEXALPHA = false;
  30095. _this.NUM_BONE_INFLUENCERS = 0;
  30096. _this.BonesPerMesh = 0;
  30097. _this.INSTANCES = false;
  30098. _this.GLOSSINESS = false;
  30099. _this.ROUGHNESS = false;
  30100. _this.EMISSIVEASILLUMINATION = false;
  30101. _this.LINKEMISSIVEWITHDIFFUSE = false;
  30102. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  30103. _this.LIGHTMAP = false;
  30104. _this.LIGHTMAPDIRECTUV = 0;
  30105. _this.USELIGHTMAPASSHADOWMAP = false;
  30106. _this.REFLECTIONMAP_3D = false;
  30107. _this.REFLECTIONMAP_SPHERICAL = false;
  30108. _this.REFLECTIONMAP_PLANAR = false;
  30109. _this.REFLECTIONMAP_CUBIC = false;
  30110. _this.REFLECTIONMAP_PROJECTION = false;
  30111. _this.REFLECTIONMAP_SKYBOX = false;
  30112. _this.REFLECTIONMAP_EXPLICIT = false;
  30113. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  30114. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  30115. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  30116. _this.INVERTCUBICMAP = false;
  30117. _this.LOGARITHMICDEPTH = false;
  30118. _this.REFRACTION = false;
  30119. _this.REFRACTIONMAP_3D = false;
  30120. _this.REFLECTIONOVERALPHA = false;
  30121. _this.TWOSIDEDLIGHTING = false;
  30122. _this.SHADOWFLOAT = false;
  30123. _this.MORPHTARGETS = false;
  30124. _this.MORPHTARGETS_NORMAL = false;
  30125. _this.MORPHTARGETS_TANGENT = false;
  30126. _this.NUM_MORPH_INFLUENCERS = 0;
  30127. _this.USERIGHTHANDEDSYSTEM = false;
  30128. _this.IMAGEPROCESSING = false;
  30129. _this.VIGNETTE = false;
  30130. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  30131. _this.VIGNETTEBLENDMODEOPAQUE = false;
  30132. _this.TONEMAPPING = false;
  30133. _this.CONTRAST = false;
  30134. _this.COLORCURVES = false;
  30135. _this.COLORGRADING = false;
  30136. _this.SAMPLER3DGREENDEPTH = false;
  30137. _this.SAMPLER3DBGRMAP = false;
  30138. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  30139. _this.EXPOSURE = false;
  30140. _this.rebuild();
  30141. return _this;
  30142. }
  30143. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  30144. var modes = [
  30145. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  30146. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  30147. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  30148. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  30149. ];
  30150. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  30151. var mode = modes_1[_i];
  30152. this[mode] = (mode === modeToEnable);
  30153. }
  30154. };
  30155. return StandardMaterialDefines;
  30156. }(BABYLON.MaterialDefines));
  30157. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  30158. var StandardMaterial = (function (_super) {
  30159. __extends(StandardMaterial, _super);
  30160. function StandardMaterial(name, scene) {
  30161. var _this = _super.call(this, name, scene) || this;
  30162. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  30163. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  30164. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  30165. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  30166. _this.specularPower = 64;
  30167. _this._useAlphaFromDiffuseTexture = false;
  30168. _this._useEmissiveAsIllumination = false;
  30169. _this._linkEmissiveWithDiffuse = false;
  30170. _this._useSpecularOverAlpha = false;
  30171. _this._useReflectionOverAlpha = false;
  30172. _this._disableLighting = false;
  30173. _this._useParallax = false;
  30174. _this._useParallaxOcclusion = false;
  30175. _this.parallaxScaleBias = 0.05;
  30176. _this._roughness = 0;
  30177. _this.indexOfRefraction = 0.98;
  30178. _this.invertRefractionY = true;
  30179. _this._useLightmapAsShadowmap = false;
  30180. _this._useReflectionFresnelFromSpecular = false;
  30181. _this._useGlossinessFromSpecularMapAlpha = false;
  30182. _this._maxSimultaneousLights = 4;
  30183. /**
  30184. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  30185. */
  30186. _this._invertNormalMapX = false;
  30187. /**
  30188. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  30189. */
  30190. _this._invertNormalMapY = false;
  30191. /**
  30192. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  30193. */
  30194. _this._twoSidedLighting = false;
  30195. _this._renderTargets = new BABYLON.SmartArray(16);
  30196. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  30197. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  30198. // Setup the default processing configuration to the scene.
  30199. _this._attachImageProcessingConfiguration(null);
  30200. _this.getRenderTargetTextures = function () {
  30201. _this._renderTargets.reset();
  30202. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  30203. _this._renderTargets.push(_this._reflectionTexture);
  30204. }
  30205. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  30206. _this._renderTargets.push(_this._refractionTexture);
  30207. }
  30208. return _this._renderTargets;
  30209. };
  30210. return _this;
  30211. }
  30212. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  30213. /**
  30214. * Gets the image processing configuration used either in this material.
  30215. */
  30216. get: function () {
  30217. return this._imageProcessingConfiguration;
  30218. },
  30219. /**
  30220. * Sets the Default image processing configuration used either in the this material.
  30221. *
  30222. * If sets to null, the scene one is in use.
  30223. */
  30224. set: function (value) {
  30225. this._attachImageProcessingConfiguration(value);
  30226. // Ensure the effect will be rebuilt.
  30227. this._markAllSubMeshesAsTexturesDirty();
  30228. },
  30229. enumerable: true,
  30230. configurable: true
  30231. });
  30232. /**
  30233. * Attaches a new image processing configuration to the Standard Material.
  30234. * @param configuration
  30235. */
  30236. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  30237. var _this = this;
  30238. if (configuration === this._imageProcessingConfiguration) {
  30239. return;
  30240. }
  30241. // Detaches observer.
  30242. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  30243. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  30244. }
  30245. // Pick the scene configuration if needed.
  30246. if (!configuration) {
  30247. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  30248. }
  30249. else {
  30250. this._imageProcessingConfiguration = configuration;
  30251. }
  30252. // Attaches observer.
  30253. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  30254. _this._markAllSubMeshesAsImageProcessingDirty();
  30255. });
  30256. };
  30257. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  30258. /**
  30259. * Gets wether the color curves effect is enabled.
  30260. */
  30261. get: function () {
  30262. return this.imageProcessingConfiguration.colorCurvesEnabled;
  30263. },
  30264. /**
  30265. * Sets wether the color curves effect is enabled.
  30266. */
  30267. set: function (value) {
  30268. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  30269. },
  30270. enumerable: true,
  30271. configurable: true
  30272. });
  30273. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  30274. /**
  30275. * Gets wether the color grading effect is enabled.
  30276. */
  30277. get: function () {
  30278. return this.imageProcessingConfiguration.colorGradingEnabled;
  30279. },
  30280. /**
  30281. * Gets wether the color grading effect is enabled.
  30282. */
  30283. set: function (value) {
  30284. this.imageProcessingConfiguration.colorGradingEnabled = value;
  30285. },
  30286. enumerable: true,
  30287. configurable: true
  30288. });
  30289. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  30290. /**
  30291. * Gets wether tonemapping is enabled or not.
  30292. */
  30293. get: function () {
  30294. return this._imageProcessingConfiguration.toneMappingEnabled;
  30295. },
  30296. /**
  30297. * Sets wether tonemapping is enabled or not
  30298. */
  30299. set: function (value) {
  30300. this._imageProcessingConfiguration.toneMappingEnabled = value;
  30301. },
  30302. enumerable: true,
  30303. configurable: true
  30304. });
  30305. ;
  30306. ;
  30307. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  30308. /**
  30309. * The camera exposure used on this material.
  30310. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  30311. * This corresponds to a photographic exposure.
  30312. */
  30313. get: function () {
  30314. return this._imageProcessingConfiguration.exposure;
  30315. },
  30316. /**
  30317. * The camera exposure used on this material.
  30318. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  30319. * This corresponds to a photographic exposure.
  30320. */
  30321. set: function (value) {
  30322. this._imageProcessingConfiguration.exposure = value;
  30323. },
  30324. enumerable: true,
  30325. configurable: true
  30326. });
  30327. ;
  30328. ;
  30329. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  30330. /**
  30331. * Gets The camera contrast used on this material.
  30332. */
  30333. get: function () {
  30334. return this._imageProcessingConfiguration.contrast;
  30335. },
  30336. /**
  30337. * Sets The camera contrast used on this material.
  30338. */
  30339. set: function (value) {
  30340. this._imageProcessingConfiguration.contrast = value;
  30341. },
  30342. enumerable: true,
  30343. configurable: true
  30344. });
  30345. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  30346. /**
  30347. * Gets the Color Grading 2D Lookup Texture.
  30348. */
  30349. get: function () {
  30350. return this._imageProcessingConfiguration.colorGradingTexture;
  30351. },
  30352. /**
  30353. * Sets the Color Grading 2D Lookup Texture.
  30354. */
  30355. set: function (value) {
  30356. this._imageProcessingConfiguration.colorGradingTexture = value;
  30357. },
  30358. enumerable: true,
  30359. configurable: true
  30360. });
  30361. StandardMaterial.prototype.getClassName = function () {
  30362. return "StandardMaterial";
  30363. };
  30364. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  30365. get: function () {
  30366. return this._useLogarithmicDepth;
  30367. },
  30368. set: function (value) {
  30369. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  30370. this._markAllSubMeshesAsMiscDirty();
  30371. },
  30372. enumerable: true,
  30373. configurable: true
  30374. });
  30375. StandardMaterial.prototype.needAlphaBlending = function () {
  30376. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  30377. };
  30378. StandardMaterial.prototype.needAlphaTesting = function () {
  30379. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  30380. };
  30381. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  30382. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  30383. };
  30384. StandardMaterial.prototype.getAlphaTestTexture = function () {
  30385. return this._diffuseTexture;
  30386. };
  30387. /**
  30388. * Child classes can use it to update shaders
  30389. */
  30390. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  30391. if (this.isFrozen) {
  30392. if (this._wasPreviouslyReady && subMesh.effect) {
  30393. return true;
  30394. }
  30395. }
  30396. if (!subMesh._materialDefines) {
  30397. subMesh._materialDefines = new StandardMaterialDefines();
  30398. }
  30399. var scene = this.getScene();
  30400. var defines = subMesh._materialDefines;
  30401. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  30402. if (defines._renderId === scene.getRenderId()) {
  30403. return true;
  30404. }
  30405. }
  30406. var engine = scene.getEngine();
  30407. // Lights
  30408. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  30409. // Textures
  30410. if (defines._areTexturesDirty) {
  30411. defines._needUVs = false;
  30412. defines.MAINUV1 = false;
  30413. defines.MAINUV2 = false;
  30414. if (scene.texturesEnabled) {
  30415. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  30416. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  30417. return false;
  30418. }
  30419. else {
  30420. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  30421. }
  30422. }
  30423. else {
  30424. defines.DIFFUSE = false;
  30425. }
  30426. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  30427. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  30428. return false;
  30429. }
  30430. else {
  30431. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  30432. }
  30433. }
  30434. else {
  30435. defines.AMBIENT = false;
  30436. }
  30437. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  30438. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  30439. return false;
  30440. }
  30441. else {
  30442. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  30443. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  30444. }
  30445. }
  30446. else {
  30447. defines.OPACITY = false;
  30448. }
  30449. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  30450. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  30451. return false;
  30452. }
  30453. else {
  30454. defines._needNormals = true;
  30455. defines.REFLECTION = true;
  30456. defines.ROUGHNESS = (this._roughness > 0);
  30457. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  30458. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  30459. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  30460. switch (this._reflectionTexture.coordinatesMode) {
  30461. case BABYLON.Texture.CUBIC_MODE:
  30462. case BABYLON.Texture.INVCUBIC_MODE:
  30463. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  30464. break;
  30465. case BABYLON.Texture.EXPLICIT_MODE:
  30466. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  30467. break;
  30468. case BABYLON.Texture.PLANAR_MODE:
  30469. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  30470. break;
  30471. case BABYLON.Texture.PROJECTION_MODE:
  30472. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  30473. break;
  30474. case BABYLON.Texture.SKYBOX_MODE:
  30475. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  30476. break;
  30477. case BABYLON.Texture.SPHERICAL_MODE:
  30478. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  30479. break;
  30480. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  30481. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  30482. break;
  30483. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  30484. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  30485. break;
  30486. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  30487. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  30488. break;
  30489. }
  30490. }
  30491. }
  30492. else {
  30493. defines.REFLECTION = false;
  30494. }
  30495. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  30496. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  30497. return false;
  30498. }
  30499. else {
  30500. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  30501. }
  30502. }
  30503. else {
  30504. defines.EMISSIVE = false;
  30505. }
  30506. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  30507. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  30508. return false;
  30509. }
  30510. else {
  30511. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  30512. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  30513. }
  30514. }
  30515. else {
  30516. defines.LIGHTMAP = false;
  30517. }
  30518. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  30519. if (!this._specularTexture.isReadyOrNotBlocking()) {
  30520. return false;
  30521. }
  30522. else {
  30523. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  30524. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  30525. }
  30526. }
  30527. else {
  30528. defines.SPECULAR = false;
  30529. }
  30530. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  30531. // Bump texure can not be not blocking.
  30532. if (!this._bumpTexture.isReady()) {
  30533. return false;
  30534. }
  30535. else {
  30536. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  30537. defines.PARALLAX = this._useParallax;
  30538. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  30539. }
  30540. }
  30541. else {
  30542. defines.BUMP = false;
  30543. }
  30544. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  30545. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  30546. return false;
  30547. }
  30548. else {
  30549. defines._needUVs = true;
  30550. defines.REFRACTION = true;
  30551. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  30552. }
  30553. }
  30554. else {
  30555. defines.REFRACTION = false;
  30556. }
  30557. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  30558. }
  30559. else {
  30560. defines.DIFFUSE = false;
  30561. defines.AMBIENT = false;
  30562. defines.OPACITY = false;
  30563. defines.REFLECTION = false;
  30564. defines.EMISSIVE = false;
  30565. defines.LIGHTMAP = false;
  30566. defines.BUMP = false;
  30567. defines.REFRACTION = false;
  30568. }
  30569. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  30570. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  30571. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  30572. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  30573. }
  30574. if (defines._areImageProcessingDirty) {
  30575. if (!this._imageProcessingConfiguration.isReady()) {
  30576. return false;
  30577. }
  30578. this._imageProcessingConfiguration.prepareDefines(defines);
  30579. }
  30580. if (defines._areFresnelDirty) {
  30581. if (StandardMaterial.FresnelEnabled) {
  30582. // Fresnel
  30583. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  30584. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  30585. this._reflectionFresnelParameters) {
  30586. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  30587. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  30588. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  30589. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  30590. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  30591. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  30592. defines._needNormals = true;
  30593. defines.FRESNEL = true;
  30594. }
  30595. }
  30596. else {
  30597. defines.FRESNEL = false;
  30598. }
  30599. }
  30600. // Misc.
  30601. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  30602. // Attribs
  30603. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  30604. // Values that need to be evaluated on every frame
  30605. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  30606. // Get correct effect
  30607. if (defines.isDirty) {
  30608. defines.markAsProcessed();
  30609. scene.resetCachedMaterial();
  30610. // Fallbacks
  30611. var fallbacks = new BABYLON.EffectFallbacks();
  30612. if (defines.REFLECTION) {
  30613. fallbacks.addFallback(0, "REFLECTION");
  30614. }
  30615. if (defines.SPECULAR) {
  30616. fallbacks.addFallback(0, "SPECULAR");
  30617. }
  30618. if (defines.BUMP) {
  30619. fallbacks.addFallback(0, "BUMP");
  30620. }
  30621. if (defines.PARALLAX) {
  30622. fallbacks.addFallback(1, "PARALLAX");
  30623. }
  30624. if (defines.PARALLAXOCCLUSION) {
  30625. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  30626. }
  30627. if (defines.SPECULAROVERALPHA) {
  30628. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  30629. }
  30630. if (defines.FOG) {
  30631. fallbacks.addFallback(1, "FOG");
  30632. }
  30633. if (defines.POINTSIZE) {
  30634. fallbacks.addFallback(0, "POINTSIZE");
  30635. }
  30636. if (defines.LOGARITHMICDEPTH) {
  30637. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  30638. }
  30639. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  30640. if (defines.SPECULARTERM) {
  30641. fallbacks.addFallback(0, "SPECULARTERM");
  30642. }
  30643. if (defines.DIFFUSEFRESNEL) {
  30644. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  30645. }
  30646. if (defines.OPACITYFRESNEL) {
  30647. fallbacks.addFallback(2, "OPACITYFRESNEL");
  30648. }
  30649. if (defines.REFLECTIONFRESNEL) {
  30650. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  30651. }
  30652. if (defines.EMISSIVEFRESNEL) {
  30653. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  30654. }
  30655. if (defines.FRESNEL) {
  30656. fallbacks.addFallback(4, "FRESNEL");
  30657. }
  30658. //Attributes
  30659. var attribs = [BABYLON.VertexBuffer.PositionKind];
  30660. if (defines.NORMAL) {
  30661. attribs.push(BABYLON.VertexBuffer.NormalKind);
  30662. }
  30663. if (defines.UV1) {
  30664. attribs.push(BABYLON.VertexBuffer.UVKind);
  30665. }
  30666. if (defines.UV2) {
  30667. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  30668. }
  30669. if (defines.VERTEXCOLOR) {
  30670. attribs.push(BABYLON.VertexBuffer.ColorKind);
  30671. }
  30672. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  30673. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  30674. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  30675. var shaderName = "default";
  30676. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  30677. "vFogInfos", "vFogColor", "pointSize",
  30678. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  30679. "mBones",
  30680. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  30681. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  30682. "logarithmicDepthConstant", "vNormalReoderParams"
  30683. ];
  30684. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  30685. var uniformBuffers = ["Material", "Scene"];
  30686. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  30687. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  30688. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  30689. uniformsNames: uniforms,
  30690. uniformBuffersNames: uniformBuffers,
  30691. samplers: samplers,
  30692. defines: defines,
  30693. maxSimultaneousLights: this._maxSimultaneousLights
  30694. });
  30695. if (this.customShaderNameResolve) {
  30696. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  30697. }
  30698. var join = defines.toString();
  30699. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  30700. attributes: attribs,
  30701. uniformsNames: uniforms,
  30702. uniformBuffersNames: uniformBuffers,
  30703. samplers: samplers,
  30704. defines: join,
  30705. fallbacks: fallbacks,
  30706. onCompiled: this.onCompiled,
  30707. onError: this.onError,
  30708. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  30709. }, engine), defines);
  30710. this.buildUniformLayout();
  30711. }
  30712. if (!subMesh.effect.isReady()) {
  30713. return false;
  30714. }
  30715. defines._renderId = scene.getRenderId();
  30716. this._wasPreviouslyReady = true;
  30717. return true;
  30718. };
  30719. StandardMaterial.prototype.buildUniformLayout = function () {
  30720. // Order is important !
  30721. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  30722. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  30723. this._uniformBuffer.addUniform("opacityParts", 4);
  30724. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  30725. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  30726. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  30727. this._uniformBuffer.addUniform("refractionRightColor", 4);
  30728. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  30729. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  30730. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  30731. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  30732. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  30733. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  30734. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  30735. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  30736. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  30737. this._uniformBuffer.addUniform("vBumpInfos", 3);
  30738. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  30739. this._uniformBuffer.addUniform("ambientMatrix", 16);
  30740. this._uniformBuffer.addUniform("opacityMatrix", 16);
  30741. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  30742. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  30743. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  30744. this._uniformBuffer.addUniform("specularMatrix", 16);
  30745. this._uniformBuffer.addUniform("bumpMatrix", 16);
  30746. this._uniformBuffer.addUniform("vNormalReoderParams", 4);
  30747. this._uniformBuffer.addUniform("refractionMatrix", 16);
  30748. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  30749. this._uniformBuffer.addUniform("vSpecularColor", 4);
  30750. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  30751. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  30752. this._uniformBuffer.addUniform("pointSize", 1);
  30753. this._uniformBuffer.create();
  30754. };
  30755. StandardMaterial.prototype.unbind = function () {
  30756. if (this._activeEffect) {
  30757. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  30758. this._activeEffect.setTexture("reflection2DSampler", null);
  30759. }
  30760. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  30761. this._activeEffect.setTexture("refraction2DSampler", null);
  30762. }
  30763. }
  30764. _super.prototype.unbind.call(this);
  30765. };
  30766. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  30767. var scene = this.getScene();
  30768. var defines = subMesh._materialDefines;
  30769. if (!defines) {
  30770. return;
  30771. }
  30772. var effect = subMesh.effect;
  30773. this._activeEffect = effect;
  30774. // Matrices
  30775. this.bindOnlyWorldMatrix(world);
  30776. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  30777. // Bones
  30778. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  30779. if (mustRebind) {
  30780. this._uniformBuffer.bindToEffect(effect, "Material");
  30781. this.bindViewProjection(effect);
  30782. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  30783. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  30784. // Fresnel
  30785. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  30786. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  30787. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  30788. }
  30789. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  30790. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  30791. }
  30792. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  30793. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  30794. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  30795. }
  30796. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  30797. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  30798. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  30799. }
  30800. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  30801. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  30802. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  30803. }
  30804. }
  30805. // Textures
  30806. if (scene.texturesEnabled) {
  30807. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  30808. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  30809. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  30810. }
  30811. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  30812. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  30813. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  30814. }
  30815. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  30816. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  30817. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  30818. }
  30819. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  30820. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  30821. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  30822. }
  30823. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  30824. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  30825. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  30826. }
  30827. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  30828. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  30829. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  30830. }
  30831. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  30832. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  30833. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  30834. }
  30835. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  30836. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  30837. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  30838. if (scene._mirroredCameraPosition) {
  30839. 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);
  30840. }
  30841. else {
  30842. 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);
  30843. }
  30844. }
  30845. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  30846. var depth = 1.0;
  30847. if (!this._refractionTexture.isCube) {
  30848. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  30849. if (this._refractionTexture.depth) {
  30850. depth = this._refractionTexture.depth;
  30851. }
  30852. }
  30853. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  30854. }
  30855. }
  30856. // Point size
  30857. if (this.pointsCloud) {
  30858. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  30859. }
  30860. if (defines.SPECULARTERM) {
  30861. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  30862. }
  30863. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  30864. // Diffuse
  30865. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  30866. }
  30867. // Textures
  30868. if (scene.texturesEnabled) {
  30869. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  30870. effect.setTexture("diffuseSampler", this._diffuseTexture);
  30871. }
  30872. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  30873. effect.setTexture("ambientSampler", this._ambientTexture);
  30874. }
  30875. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  30876. effect.setTexture("opacitySampler", this._opacityTexture);
  30877. }
  30878. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  30879. if (this._reflectionTexture.isCube) {
  30880. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  30881. }
  30882. else {
  30883. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  30884. }
  30885. }
  30886. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  30887. effect.setTexture("emissiveSampler", this._emissiveTexture);
  30888. }
  30889. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  30890. effect.setTexture("lightmapSampler", this._lightmapTexture);
  30891. }
  30892. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  30893. effect.setTexture("specularSampler", this._specularTexture);
  30894. }
  30895. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  30896. effect.setTexture("bumpSampler", this._bumpTexture);
  30897. }
  30898. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  30899. var depth = 1.0;
  30900. if (this._refractionTexture.isCube) {
  30901. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  30902. }
  30903. else {
  30904. effect.setTexture("refraction2DSampler", this._refractionTexture);
  30905. }
  30906. }
  30907. }
  30908. // Clip plane
  30909. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  30910. // Colors
  30911. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  30912. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  30913. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  30914. }
  30915. if (mustRebind || !this.isFrozen) {
  30916. // Lights
  30917. if (scene.lightsEnabled && !this._disableLighting) {
  30918. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  30919. }
  30920. // View
  30921. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  30922. this.bindView(effect);
  30923. }
  30924. // Fog
  30925. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  30926. // Morph targets
  30927. if (defines.NUM_MORPH_INFLUENCERS) {
  30928. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  30929. }
  30930. // Log. depth
  30931. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  30932. // image processing
  30933. this._imageProcessingConfiguration.bind(this._activeEffect);
  30934. }
  30935. this._uniformBuffer.update();
  30936. this._afterBind(mesh, this._activeEffect);
  30937. };
  30938. StandardMaterial.prototype.getAnimatables = function () {
  30939. var results = [];
  30940. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  30941. results.push(this._diffuseTexture);
  30942. }
  30943. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  30944. results.push(this._ambientTexture);
  30945. }
  30946. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  30947. results.push(this._opacityTexture);
  30948. }
  30949. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  30950. results.push(this._reflectionTexture);
  30951. }
  30952. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  30953. results.push(this._emissiveTexture);
  30954. }
  30955. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  30956. results.push(this._specularTexture);
  30957. }
  30958. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  30959. results.push(this._bumpTexture);
  30960. }
  30961. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  30962. results.push(this._lightmapTexture);
  30963. }
  30964. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  30965. results.push(this._refractionTexture);
  30966. }
  30967. return results;
  30968. };
  30969. StandardMaterial.prototype.getActiveTextures = function () {
  30970. var activeTextures = _super.prototype.getActiveTextures.call(this);
  30971. if (this._diffuseTexture) {
  30972. activeTextures.push(this._diffuseTexture);
  30973. }
  30974. if (this._ambientTexture) {
  30975. activeTextures.push(this._ambientTexture);
  30976. }
  30977. if (this._opacityTexture) {
  30978. activeTextures.push(this._opacityTexture);
  30979. }
  30980. if (this._reflectionTexture) {
  30981. activeTextures.push(this._reflectionTexture);
  30982. }
  30983. if (this._emissiveTexture) {
  30984. activeTextures.push(this._emissiveTexture);
  30985. }
  30986. if (this._specularTexture) {
  30987. activeTextures.push(this._specularTexture);
  30988. }
  30989. if (this._bumpTexture) {
  30990. activeTextures.push(this._bumpTexture);
  30991. }
  30992. if (this._lightmapTexture) {
  30993. activeTextures.push(this._lightmapTexture);
  30994. }
  30995. if (this._refractionTexture) {
  30996. activeTextures.push(this._refractionTexture);
  30997. }
  30998. return activeTextures;
  30999. };
  31000. StandardMaterial.prototype.hasTexture = function (texture) {
  31001. if (_super.prototype.hasTexture.call(this, texture)) {
  31002. return true;
  31003. }
  31004. if (this._diffuseTexture === texture) {
  31005. return true;
  31006. }
  31007. if (this._ambientTexture === texture) {
  31008. return true;
  31009. }
  31010. if (this._opacityTexture === texture) {
  31011. return true;
  31012. }
  31013. if (this._reflectionTexture === texture) {
  31014. return true;
  31015. }
  31016. if (this._emissiveTexture === texture) {
  31017. return true;
  31018. }
  31019. if (this._specularTexture === texture) {
  31020. return true;
  31021. }
  31022. if (this._bumpTexture === texture) {
  31023. return true;
  31024. }
  31025. if (this._lightmapTexture === texture) {
  31026. return true;
  31027. }
  31028. if (this._refractionTexture === texture) {
  31029. return true;
  31030. }
  31031. return false;
  31032. };
  31033. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31034. if (forceDisposeTextures) {
  31035. if (this._diffuseTexture) {
  31036. this._diffuseTexture.dispose();
  31037. }
  31038. if (this._ambientTexture) {
  31039. this._ambientTexture.dispose();
  31040. }
  31041. if (this._opacityTexture) {
  31042. this._opacityTexture.dispose();
  31043. }
  31044. if (this._reflectionTexture) {
  31045. this._reflectionTexture.dispose();
  31046. }
  31047. if (this._emissiveTexture) {
  31048. this._emissiveTexture.dispose();
  31049. }
  31050. if (this._specularTexture) {
  31051. this._specularTexture.dispose();
  31052. }
  31053. if (this._bumpTexture) {
  31054. this._bumpTexture.dispose();
  31055. }
  31056. if (this._lightmapTexture) {
  31057. this._lightmapTexture.dispose();
  31058. }
  31059. if (this._refractionTexture) {
  31060. this._refractionTexture.dispose();
  31061. }
  31062. }
  31063. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  31064. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  31065. }
  31066. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  31067. };
  31068. StandardMaterial.prototype.clone = function (name) {
  31069. var _this = this;
  31070. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  31071. result.name = name;
  31072. result.id = name;
  31073. return result;
  31074. };
  31075. StandardMaterial.prototype.serialize = function () {
  31076. return BABYLON.SerializationHelper.Serialize(this);
  31077. };
  31078. // Statics
  31079. StandardMaterial.Parse = function (source, scene, rootUrl) {
  31080. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  31081. };
  31082. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  31083. get: function () {
  31084. return StandardMaterial._DiffuseTextureEnabled;
  31085. },
  31086. set: function (value) {
  31087. if (StandardMaterial._DiffuseTextureEnabled === value) {
  31088. return;
  31089. }
  31090. StandardMaterial._DiffuseTextureEnabled = value;
  31091. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31092. },
  31093. enumerable: true,
  31094. configurable: true
  31095. });
  31096. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  31097. get: function () {
  31098. return StandardMaterial._AmbientTextureEnabled;
  31099. },
  31100. set: function (value) {
  31101. if (StandardMaterial._AmbientTextureEnabled === value) {
  31102. return;
  31103. }
  31104. StandardMaterial._AmbientTextureEnabled = value;
  31105. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31106. },
  31107. enumerable: true,
  31108. configurable: true
  31109. });
  31110. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  31111. get: function () {
  31112. return StandardMaterial._OpacityTextureEnabled;
  31113. },
  31114. set: function (value) {
  31115. if (StandardMaterial._OpacityTextureEnabled === value) {
  31116. return;
  31117. }
  31118. StandardMaterial._OpacityTextureEnabled = value;
  31119. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31120. },
  31121. enumerable: true,
  31122. configurable: true
  31123. });
  31124. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  31125. get: function () {
  31126. return StandardMaterial._ReflectionTextureEnabled;
  31127. },
  31128. set: function (value) {
  31129. if (StandardMaterial._ReflectionTextureEnabled === value) {
  31130. return;
  31131. }
  31132. StandardMaterial._ReflectionTextureEnabled = value;
  31133. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31134. },
  31135. enumerable: true,
  31136. configurable: true
  31137. });
  31138. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  31139. get: function () {
  31140. return StandardMaterial._EmissiveTextureEnabled;
  31141. },
  31142. set: function (value) {
  31143. if (StandardMaterial._EmissiveTextureEnabled === value) {
  31144. return;
  31145. }
  31146. StandardMaterial._EmissiveTextureEnabled = value;
  31147. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31148. },
  31149. enumerable: true,
  31150. configurable: true
  31151. });
  31152. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  31153. get: function () {
  31154. return StandardMaterial._SpecularTextureEnabled;
  31155. },
  31156. set: function (value) {
  31157. if (StandardMaterial._SpecularTextureEnabled === value) {
  31158. return;
  31159. }
  31160. StandardMaterial._SpecularTextureEnabled = value;
  31161. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31162. },
  31163. enumerable: true,
  31164. configurable: true
  31165. });
  31166. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  31167. get: function () {
  31168. return StandardMaterial._BumpTextureEnabled;
  31169. },
  31170. set: function (value) {
  31171. if (StandardMaterial._BumpTextureEnabled === value) {
  31172. return;
  31173. }
  31174. StandardMaterial._BumpTextureEnabled = value;
  31175. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31176. },
  31177. enumerable: true,
  31178. configurable: true
  31179. });
  31180. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  31181. get: function () {
  31182. return StandardMaterial._LightmapTextureEnabled;
  31183. },
  31184. set: function (value) {
  31185. if (StandardMaterial._LightmapTextureEnabled === value) {
  31186. return;
  31187. }
  31188. StandardMaterial._LightmapTextureEnabled = value;
  31189. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31190. },
  31191. enumerable: true,
  31192. configurable: true
  31193. });
  31194. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  31195. get: function () {
  31196. return StandardMaterial._RefractionTextureEnabled;
  31197. },
  31198. set: function (value) {
  31199. if (StandardMaterial._RefractionTextureEnabled === value) {
  31200. return;
  31201. }
  31202. StandardMaterial._RefractionTextureEnabled = value;
  31203. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31204. },
  31205. enumerable: true,
  31206. configurable: true
  31207. });
  31208. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  31209. get: function () {
  31210. return StandardMaterial._ColorGradingTextureEnabled;
  31211. },
  31212. set: function (value) {
  31213. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  31214. return;
  31215. }
  31216. StandardMaterial._ColorGradingTextureEnabled = value;
  31217. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31218. },
  31219. enumerable: true,
  31220. configurable: true
  31221. });
  31222. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  31223. get: function () {
  31224. return StandardMaterial._FresnelEnabled;
  31225. },
  31226. set: function (value) {
  31227. if (StandardMaterial._FresnelEnabled === value) {
  31228. return;
  31229. }
  31230. StandardMaterial._FresnelEnabled = value;
  31231. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  31232. },
  31233. enumerable: true,
  31234. configurable: true
  31235. });
  31236. // Flags used to enable or disable a type of texture for all Standard Materials
  31237. StandardMaterial._DiffuseTextureEnabled = true;
  31238. StandardMaterial._AmbientTextureEnabled = true;
  31239. StandardMaterial._OpacityTextureEnabled = true;
  31240. StandardMaterial._ReflectionTextureEnabled = true;
  31241. StandardMaterial._EmissiveTextureEnabled = true;
  31242. StandardMaterial._SpecularTextureEnabled = true;
  31243. StandardMaterial._BumpTextureEnabled = true;
  31244. StandardMaterial._LightmapTextureEnabled = true;
  31245. StandardMaterial._RefractionTextureEnabled = true;
  31246. StandardMaterial._ColorGradingTextureEnabled = true;
  31247. StandardMaterial._FresnelEnabled = true;
  31248. __decorate([
  31249. BABYLON.serializeAsTexture("diffuseTexture")
  31250. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  31251. __decorate([
  31252. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31253. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  31254. __decorate([
  31255. BABYLON.serializeAsTexture("ambientTexture")
  31256. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  31257. __decorate([
  31258. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31259. ], StandardMaterial.prototype, "ambientTexture", void 0);
  31260. __decorate([
  31261. BABYLON.serializeAsTexture("opacityTexture")
  31262. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  31263. __decorate([
  31264. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31265. ], StandardMaterial.prototype, "opacityTexture", void 0);
  31266. __decorate([
  31267. BABYLON.serializeAsTexture("reflectionTexture")
  31268. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  31269. __decorate([
  31270. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31271. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  31272. __decorate([
  31273. BABYLON.serializeAsTexture("emissiveTexture")
  31274. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  31275. __decorate([
  31276. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31277. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  31278. __decorate([
  31279. BABYLON.serializeAsTexture("specularTexture")
  31280. ], StandardMaterial.prototype, "_specularTexture", void 0);
  31281. __decorate([
  31282. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31283. ], StandardMaterial.prototype, "specularTexture", void 0);
  31284. __decorate([
  31285. BABYLON.serializeAsTexture("bumpTexture")
  31286. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  31287. __decorate([
  31288. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31289. ], StandardMaterial.prototype, "bumpTexture", void 0);
  31290. __decorate([
  31291. BABYLON.serializeAsTexture("lightmapTexture")
  31292. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  31293. __decorate([
  31294. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31295. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  31296. __decorate([
  31297. BABYLON.serializeAsTexture("refractionTexture")
  31298. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  31299. __decorate([
  31300. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31301. ], StandardMaterial.prototype, "refractionTexture", void 0);
  31302. __decorate([
  31303. BABYLON.serializeAsColor3("ambient")
  31304. ], StandardMaterial.prototype, "ambientColor", void 0);
  31305. __decorate([
  31306. BABYLON.serializeAsColor3("diffuse")
  31307. ], StandardMaterial.prototype, "diffuseColor", void 0);
  31308. __decorate([
  31309. BABYLON.serializeAsColor3("specular")
  31310. ], StandardMaterial.prototype, "specularColor", void 0);
  31311. __decorate([
  31312. BABYLON.serializeAsColor3("emissive")
  31313. ], StandardMaterial.prototype, "emissiveColor", void 0);
  31314. __decorate([
  31315. BABYLON.serialize()
  31316. ], StandardMaterial.prototype, "specularPower", void 0);
  31317. __decorate([
  31318. BABYLON.serialize("useAlphaFromDiffuseTexture")
  31319. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  31320. __decorate([
  31321. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31322. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  31323. __decorate([
  31324. BABYLON.serialize("useEmissiveAsIllumination")
  31325. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  31326. __decorate([
  31327. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31328. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  31329. __decorate([
  31330. BABYLON.serialize("linkEmissiveWithDiffuse")
  31331. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  31332. __decorate([
  31333. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31334. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  31335. __decorate([
  31336. BABYLON.serialize("useSpecularOverAlpha")
  31337. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  31338. __decorate([
  31339. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31340. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  31341. __decorate([
  31342. BABYLON.serialize("useReflectionOverAlpha")
  31343. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  31344. __decorate([
  31345. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31346. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  31347. __decorate([
  31348. BABYLON.serialize("disableLighting")
  31349. ], StandardMaterial.prototype, "_disableLighting", void 0);
  31350. __decorate([
  31351. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  31352. ], StandardMaterial.prototype, "disableLighting", void 0);
  31353. __decorate([
  31354. BABYLON.serialize("useParallax")
  31355. ], StandardMaterial.prototype, "_useParallax", void 0);
  31356. __decorate([
  31357. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31358. ], StandardMaterial.prototype, "useParallax", void 0);
  31359. __decorate([
  31360. BABYLON.serialize("useParallaxOcclusion")
  31361. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  31362. __decorate([
  31363. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31364. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  31365. __decorate([
  31366. BABYLON.serialize()
  31367. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  31368. __decorate([
  31369. BABYLON.serialize("roughness")
  31370. ], StandardMaterial.prototype, "_roughness", void 0);
  31371. __decorate([
  31372. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31373. ], StandardMaterial.prototype, "roughness", void 0);
  31374. __decorate([
  31375. BABYLON.serialize()
  31376. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  31377. __decorate([
  31378. BABYLON.serialize()
  31379. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  31380. __decorate([
  31381. BABYLON.serialize("useLightmapAsShadowmap")
  31382. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  31383. __decorate([
  31384. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31385. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  31386. __decorate([
  31387. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  31388. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  31389. __decorate([
  31390. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31391. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  31392. __decorate([
  31393. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  31394. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  31395. __decorate([
  31396. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31397. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  31398. __decorate([
  31399. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  31400. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  31401. __decorate([
  31402. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31403. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  31404. __decorate([
  31405. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  31406. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  31407. __decorate([
  31408. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31409. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  31410. __decorate([
  31411. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  31412. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  31413. __decorate([
  31414. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31415. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  31416. __decorate([
  31417. BABYLON.serialize("useReflectionFresnelFromSpecular")
  31418. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  31419. __decorate([
  31420. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31421. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  31422. __decorate([
  31423. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  31424. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  31425. __decorate([
  31426. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31427. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  31428. __decorate([
  31429. BABYLON.serialize("maxSimultaneousLights")
  31430. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  31431. __decorate([
  31432. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  31433. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  31434. __decorate([
  31435. BABYLON.serialize("invertNormalMapX")
  31436. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  31437. __decorate([
  31438. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31439. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  31440. __decorate([
  31441. BABYLON.serialize("invertNormalMapY")
  31442. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  31443. __decorate([
  31444. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31445. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  31446. __decorate([
  31447. BABYLON.serialize("twoSidedLighting")
  31448. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  31449. __decorate([
  31450. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31451. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  31452. __decorate([
  31453. BABYLON.serialize()
  31454. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  31455. return StandardMaterial;
  31456. }(BABYLON.PushMaterial));
  31457. BABYLON.StandardMaterial = StandardMaterial;
  31458. })(BABYLON || (BABYLON = {}));
  31459. //# sourceMappingURL=babylon.standardMaterial.js.map
  31460. var BABYLON;
  31461. (function (BABYLON) {
  31462. var PBRMaterialDefines = (function (_super) {
  31463. __extends(PBRMaterialDefines, _super);
  31464. function PBRMaterialDefines() {
  31465. var _this = _super.call(this) || this;
  31466. _this.PBR = true;
  31467. _this.MAINUV1 = false;
  31468. _this.MAINUV2 = false;
  31469. _this.UV1 = false;
  31470. _this.UV2 = false;
  31471. _this.ALBEDO = false;
  31472. _this.ALBEDODIRECTUV = 0;
  31473. _this.VERTEXCOLOR = false;
  31474. _this.AMBIENT = false;
  31475. _this.AMBIENTDIRECTUV = 0;
  31476. _this.AMBIENTINGRAYSCALE = false;
  31477. _this.OPACITY = false;
  31478. _this.VERTEXALPHA = false;
  31479. _this.OPACITYDIRECTUV = 0;
  31480. _this.OPACITYRGB = false;
  31481. _this.ALPHATEST = false;
  31482. _this.ALPHABLEND = false;
  31483. _this.ALPHAFROMALBEDO = false;
  31484. _this.ALPHATESTVALUE = 0.5;
  31485. _this.SPECULAROVERALPHA = false;
  31486. _this.RADIANCEOVERALPHA = false;
  31487. _this.ALPHAFRESNEL = false;
  31488. _this.PREMULTIPLYALPHA = false;
  31489. _this.EMISSIVE = false;
  31490. _this.EMISSIVEDIRECTUV = 0;
  31491. _this.REFLECTIVITY = false;
  31492. _this.REFLECTIVITYDIRECTUV = 0;
  31493. _this.SPECULARTERM = false;
  31494. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  31495. _this.MICROSURFACEAUTOMATIC = false;
  31496. _this.LODBASEDMICROSFURACE = false;
  31497. _this.MICROSURFACEMAP = false;
  31498. _this.MICROSURFACEMAPDIRECTUV = 0;
  31499. _this.METALLICWORKFLOW = false;
  31500. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  31501. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  31502. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  31503. _this.AOSTOREINMETALMAPRED = false;
  31504. _this.ENVIRONMENTBRDF = false;
  31505. _this.NORMAL = false;
  31506. _this.TANGENT = false;
  31507. _this.BUMP = false;
  31508. _this.BUMPDIRECTUV = 0;
  31509. _this.PARALLAX = false;
  31510. _this.PARALLAXOCCLUSION = false;
  31511. _this.NORMALXYSCALE = true;
  31512. _this.LIGHTMAP = false;
  31513. _this.LIGHTMAPDIRECTUV = 0;
  31514. _this.USELIGHTMAPASSHADOWMAP = false;
  31515. _this.REFLECTION = false;
  31516. _this.REFLECTIONMAP_3D = false;
  31517. _this.REFLECTIONMAP_SPHERICAL = false;
  31518. _this.REFLECTIONMAP_PLANAR = false;
  31519. _this.REFLECTIONMAP_CUBIC = false;
  31520. _this.REFLECTIONMAP_PROJECTION = false;
  31521. _this.REFLECTIONMAP_SKYBOX = false;
  31522. _this.REFLECTIONMAP_EXPLICIT = false;
  31523. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  31524. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  31525. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  31526. _this.INVERTCUBICMAP = false;
  31527. _this.USESPHERICALFROMREFLECTIONMAP = false;
  31528. _this.USESPHERICALINFRAGMENT = false;
  31529. _this.REFLECTIONMAP_OPPOSITEZ = false;
  31530. _this.LODINREFLECTIONALPHA = false;
  31531. _this.GAMMAREFLECTION = false;
  31532. _this.REFRACTION = false;
  31533. _this.REFRACTIONMAP_3D = false;
  31534. _this.REFRACTIONMAP_OPPOSITEZ = false;
  31535. _this.LODINREFRACTIONALPHA = false;
  31536. _this.GAMMAREFRACTION = false;
  31537. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  31538. _this.INSTANCES = false;
  31539. _this.NUM_BONE_INFLUENCERS = 0;
  31540. _this.BonesPerMesh = 0;
  31541. _this.MORPHTARGETS = false;
  31542. _this.MORPHTARGETS_NORMAL = false;
  31543. _this.MORPHTARGETS_TANGENT = false;
  31544. _this.NUM_MORPH_INFLUENCERS = 0;
  31545. _this.IMAGEPROCESSING = false;
  31546. _this.VIGNETTE = false;
  31547. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  31548. _this.VIGNETTEBLENDMODEOPAQUE = false;
  31549. _this.TONEMAPPING = false;
  31550. _this.CONTRAST = false;
  31551. _this.COLORCURVES = false;
  31552. _this.COLORGRADING = false;
  31553. _this.SAMPLER3DGREENDEPTH = false;
  31554. _this.SAMPLER3DBGRMAP = false;
  31555. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  31556. _this.EXPOSURE = false;
  31557. _this.USEPHYSICALLIGHTFALLOFF = false;
  31558. _this.TWOSIDEDLIGHTING = false;
  31559. _this.SHADOWFLOAT = false;
  31560. _this.USERIGHTHANDEDSYSTEM = false;
  31561. _this.CLIPPLANE = false;
  31562. _this.POINTSIZE = false;
  31563. _this.FOG = false;
  31564. _this.LOGARITHMICDEPTH = false;
  31565. _this.FORCENORMALFORWARD = false;
  31566. _this.rebuild();
  31567. return _this;
  31568. }
  31569. PBRMaterialDefines.prototype.reset = function () {
  31570. _super.prototype.reset.call(this);
  31571. this.ALPHATESTVALUE = 0.5;
  31572. this.PBR = true;
  31573. };
  31574. return PBRMaterialDefines;
  31575. }(BABYLON.MaterialDefines));
  31576. /**
  31577. * The Physically based material base class of BJS.
  31578. *
  31579. * This offers the main features of a standard PBR material.
  31580. * For more information, please refer to the documentation :
  31581. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  31582. */
  31583. var PBRBaseMaterial = (function (_super) {
  31584. __extends(PBRBaseMaterial, _super);
  31585. /**
  31586. * Instantiates a new PBRMaterial instance.
  31587. *
  31588. * @param name The material name
  31589. * @param scene The scene the material will be use in.
  31590. */
  31591. function PBRBaseMaterial(name, scene) {
  31592. var _this = _super.call(this, name, scene) || this;
  31593. /**
  31594. * Intensity of the direct lights e.g. the four lights available in your scene.
  31595. * This impacts both the direct diffuse and specular highlights.
  31596. */
  31597. _this._directIntensity = 1.0;
  31598. /**
  31599. * Intensity of the emissive part of the material.
  31600. * This helps controlling the emissive effect without modifying the emissive color.
  31601. */
  31602. _this._emissiveIntensity = 1.0;
  31603. /**
  31604. * Intensity of the environment e.g. how much the environment will light the object
  31605. * either through harmonics for rough material or through the refelction for shiny ones.
  31606. */
  31607. _this._environmentIntensity = 1.0;
  31608. /**
  31609. * This is a special control allowing the reduction of the specular highlights coming from the
  31610. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  31611. */
  31612. _this._specularIntensity = 1.0;
  31613. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  31614. /**
  31615. * Debug Control allowing disabling the bump map on this material.
  31616. */
  31617. _this._disableBumpMap = false;
  31618. /**
  31619. * AKA Occlusion Texture Intensity in other nomenclature.
  31620. */
  31621. _this._ambientTextureStrength = 1.0;
  31622. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  31623. /**
  31624. * AKA Diffuse Color in other nomenclature.
  31625. */
  31626. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  31627. /**
  31628. * AKA Specular Color in other nomenclature.
  31629. */
  31630. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  31631. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  31632. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  31633. /**
  31634. * AKA Glossiness in other nomenclature.
  31635. */
  31636. _this._microSurface = 0.9;
  31637. /**
  31638. * source material index of refraction (IOR)' / 'destination material IOR.
  31639. */
  31640. _this._indexOfRefraction = 0.66;
  31641. /**
  31642. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  31643. */
  31644. _this._invertRefractionY = false;
  31645. /**
  31646. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  31647. * Materials half opaque for instance using refraction could benefit from this control.
  31648. */
  31649. _this._linkRefractionWithTransparency = false;
  31650. _this._useLightmapAsShadowmap = false;
  31651. /**
  31652. * Specifies that the alpha is coming form the albedo channel alpha channel.
  31653. */
  31654. _this._useAlphaFromAlbedoTexture = false;
  31655. /**
  31656. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  31657. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  31658. */
  31659. _this._useSpecularOverAlpha = true;
  31660. /**
  31661. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  31662. */
  31663. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  31664. /**
  31665. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  31666. */
  31667. _this._useRoughnessFromMetallicTextureAlpha = true;
  31668. /**
  31669. * Specifies if the metallic texture contains the roughness information in its green channel.
  31670. */
  31671. _this._useRoughnessFromMetallicTextureGreen = false;
  31672. /**
  31673. * Specifies if the metallic texture contains the metallness information in its blue channel.
  31674. */
  31675. _this._useMetallnessFromMetallicTextureBlue = false;
  31676. /**
  31677. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  31678. */
  31679. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  31680. /**
  31681. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  31682. */
  31683. _this._useAmbientInGrayScale = false;
  31684. /**
  31685. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  31686. * The material will try to infer what glossiness each pixel should be.
  31687. */
  31688. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  31689. /**
  31690. * BJS is using an harcoded light falloff based on a manually sets up range.
  31691. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  31692. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  31693. */
  31694. _this._usePhysicalLightFalloff = true;
  31695. /**
  31696. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  31697. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  31698. */
  31699. _this._useRadianceOverAlpha = true;
  31700. /**
  31701. * Allows using the bump map in parallax mode.
  31702. */
  31703. _this._useParallax = false;
  31704. /**
  31705. * Allows using the bump map in parallax occlusion mode.
  31706. */
  31707. _this._useParallaxOcclusion = false;
  31708. /**
  31709. * Controls the scale bias of the parallax mode.
  31710. */
  31711. _this._parallaxScaleBias = 0.05;
  31712. /**
  31713. * If sets to true, disables all the lights affecting the material.
  31714. */
  31715. _this._disableLighting = false;
  31716. /**
  31717. * Number of Simultaneous lights allowed on the material.
  31718. */
  31719. _this._maxSimultaneousLights = 4;
  31720. /**
  31721. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  31722. */
  31723. _this._invertNormalMapX = false;
  31724. /**
  31725. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  31726. */
  31727. _this._invertNormalMapY = false;
  31728. /**
  31729. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  31730. */
  31731. _this._twoSidedLighting = false;
  31732. /**
  31733. * Defines the alpha limits in alpha test mode.
  31734. */
  31735. _this._alphaCutOff = 0.4;
  31736. /**
  31737. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  31738. */
  31739. _this._forceAlphaTest = false;
  31740. /**
  31741. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  31742. * in your scene composition.
  31743. */
  31744. _this._preMultiplyAlpha = false;
  31745. /**
  31746. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  31747. * And/Or occlude the blended part.
  31748. */
  31749. _this._useAlphaFresnel = false;
  31750. /**
  31751. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  31752. * from cos thetav and roughness:
  31753. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  31754. */
  31755. _this._environmentBRDFTexture = null;
  31756. /**
  31757. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  31758. */
  31759. _this._forceIrradianceInFragment = false;
  31760. /**
  31761. * Force normal to face away from face.
  31762. * (Temporary internal fix to remove before 3.1)
  31763. */
  31764. _this._forceNormalForward = false;
  31765. _this._renderTargets = new BABYLON.SmartArray(16);
  31766. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  31767. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  31768. _this._tempColor = new BABYLON.Color3();
  31769. // Setup the default processing configuration to the scene.
  31770. _this._attachImageProcessingConfiguration(null);
  31771. _this.getRenderTargetTextures = function () {
  31772. _this._renderTargets.reset();
  31773. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  31774. _this._renderTargets.push(_this._reflectionTexture);
  31775. }
  31776. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  31777. _this._renderTargets.push(_this._refractionTexture);
  31778. }
  31779. return _this._renderTargets;
  31780. };
  31781. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  31782. return _this;
  31783. }
  31784. /**
  31785. * Attaches a new image processing configuration to the PBR Material.
  31786. * @param configuration
  31787. */
  31788. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  31789. var _this = this;
  31790. if (configuration === this._imageProcessingConfiguration) {
  31791. return;
  31792. }
  31793. // Detaches observer.
  31794. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  31795. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  31796. }
  31797. // Pick the scene configuration if needed.
  31798. if (!configuration) {
  31799. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  31800. }
  31801. else {
  31802. this._imageProcessingConfiguration = configuration;
  31803. }
  31804. // Attaches observer.
  31805. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  31806. _this._markAllSubMeshesAsImageProcessingDirty();
  31807. });
  31808. };
  31809. PBRBaseMaterial.prototype.getClassName = function () {
  31810. return "PBRBaseMaterial";
  31811. };
  31812. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  31813. get: function () {
  31814. return this._useLogarithmicDepth;
  31815. },
  31816. set: function (value) {
  31817. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  31818. },
  31819. enumerable: true,
  31820. configurable: true
  31821. });
  31822. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  31823. if (this._linkRefractionWithTransparency) {
  31824. return false;
  31825. }
  31826. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  31827. };
  31828. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  31829. if (this._forceAlphaTest) {
  31830. return true;
  31831. }
  31832. if (this._linkRefractionWithTransparency) {
  31833. return false;
  31834. }
  31835. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  31836. };
  31837. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  31838. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  31839. };
  31840. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  31841. return this._albedoTexture;
  31842. };
  31843. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31844. if (this.isFrozen) {
  31845. if (this._wasPreviouslyReady) {
  31846. return true;
  31847. }
  31848. }
  31849. if (!subMesh._materialDefines) {
  31850. subMesh._materialDefines = new PBRMaterialDefines();
  31851. }
  31852. var scene = this.getScene();
  31853. var defines = subMesh._materialDefines;
  31854. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  31855. if (defines._renderId === scene.getRenderId()) {
  31856. return true;
  31857. }
  31858. }
  31859. var engine = scene.getEngine();
  31860. // Lights
  31861. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  31862. defines._needNormals = true;
  31863. // Textures
  31864. if (defines._areTexturesDirty) {
  31865. defines._needUVs = false;
  31866. if (scene.texturesEnabled) {
  31867. if (scene.getEngine().getCaps().textureLOD) {
  31868. defines.LODBASEDMICROSFURACE = true;
  31869. }
  31870. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  31871. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  31872. return false;
  31873. }
  31874. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  31875. }
  31876. else {
  31877. defines.ALBEDO = false;
  31878. }
  31879. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  31880. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  31881. return false;
  31882. }
  31883. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  31884. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  31885. }
  31886. else {
  31887. defines.AMBIENT = false;
  31888. }
  31889. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  31890. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  31891. return false;
  31892. }
  31893. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  31894. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  31895. }
  31896. else {
  31897. defines.OPACITY = false;
  31898. }
  31899. var reflectionTexture = this._getReflectionTexture();
  31900. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  31901. if (!reflectionTexture.isReadyOrNotBlocking()) {
  31902. return false;
  31903. }
  31904. defines.REFLECTION = true;
  31905. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  31906. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  31907. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  31908. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  31909. defines.INVERTCUBICMAP = true;
  31910. }
  31911. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  31912. switch (reflectionTexture.coordinatesMode) {
  31913. case BABYLON.Texture.CUBIC_MODE:
  31914. case BABYLON.Texture.INVCUBIC_MODE:
  31915. defines.REFLECTIONMAP_CUBIC = true;
  31916. break;
  31917. case BABYLON.Texture.EXPLICIT_MODE:
  31918. defines.REFLECTIONMAP_EXPLICIT = true;
  31919. break;
  31920. case BABYLON.Texture.PLANAR_MODE:
  31921. defines.REFLECTIONMAP_PLANAR = true;
  31922. break;
  31923. case BABYLON.Texture.PROJECTION_MODE:
  31924. defines.REFLECTIONMAP_PROJECTION = true;
  31925. break;
  31926. case BABYLON.Texture.SKYBOX_MODE:
  31927. defines.REFLECTIONMAP_SKYBOX = true;
  31928. break;
  31929. case BABYLON.Texture.SPHERICAL_MODE:
  31930. defines.REFLECTIONMAP_SPHERICAL = true;
  31931. break;
  31932. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  31933. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  31934. break;
  31935. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  31936. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  31937. break;
  31938. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  31939. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  31940. break;
  31941. }
  31942. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  31943. if (reflectionTexture.sphericalPolynomial) {
  31944. defines.USESPHERICALFROMREFLECTIONMAP = true;
  31945. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  31946. defines.USESPHERICALINFRAGMENT = true;
  31947. }
  31948. }
  31949. }
  31950. }
  31951. else {
  31952. defines.REFLECTION = false;
  31953. defines.REFLECTIONMAP_3D = false;
  31954. defines.REFLECTIONMAP_SPHERICAL = false;
  31955. defines.REFLECTIONMAP_PLANAR = false;
  31956. defines.REFLECTIONMAP_CUBIC = false;
  31957. defines.REFLECTIONMAP_PROJECTION = false;
  31958. defines.REFLECTIONMAP_SKYBOX = false;
  31959. defines.REFLECTIONMAP_EXPLICIT = false;
  31960. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  31961. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  31962. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  31963. defines.INVERTCUBICMAP = false;
  31964. defines.USESPHERICALFROMREFLECTIONMAP = false;
  31965. defines.USESPHERICALINFRAGMENT = false;
  31966. defines.REFLECTIONMAP_OPPOSITEZ = false;
  31967. defines.LODINREFLECTIONALPHA = false;
  31968. defines.GAMMAREFLECTION = false;
  31969. }
  31970. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  31971. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  31972. return false;
  31973. }
  31974. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  31975. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  31976. }
  31977. else {
  31978. defines.LIGHTMAP = false;
  31979. }
  31980. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  31981. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  31982. return false;
  31983. }
  31984. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  31985. }
  31986. else {
  31987. defines.EMISSIVE = false;
  31988. }
  31989. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  31990. if (this._metallicTexture) {
  31991. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  31992. return false;
  31993. }
  31994. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  31995. defines.METALLICWORKFLOW = true;
  31996. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  31997. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  31998. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  31999. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  32000. }
  32001. else if (this._reflectivityTexture) {
  32002. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  32003. return false;
  32004. }
  32005. defines.METALLICWORKFLOW = false;
  32006. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  32007. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  32008. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  32009. }
  32010. else {
  32011. defines.METALLICWORKFLOW = false;
  32012. defines.REFLECTIVITY = false;
  32013. }
  32014. if (this._microSurfaceTexture) {
  32015. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  32016. return false;
  32017. }
  32018. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  32019. }
  32020. else {
  32021. defines.MICROSURFACEMAP = false;
  32022. }
  32023. }
  32024. else {
  32025. defines.REFLECTIVITY = false;
  32026. defines.MICROSURFACEMAP = false;
  32027. }
  32028. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  32029. // Bump texure can not be none blocking.
  32030. if (!this._bumpTexture.isReady()) {
  32031. return false;
  32032. }
  32033. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  32034. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  32035. defines.PARALLAX = true;
  32036. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  32037. }
  32038. else {
  32039. defines.PARALLAX = false;
  32040. }
  32041. defines.USERIGHTHANDEDSYSTEM = scene.useRightHandedSystem;
  32042. }
  32043. else {
  32044. defines.BUMP = false;
  32045. }
  32046. var refractionTexture = this._getRefractionTexture();
  32047. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  32048. if (!refractionTexture.isReadyOrNotBlocking()) {
  32049. return false;
  32050. }
  32051. defines.REFRACTION = true;
  32052. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  32053. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  32054. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  32055. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  32056. if (this._linkRefractionWithTransparency) {
  32057. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  32058. }
  32059. }
  32060. else {
  32061. defines.REFRACTION = false;
  32062. }
  32063. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  32064. // This is blocking.
  32065. if (!this._environmentBRDFTexture.isReady()) {
  32066. return false;
  32067. }
  32068. defines.ENVIRONMENTBRDF = true;
  32069. }
  32070. if (this._shouldUseAlphaFromAlbedoTexture()) {
  32071. defines.ALPHAFROMALBEDO = true;
  32072. }
  32073. }
  32074. if (this._useSpecularOverAlpha) {
  32075. defines.SPECULAROVERALPHA = true;
  32076. }
  32077. if (this._usePhysicalLightFalloff) {
  32078. defines.USEPHYSICALLIGHTFALLOFF = true;
  32079. }
  32080. if (this._useRadianceOverAlpha) {
  32081. defines.RADIANCEOVERALPHA = true;
  32082. }
  32083. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  32084. defines.METALLICWORKFLOW = true;
  32085. }
  32086. if (!this.backFaceCulling && this._twoSidedLighting) {
  32087. defines.TWOSIDEDLIGHTING = true;
  32088. }
  32089. defines.ALPHATESTVALUE = this._alphaCutOff;
  32090. defines.PREMULTIPLYALPHA = this._preMultiplyAlpha;
  32091. defines.ALPHABLEND = this.needAlphaBlending();
  32092. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  32093. }
  32094. if (defines._areImageProcessingDirty) {
  32095. if (!this._imageProcessingConfiguration.isReady()) {
  32096. return false;
  32097. }
  32098. this._imageProcessingConfiguration.prepareDefines(defines);
  32099. }
  32100. defines.FORCENORMALFORWARD = this._forceNormalForward;
  32101. // Misc.
  32102. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  32103. // Values that need to be evaluated on every frame
  32104. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._forceAlphaTest);
  32105. // Attribs
  32106. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true)) {
  32107. if (mesh) {
  32108. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32109. mesh.createNormals(true);
  32110. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  32111. }
  32112. }
  32113. }
  32114. // Get correct effect
  32115. if (defines.isDirty) {
  32116. defines.markAsProcessed();
  32117. scene.resetCachedMaterial();
  32118. // Fallbacks
  32119. var fallbacks = new BABYLON.EffectFallbacks();
  32120. if (defines.ENVIRONMENTBRDF) {
  32121. fallbacks.addFallback(0, "ENVIRONMENTBRDF");
  32122. }
  32123. if (defines.REFLECTION) {
  32124. fallbacks.addFallback(0, "REFLECTION");
  32125. }
  32126. if (defines.REFRACTION) {
  32127. fallbacks.addFallback(0, "REFRACTION");
  32128. }
  32129. if (defines.REFLECTIVITY) {
  32130. fallbacks.addFallback(0, "REFLECTIVITY");
  32131. }
  32132. if (defines.BUMP) {
  32133. fallbacks.addFallback(0, "BUMP");
  32134. }
  32135. if (defines.PARALLAX) {
  32136. fallbacks.addFallback(1, "PARALLAX");
  32137. }
  32138. if (defines.PARALLAXOCCLUSION) {
  32139. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  32140. }
  32141. if (defines.SPECULAROVERALPHA) {
  32142. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  32143. }
  32144. if (defines.FOG) {
  32145. fallbacks.addFallback(1, "FOG");
  32146. }
  32147. if (defines.POINTSIZE) {
  32148. fallbacks.addFallback(0, "POINTSIZE");
  32149. }
  32150. if (defines.LOGARITHMICDEPTH) {
  32151. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  32152. }
  32153. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  32154. if (defines.SPECULARTERM) {
  32155. fallbacks.addFallback(0, "SPECULARTERM");
  32156. }
  32157. if (defines.NUM_BONE_INFLUENCERS > 0) {
  32158. fallbacks.addCPUSkinningFallback(0, mesh);
  32159. }
  32160. //Attributes
  32161. var attribs = [BABYLON.VertexBuffer.PositionKind];
  32162. if (defines.NORMAL) {
  32163. attribs.push(BABYLON.VertexBuffer.NormalKind);
  32164. }
  32165. if (defines.TANGENT) {
  32166. attribs.push(BABYLON.VertexBuffer.TangentKind);
  32167. }
  32168. if (defines.UV1) {
  32169. attribs.push(BABYLON.VertexBuffer.UVKind);
  32170. }
  32171. if (defines.UV2) {
  32172. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  32173. }
  32174. if (defines.VERTEXCOLOR) {
  32175. attribs.push(BABYLON.VertexBuffer.ColorKind);
  32176. }
  32177. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  32178. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  32179. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  32180. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  32181. "vFogInfos", "vFogColor", "pointSize",
  32182. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  32183. "mBones",
  32184. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  32185. "vLightingIntensity",
  32186. "logarithmicDepthConstant",
  32187. "vSphericalX", "vSphericalY", "vSphericalZ",
  32188. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  32189. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  32190. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  32191. "vNormalReoderParams"
  32192. ];
  32193. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  32194. "bumpSampler", "lightmapSampler", "opacitySampler",
  32195. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  32196. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  32197. "microSurfaceSampler", "environmentBrdfSampler"];
  32198. var uniformBuffers = ["Material", "Scene"];
  32199. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  32200. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  32201. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  32202. uniformsNames: uniforms,
  32203. uniformBuffersNames: uniformBuffers,
  32204. samplers: samplers,
  32205. defines: defines,
  32206. maxSimultaneousLights: this._maxSimultaneousLights
  32207. });
  32208. var onCompiled = function (effect) {
  32209. if (this.onCompiled) {
  32210. this.onCompiled(effect);
  32211. }
  32212. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  32213. }.bind(this);
  32214. var join = defines.toString();
  32215. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  32216. attributes: attribs,
  32217. uniformsNames: uniforms,
  32218. uniformBuffersNames: uniformBuffers,
  32219. samplers: samplers,
  32220. defines: join,
  32221. fallbacks: fallbacks,
  32222. onCompiled: onCompiled,
  32223. onError: this.onError,
  32224. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  32225. }, engine), defines);
  32226. this.buildUniformLayout();
  32227. }
  32228. if (!subMesh.effect.isReady()) {
  32229. return false;
  32230. }
  32231. defines._renderId = scene.getRenderId();
  32232. this._wasPreviouslyReady = true;
  32233. return true;
  32234. };
  32235. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  32236. // Order is important !
  32237. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  32238. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  32239. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  32240. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  32241. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  32242. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  32243. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  32244. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  32245. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  32246. this._uniformBuffer.addUniform("vBumpInfos", 3);
  32247. this._uniformBuffer.addUniform("albedoMatrix", 16);
  32248. this._uniformBuffer.addUniform("ambientMatrix", 16);
  32249. this._uniformBuffer.addUniform("opacityMatrix", 16);
  32250. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  32251. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  32252. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  32253. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  32254. this._uniformBuffer.addUniform("bumpMatrix", 16);
  32255. this._uniformBuffer.addUniform("vNormalReoderParams", 4);
  32256. this._uniformBuffer.addUniform("refractionMatrix", 16);
  32257. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  32258. this._uniformBuffer.addUniform("vReflectionColor", 3);
  32259. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  32260. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  32261. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  32262. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  32263. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  32264. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  32265. this._uniformBuffer.addUniform("pointSize", 1);
  32266. this._uniformBuffer.create();
  32267. };
  32268. PBRBaseMaterial.prototype.unbind = function () {
  32269. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  32270. this._uniformBuffer.setTexture("reflectionSampler", null);
  32271. }
  32272. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  32273. this._uniformBuffer.setTexture("refractionSampler", null);
  32274. }
  32275. _super.prototype.unbind.call(this);
  32276. };
  32277. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  32278. this._activeEffect.setMatrix("world", world);
  32279. };
  32280. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  32281. var scene = this.getScene();
  32282. var defines = subMesh._materialDefines;
  32283. if (!defines) {
  32284. return;
  32285. }
  32286. var effect = subMesh.effect;
  32287. this._activeEffect = effect;
  32288. // Matrices
  32289. this.bindOnlyWorldMatrix(world);
  32290. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  32291. // Bones
  32292. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  32293. if (mustRebind) {
  32294. this._uniformBuffer.bindToEffect(effect, "Material");
  32295. this.bindViewProjection(effect);
  32296. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  32297. // Texture uniforms
  32298. if (scene.texturesEnabled) {
  32299. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  32300. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  32301. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  32302. }
  32303. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  32304. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  32305. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  32306. }
  32307. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  32308. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  32309. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  32310. }
  32311. var reflectionTexture = this._getReflectionTexture();
  32312. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  32313. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  32314. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  32315. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  32316. var polynomials = reflectionTexture.sphericalPolynomial;
  32317. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  32318. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  32319. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  32320. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  32321. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  32322. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  32323. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  32324. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  32325. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  32326. }
  32327. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  32328. }
  32329. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  32330. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  32331. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  32332. }
  32333. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  32334. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  32335. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  32336. }
  32337. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  32338. if (this._metallicTexture) {
  32339. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  32340. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  32341. }
  32342. else if (this._reflectivityTexture) {
  32343. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  32344. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  32345. }
  32346. if (this._microSurfaceTexture) {
  32347. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  32348. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  32349. }
  32350. }
  32351. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  32352. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  32353. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  32354. if (scene._mirroredCameraPosition) {
  32355. 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);
  32356. }
  32357. else {
  32358. 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);
  32359. }
  32360. }
  32361. var refractionTexture = this._getRefractionTexture();
  32362. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  32363. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  32364. var depth = 1.0;
  32365. if (!refractionTexture.isCube) {
  32366. if (refractionTexture.depth) {
  32367. depth = refractionTexture.depth;
  32368. }
  32369. }
  32370. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  32371. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  32372. }
  32373. }
  32374. // Point size
  32375. if (this.pointsCloud) {
  32376. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  32377. }
  32378. // Colors
  32379. if (defines.METALLICWORKFLOW) {
  32380. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  32381. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  32382. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  32383. }
  32384. else {
  32385. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  32386. }
  32387. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  32388. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  32389. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  32390. // Misc
  32391. this._lightingInfos.x = this._directIntensity;
  32392. this._lightingInfos.y = this._emissiveIntensity;
  32393. this._lightingInfos.z = this._environmentIntensity;
  32394. this._lightingInfos.w = this._specularIntensity;
  32395. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  32396. }
  32397. // Textures
  32398. if (scene.texturesEnabled) {
  32399. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  32400. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  32401. }
  32402. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  32403. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  32404. }
  32405. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  32406. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  32407. }
  32408. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  32409. if (defines.LODBASEDMICROSFURACE) {
  32410. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  32411. }
  32412. else {
  32413. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  32414. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  32415. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  32416. }
  32417. }
  32418. if (defines.ENVIRONMENTBRDF) {
  32419. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  32420. }
  32421. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  32422. if (defines.LODBASEDMICROSFURACE) {
  32423. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  32424. }
  32425. else {
  32426. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  32427. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  32428. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  32429. }
  32430. }
  32431. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  32432. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  32433. }
  32434. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  32435. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  32436. }
  32437. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  32438. if (this._metallicTexture) {
  32439. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  32440. }
  32441. else if (this._reflectivityTexture) {
  32442. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  32443. }
  32444. if (this._microSurfaceTexture) {
  32445. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  32446. }
  32447. }
  32448. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  32449. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  32450. }
  32451. }
  32452. // Clip plane
  32453. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  32454. // Colors
  32455. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  32456. var eyePosition = scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition;
  32457. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, scene._mirroredCameraPosition ? -1 : 1);
  32458. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  32459. }
  32460. if (mustRebind || !this.isFrozen) {
  32461. // Lights
  32462. if (scene.lightsEnabled && !this._disableLighting) {
  32463. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  32464. }
  32465. // View
  32466. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  32467. this.bindView(effect);
  32468. }
  32469. // Fog
  32470. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  32471. // Morph targets
  32472. if (defines.NUM_MORPH_INFLUENCERS) {
  32473. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  32474. }
  32475. // image processing
  32476. this._imageProcessingConfiguration.bind(this._activeEffect);
  32477. // Log. depth
  32478. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  32479. }
  32480. this._uniformBuffer.update();
  32481. this._afterBind(mesh);
  32482. scene = null;
  32483. };
  32484. PBRBaseMaterial.prototype.getAnimatables = function () {
  32485. var results = [];
  32486. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  32487. results.push(this._albedoTexture);
  32488. }
  32489. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  32490. results.push(this._ambientTexture);
  32491. }
  32492. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  32493. results.push(this._opacityTexture);
  32494. }
  32495. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  32496. results.push(this._reflectionTexture);
  32497. }
  32498. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  32499. results.push(this._emissiveTexture);
  32500. }
  32501. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  32502. results.push(this._metallicTexture);
  32503. }
  32504. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  32505. results.push(this._reflectivityTexture);
  32506. }
  32507. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  32508. results.push(this._bumpTexture);
  32509. }
  32510. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  32511. results.push(this._lightmapTexture);
  32512. }
  32513. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  32514. results.push(this._refractionTexture);
  32515. }
  32516. return results;
  32517. };
  32518. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  32519. if (this._reflectionTexture) {
  32520. return this._reflectionTexture;
  32521. }
  32522. return this.getScene().environmentTexture;
  32523. };
  32524. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  32525. if (this._refractionTexture) {
  32526. return this._refractionTexture;
  32527. }
  32528. if (this._linkRefractionWithTransparency) {
  32529. return this.getScene().environmentTexture;
  32530. }
  32531. return null;
  32532. };
  32533. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  32534. if (forceDisposeTextures) {
  32535. if (this._albedoTexture) {
  32536. this._albedoTexture.dispose();
  32537. }
  32538. if (this._ambientTexture) {
  32539. this._ambientTexture.dispose();
  32540. }
  32541. if (this._opacityTexture) {
  32542. this._opacityTexture.dispose();
  32543. }
  32544. if (this._reflectionTexture) {
  32545. this._reflectionTexture.dispose();
  32546. }
  32547. if (this._environmentBRDFTexture) {
  32548. this._environmentBRDFTexture.dispose();
  32549. }
  32550. if (this._emissiveTexture) {
  32551. this._emissiveTexture.dispose();
  32552. }
  32553. if (this._metallicTexture) {
  32554. this._metallicTexture.dispose();
  32555. }
  32556. if (this._reflectivityTexture) {
  32557. this._reflectivityTexture.dispose();
  32558. }
  32559. if (this._bumpTexture) {
  32560. this._bumpTexture.dispose();
  32561. }
  32562. if (this._lightmapTexture) {
  32563. this._lightmapTexture.dispose();
  32564. }
  32565. if (this._refractionTexture) {
  32566. this._refractionTexture.dispose();
  32567. }
  32568. }
  32569. this._renderTargets.dispose();
  32570. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  32571. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  32572. }
  32573. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  32574. };
  32575. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  32576. __decorate([
  32577. BABYLON.serializeAsImageProcessingConfiguration()
  32578. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  32579. __decorate([
  32580. BABYLON.serialize()
  32581. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  32582. return PBRBaseMaterial;
  32583. }(BABYLON.PushMaterial));
  32584. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  32585. })(BABYLON || (BABYLON = {}));
  32586. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  32587. var BABYLON;
  32588. (function (BABYLON) {
  32589. var Internals;
  32590. (function (Internals) {
  32591. /**
  32592. * The Physically based simple base material of BJS.
  32593. *
  32594. * This enables better naming and convention enforcements on top of the pbrMaterial.
  32595. * It is used as the base class for both the specGloss and metalRough conventions.
  32596. */
  32597. var PBRBaseSimpleMaterial = (function (_super) {
  32598. __extends(PBRBaseSimpleMaterial, _super);
  32599. /**
  32600. * Instantiates a new PBRMaterial instance.
  32601. *
  32602. * @param name The material name
  32603. * @param scene The scene the material will be use in.
  32604. */
  32605. function PBRBaseSimpleMaterial(name, scene) {
  32606. var _this = _super.call(this, name, scene) || this;
  32607. /**
  32608. * Number of Simultaneous lights allowed on the material.
  32609. */
  32610. _this.maxSimultaneousLights = 4;
  32611. /**
  32612. * If sets to true, disables all the lights affecting the material.
  32613. */
  32614. _this.disableLighting = false;
  32615. /**
  32616. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  32617. */
  32618. _this.invertNormalMapX = false;
  32619. /**
  32620. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  32621. */
  32622. _this.invertNormalMapY = false;
  32623. /**
  32624. * Emissivie color used to self-illuminate the model.
  32625. */
  32626. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  32627. /**
  32628. * Occlusion Channel Strenght.
  32629. */
  32630. _this.occlusionStrength = 1.0;
  32631. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  32632. _this._useAmbientInGrayScale = true;
  32633. return _this;
  32634. }
  32635. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  32636. /**
  32637. * Gets the current transparency mode.
  32638. */
  32639. get: function () {
  32640. return this._transparencyMode;
  32641. },
  32642. /**
  32643. * Sets the transparency mode of the material.
  32644. */
  32645. set: function (value) {
  32646. if (this._transparencyMode === value) {
  32647. return;
  32648. }
  32649. this._transparencyMode = value;
  32650. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  32651. this._forceAlphaTest = true;
  32652. }
  32653. else {
  32654. this._forceAlphaTest = false;
  32655. }
  32656. this._markAllSubMeshesAsTexturesDirty();
  32657. },
  32658. enumerable: true,
  32659. configurable: true
  32660. });
  32661. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  32662. /**
  32663. * Gets the current double sided mode.
  32664. */
  32665. get: function () {
  32666. return this._twoSidedLighting;
  32667. },
  32668. /**
  32669. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  32670. */
  32671. set: function (value) {
  32672. if (this._twoSidedLighting === value) {
  32673. return;
  32674. }
  32675. this._twoSidedLighting = value;
  32676. this.backFaceCulling = !value;
  32677. this._markAllSubMeshesAsTexturesDirty();
  32678. },
  32679. enumerable: true,
  32680. configurable: true
  32681. });
  32682. /**
  32683. * Specifies wether or not the alpha value of the albedo texture should be used.
  32684. */
  32685. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  32686. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  32687. };
  32688. /**
  32689. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  32690. */
  32691. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  32692. if (this._linkRefractionWithTransparency) {
  32693. return false;
  32694. }
  32695. return (this.alpha < 1.0) ||
  32696. (this._shouldUseAlphaFromAlbedoTexture() &&
  32697. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  32698. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  32699. };
  32700. /**
  32701. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  32702. */
  32703. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  32704. if (this._linkRefractionWithTransparency) {
  32705. return false;
  32706. }
  32707. return this._shouldUseAlphaFromAlbedoTexture() &&
  32708. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  32709. };
  32710. /**
  32711. * Return the active textures of the material.
  32712. */
  32713. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  32714. var activeTextures = _super.prototype.getActiveTextures.call(this);
  32715. if (this.environmentTexture) {
  32716. activeTextures.push(this.environmentTexture);
  32717. }
  32718. if (this.normalTexture) {
  32719. activeTextures.push(this.normalTexture);
  32720. }
  32721. if (this.emissiveTexture) {
  32722. activeTextures.push(this.emissiveTexture);
  32723. }
  32724. if (this.occlusionTexture) {
  32725. activeTextures.push(this.occlusionTexture);
  32726. }
  32727. return activeTextures;
  32728. };
  32729. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  32730. return "PBRBaseSimpleMaterial";
  32731. };
  32732. __decorate([
  32733. BABYLON.serialize(),
  32734. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  32735. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  32736. __decorate([
  32737. BABYLON.serialize(),
  32738. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  32739. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  32740. __decorate([
  32741. BABYLON.serializeAsTexture(),
  32742. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  32743. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  32744. __decorate([
  32745. BABYLON.serialize(),
  32746. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32747. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  32748. __decorate([
  32749. BABYLON.serialize(),
  32750. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32751. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  32752. __decorate([
  32753. BABYLON.serializeAsTexture(),
  32754. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  32755. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  32756. __decorate([
  32757. BABYLON.serializeAsColor3("emissive"),
  32758. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32759. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  32760. __decorate([
  32761. BABYLON.serializeAsTexture(),
  32762. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32763. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  32764. __decorate([
  32765. BABYLON.serialize(),
  32766. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  32767. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  32768. __decorate([
  32769. BABYLON.serializeAsTexture(),
  32770. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  32771. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  32772. __decorate([
  32773. BABYLON.serialize(),
  32774. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  32775. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  32776. __decorate([
  32777. BABYLON.serialize()
  32778. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  32779. __decorate([
  32780. BABYLON.serialize()
  32781. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  32782. return PBRBaseSimpleMaterial;
  32783. }(BABYLON.PBRBaseMaterial));
  32784. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  32785. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  32786. })(BABYLON || (BABYLON = {}));
  32787. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  32788. var BABYLON;
  32789. (function (BABYLON) {
  32790. /**
  32791. * The Physically based material of BJS.
  32792. *
  32793. * This offers the main features of a standard PBR material.
  32794. * For more information, please refer to the documentation :
  32795. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  32796. */
  32797. var PBRMaterial = (function (_super) {
  32798. __extends(PBRMaterial, _super);
  32799. /**
  32800. * Instantiates a new PBRMaterial instance.
  32801. *
  32802. * @param name The material name
  32803. * @param scene The scene the material will be use in.
  32804. */
  32805. function PBRMaterial(name, scene) {
  32806. var _this = _super.call(this, name, scene) || this;
  32807. /**
  32808. * Intensity of the direct lights e.g. the four lights available in your scene.
  32809. * This impacts both the direct diffuse and specular highlights.
  32810. */
  32811. _this.directIntensity = 1.0;
  32812. /**
  32813. * Intensity of the emissive part of the material.
  32814. * This helps controlling the emissive effect without modifying the emissive color.
  32815. */
  32816. _this.emissiveIntensity = 1.0;
  32817. /**
  32818. * Intensity of the environment e.g. how much the environment will light the object
  32819. * either through harmonics for rough material or through the refelction for shiny ones.
  32820. */
  32821. _this.environmentIntensity = 1.0;
  32822. /**
  32823. * This is a special control allowing the reduction of the specular highlights coming from the
  32824. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  32825. */
  32826. _this.specularIntensity = 1.0;
  32827. /**
  32828. * Debug Control allowing disabling the bump map on this material.
  32829. */
  32830. _this.disableBumpMap = false;
  32831. /**
  32832. * AKA Occlusion Texture Intensity in other nomenclature.
  32833. */
  32834. _this.ambientTextureStrength = 1.0;
  32835. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  32836. /**
  32837. * AKA Diffuse Color in other nomenclature.
  32838. */
  32839. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  32840. /**
  32841. * AKA Specular Color in other nomenclature.
  32842. */
  32843. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  32844. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  32845. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  32846. /**
  32847. * AKA Glossiness in other nomenclature.
  32848. */
  32849. _this.microSurface = 1.0;
  32850. /**
  32851. * source material index of refraction (IOR)' / 'destination material IOR.
  32852. */
  32853. _this.indexOfRefraction = 0.66;
  32854. /**
  32855. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  32856. */
  32857. _this.invertRefractionY = false;
  32858. /**
  32859. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  32860. * Materials half opaque for instance using refraction could benefit from this control.
  32861. */
  32862. _this.linkRefractionWithTransparency = false;
  32863. _this.useLightmapAsShadowmap = false;
  32864. /**
  32865. * Specifies that the alpha is coming form the albedo channel alpha channel.
  32866. */
  32867. _this.useAlphaFromAlbedoTexture = false;
  32868. /**
  32869. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  32870. */
  32871. _this.forceAlphaTest = false;
  32872. /**
  32873. * Defines the alpha limits in alpha test mode.
  32874. */
  32875. _this.alphaCutOff = 0.4;
  32876. /**
  32877. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  32878. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  32879. */
  32880. _this.useSpecularOverAlpha = true;
  32881. /**
  32882. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  32883. */
  32884. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  32885. /**
  32886. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  32887. */
  32888. _this.useRoughnessFromMetallicTextureAlpha = true;
  32889. /**
  32890. * Specifies if the metallic texture contains the roughness information in its green channel.
  32891. */
  32892. _this.useRoughnessFromMetallicTextureGreen = false;
  32893. /**
  32894. * Specifies if the metallic texture contains the metallness information in its blue channel.
  32895. */
  32896. _this.useMetallnessFromMetallicTextureBlue = false;
  32897. /**
  32898. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  32899. */
  32900. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  32901. /**
  32902. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  32903. */
  32904. _this.useAmbientInGrayScale = false;
  32905. /**
  32906. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  32907. * The material will try to infer what glossiness each pixel should be.
  32908. */
  32909. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  32910. /**
  32911. * BJS is using an harcoded light falloff based on a manually sets up range.
  32912. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  32913. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  32914. */
  32915. _this.usePhysicalLightFalloff = true;
  32916. /**
  32917. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  32918. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  32919. */
  32920. _this.useRadianceOverAlpha = true;
  32921. /**
  32922. * Allows using the bump map in parallax mode.
  32923. */
  32924. _this.useParallax = false;
  32925. /**
  32926. * Allows using the bump map in parallax occlusion mode.
  32927. */
  32928. _this.useParallaxOcclusion = false;
  32929. /**
  32930. * Controls the scale bias of the parallax mode.
  32931. */
  32932. _this.parallaxScaleBias = 0.05;
  32933. /**
  32934. * If sets to true, disables all the lights affecting the material.
  32935. */
  32936. _this.disableLighting = false;
  32937. /**
  32938. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  32939. */
  32940. _this.forceIrradianceInFragment = false;
  32941. /**
  32942. * Number of Simultaneous lights allowed on the material.
  32943. */
  32944. _this.maxSimultaneousLights = 4;
  32945. /**
  32946. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  32947. */
  32948. _this.invertNormalMapX = false;
  32949. /**
  32950. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  32951. */
  32952. _this.invertNormalMapY = false;
  32953. /**
  32954. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  32955. */
  32956. _this.twoSidedLighting = false;
  32957. /**
  32958. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  32959. * in your scene composition.
  32960. */
  32961. _this.preMultiplyAlpha = false;
  32962. /**
  32963. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  32964. * And/Or occlude the blended part.
  32965. */
  32966. _this.useAlphaFresnel = false;
  32967. /**
  32968. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  32969. * And/Or occlude the blended part.
  32970. */
  32971. _this.environmentBRDFTexture = null;
  32972. /**
  32973. * Force normal to face away from face.
  32974. * (Temporary internal fix to remove before 3.1)
  32975. */
  32976. _this.forceNormalForward = false;
  32977. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  32978. return _this;
  32979. }
  32980. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  32981. /**
  32982. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  32983. */
  32984. get: function () {
  32985. return this._PBRMATERIAL_OPAQUE;
  32986. },
  32987. enumerable: true,
  32988. configurable: true
  32989. });
  32990. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  32991. /**
  32992. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  32993. */
  32994. get: function () {
  32995. return this._PBRMATERIAL_ALPHATEST;
  32996. },
  32997. enumerable: true,
  32998. configurable: true
  32999. });
  33000. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  33001. /**
  33002. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  33003. */
  33004. get: function () {
  33005. return this._PBRMATERIAL_ALPHABLEND;
  33006. },
  33007. enumerable: true,
  33008. configurable: true
  33009. });
  33010. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  33011. /**
  33012. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  33013. * They are also discarded below the alpha cutoff threshold to improve performances.
  33014. */
  33015. get: function () {
  33016. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  33017. },
  33018. enumerable: true,
  33019. configurable: true
  33020. });
  33021. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  33022. /**
  33023. * Gets the image processing configuration used either in this material.
  33024. */
  33025. get: function () {
  33026. return this._imageProcessingConfiguration;
  33027. },
  33028. /**
  33029. * Sets the Default image processing configuration used either in the this material.
  33030. *
  33031. * If sets to null, the scene one is in use.
  33032. */
  33033. set: function (value) {
  33034. this._attachImageProcessingConfiguration(value);
  33035. // Ensure the effect will be rebuilt.
  33036. this._markAllSubMeshesAsTexturesDirty();
  33037. },
  33038. enumerable: true,
  33039. configurable: true
  33040. });
  33041. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  33042. /**
  33043. * Gets wether the color curves effect is enabled.
  33044. */
  33045. get: function () {
  33046. return this.imageProcessingConfiguration.colorCurvesEnabled;
  33047. },
  33048. /**
  33049. * Sets wether the color curves effect is enabled.
  33050. */
  33051. set: function (value) {
  33052. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  33053. },
  33054. enumerable: true,
  33055. configurable: true
  33056. });
  33057. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  33058. /**
  33059. * Gets wether the color grading effect is enabled.
  33060. */
  33061. get: function () {
  33062. return this.imageProcessingConfiguration.colorGradingEnabled;
  33063. },
  33064. /**
  33065. * Gets wether the color grading effect is enabled.
  33066. */
  33067. set: function (value) {
  33068. this.imageProcessingConfiguration.colorGradingEnabled = value;
  33069. },
  33070. enumerable: true,
  33071. configurable: true
  33072. });
  33073. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  33074. /**
  33075. * Gets wether tonemapping is enabled or not.
  33076. */
  33077. get: function () {
  33078. return this._imageProcessingConfiguration.toneMappingEnabled;
  33079. },
  33080. /**
  33081. * Sets wether tonemapping is enabled or not
  33082. */
  33083. set: function (value) {
  33084. this._imageProcessingConfiguration.toneMappingEnabled = value;
  33085. },
  33086. enumerable: true,
  33087. configurable: true
  33088. });
  33089. ;
  33090. ;
  33091. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  33092. /**
  33093. * The camera exposure used on this material.
  33094. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  33095. * This corresponds to a photographic exposure.
  33096. */
  33097. get: function () {
  33098. return this._imageProcessingConfiguration.exposure;
  33099. },
  33100. /**
  33101. * The camera exposure used on this material.
  33102. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  33103. * This corresponds to a photographic exposure.
  33104. */
  33105. set: function (value) {
  33106. this._imageProcessingConfiguration.exposure = value;
  33107. },
  33108. enumerable: true,
  33109. configurable: true
  33110. });
  33111. ;
  33112. ;
  33113. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  33114. /**
  33115. * Gets The camera contrast used on this material.
  33116. */
  33117. get: function () {
  33118. return this._imageProcessingConfiguration.contrast;
  33119. },
  33120. /**
  33121. * Sets The camera contrast used on this material.
  33122. */
  33123. set: function (value) {
  33124. this._imageProcessingConfiguration.contrast = value;
  33125. },
  33126. enumerable: true,
  33127. configurable: true
  33128. });
  33129. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  33130. /**
  33131. * Gets the Color Grading 2D Lookup Texture.
  33132. */
  33133. get: function () {
  33134. return this._imageProcessingConfiguration.colorGradingTexture;
  33135. },
  33136. /**
  33137. * Sets the Color Grading 2D Lookup Texture.
  33138. */
  33139. set: function (value) {
  33140. this._imageProcessingConfiguration.colorGradingTexture = value;
  33141. },
  33142. enumerable: true,
  33143. configurable: true
  33144. });
  33145. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  33146. /**
  33147. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33148. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33149. * 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;
  33150. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33151. */
  33152. get: function () {
  33153. return this._imageProcessingConfiguration.colorCurves;
  33154. },
  33155. /**
  33156. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33157. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33158. * 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;
  33159. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33160. */
  33161. set: function (value) {
  33162. this._imageProcessingConfiguration.colorCurves = value;
  33163. },
  33164. enumerable: true,
  33165. configurable: true
  33166. });
  33167. PBRMaterial.prototype.getClassName = function () {
  33168. return "PBRMaterial";
  33169. };
  33170. PBRMaterial.prototype.getActiveTextures = function () {
  33171. var activeTextures = _super.prototype.getActiveTextures.call(this);
  33172. if (this._albedoTexture) {
  33173. activeTextures.push(this._albedoTexture);
  33174. }
  33175. if (this._ambientTexture) {
  33176. activeTextures.push(this._ambientTexture);
  33177. }
  33178. if (this._opacityTexture) {
  33179. activeTextures.push(this._opacityTexture);
  33180. }
  33181. if (this._reflectionTexture) {
  33182. activeTextures.push(this._reflectionTexture);
  33183. }
  33184. if (this._emissiveTexture) {
  33185. activeTextures.push(this._emissiveTexture);
  33186. }
  33187. if (this._reflectivityTexture) {
  33188. activeTextures.push(this._reflectivityTexture);
  33189. }
  33190. if (this._metallicTexture) {
  33191. activeTextures.push(this._metallicTexture);
  33192. }
  33193. if (this._microSurfaceTexture) {
  33194. activeTextures.push(this._microSurfaceTexture);
  33195. }
  33196. if (this._bumpTexture) {
  33197. activeTextures.push(this._bumpTexture);
  33198. }
  33199. if (this._lightmapTexture) {
  33200. activeTextures.push(this._lightmapTexture);
  33201. }
  33202. if (this._refractionTexture) {
  33203. activeTextures.push(this._refractionTexture);
  33204. }
  33205. return activeTextures;
  33206. };
  33207. PBRMaterial.prototype.hasTexture = function (texture) {
  33208. if (_super.prototype.hasTexture.call(this, texture)) {
  33209. return true;
  33210. }
  33211. if (this._albedoTexture === texture) {
  33212. return true;
  33213. }
  33214. if (this._ambientTexture === texture) {
  33215. return true;
  33216. }
  33217. if (this._opacityTexture === texture) {
  33218. return true;
  33219. }
  33220. if (this._reflectionTexture === texture) {
  33221. return true;
  33222. }
  33223. if (this._reflectivityTexture === texture) {
  33224. return true;
  33225. }
  33226. if (this._metallicTexture === texture) {
  33227. return true;
  33228. }
  33229. if (this._microSurfaceTexture === texture) {
  33230. return true;
  33231. }
  33232. if (this._bumpTexture === texture) {
  33233. return true;
  33234. }
  33235. if (this._lightmapTexture === texture) {
  33236. return true;
  33237. }
  33238. if (this._refractionTexture === texture) {
  33239. return true;
  33240. }
  33241. return false;
  33242. };
  33243. PBRMaterial.prototype.clone = function (name) {
  33244. var _this = this;
  33245. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  33246. };
  33247. PBRMaterial.prototype.serialize = function () {
  33248. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  33249. serializationObject.customType = "BABYLON.PBRMaterial";
  33250. return serializationObject;
  33251. };
  33252. // Statics
  33253. PBRMaterial.Parse = function (source, scene, rootUrl) {
  33254. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  33255. };
  33256. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  33257. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  33258. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  33259. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  33260. __decorate([
  33261. BABYLON.serialize(),
  33262. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33263. ], PBRMaterial.prototype, "directIntensity", void 0);
  33264. __decorate([
  33265. BABYLON.serialize(),
  33266. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33267. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  33268. __decorate([
  33269. BABYLON.serialize(),
  33270. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33271. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  33272. __decorate([
  33273. BABYLON.serialize(),
  33274. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33275. ], PBRMaterial.prototype, "specularIntensity", void 0);
  33276. __decorate([
  33277. BABYLON.serialize(),
  33278. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33279. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  33280. __decorate([
  33281. BABYLON.serializeAsTexture(),
  33282. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33283. ], PBRMaterial.prototype, "albedoTexture", void 0);
  33284. __decorate([
  33285. BABYLON.serializeAsTexture(),
  33286. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33287. ], PBRMaterial.prototype, "ambientTexture", void 0);
  33288. __decorate([
  33289. BABYLON.serialize(),
  33290. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33291. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  33292. __decorate([
  33293. BABYLON.serializeAsTexture(),
  33294. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33295. ], PBRMaterial.prototype, "opacityTexture", void 0);
  33296. __decorate([
  33297. BABYLON.serializeAsTexture(),
  33298. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33299. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  33300. __decorate([
  33301. BABYLON.serializeAsTexture(),
  33302. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33303. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  33304. __decorate([
  33305. BABYLON.serializeAsTexture(),
  33306. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33307. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  33308. __decorate([
  33309. BABYLON.serializeAsTexture(),
  33310. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33311. ], PBRMaterial.prototype, "metallicTexture", void 0);
  33312. __decorate([
  33313. BABYLON.serialize(),
  33314. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33315. ], PBRMaterial.prototype, "metallic", void 0);
  33316. __decorate([
  33317. BABYLON.serialize(),
  33318. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33319. ], PBRMaterial.prototype, "roughness", void 0);
  33320. __decorate([
  33321. BABYLON.serializeAsTexture(),
  33322. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33323. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  33324. __decorate([
  33325. BABYLON.serializeAsTexture(),
  33326. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33327. ], PBRMaterial.prototype, "bumpTexture", void 0);
  33328. __decorate([
  33329. BABYLON.serializeAsTexture(),
  33330. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  33331. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  33332. __decorate([
  33333. BABYLON.serializeAsTexture(),
  33334. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33335. ], PBRMaterial.prototype, "refractionTexture", void 0);
  33336. __decorate([
  33337. BABYLON.serializeAsColor3("ambient"),
  33338. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33339. ], PBRMaterial.prototype, "ambientColor", void 0);
  33340. __decorate([
  33341. BABYLON.serializeAsColor3("albedo"),
  33342. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33343. ], PBRMaterial.prototype, "albedoColor", void 0);
  33344. __decorate([
  33345. BABYLON.serializeAsColor3("reflectivity"),
  33346. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33347. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  33348. __decorate([
  33349. BABYLON.serializeAsColor3("reflection"),
  33350. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33351. ], PBRMaterial.prototype, "reflectionColor", void 0);
  33352. __decorate([
  33353. BABYLON.serializeAsColor3("emissive"),
  33354. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33355. ], PBRMaterial.prototype, "emissiveColor", void 0);
  33356. __decorate([
  33357. BABYLON.serialize(),
  33358. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33359. ], PBRMaterial.prototype, "microSurface", void 0);
  33360. __decorate([
  33361. BABYLON.serialize(),
  33362. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33363. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  33364. __decorate([
  33365. BABYLON.serialize(),
  33366. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33367. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  33368. __decorate([
  33369. BABYLON.serialize(),
  33370. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33371. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  33372. __decorate([
  33373. BABYLON.serialize(),
  33374. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33375. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  33376. __decorate([
  33377. BABYLON.serialize(),
  33378. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33379. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  33380. __decorate([
  33381. BABYLON.serialize(),
  33382. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33383. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  33384. __decorate([
  33385. BABYLON.serialize(),
  33386. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33387. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  33388. __decorate([
  33389. BABYLON.serialize(),
  33390. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33391. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  33392. __decorate([
  33393. BABYLON.serialize(),
  33394. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33395. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  33396. __decorate([
  33397. BABYLON.serialize(),
  33398. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33399. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  33400. __decorate([
  33401. BABYLON.serialize(),
  33402. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33403. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  33404. __decorate([
  33405. BABYLON.serialize(),
  33406. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33407. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  33408. __decorate([
  33409. BABYLON.serialize(),
  33410. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33411. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  33412. __decorate([
  33413. BABYLON.serialize(),
  33414. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33415. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  33416. __decorate([
  33417. BABYLON.serialize(),
  33418. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33419. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  33420. __decorate([
  33421. BABYLON.serialize(),
  33422. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33423. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  33424. __decorate([
  33425. BABYLON.serialize(),
  33426. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33427. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  33428. __decorate([
  33429. BABYLON.serialize(),
  33430. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33431. ], PBRMaterial.prototype, "useParallax", void 0);
  33432. __decorate([
  33433. BABYLON.serialize(),
  33434. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33435. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  33436. __decorate([
  33437. BABYLON.serialize(),
  33438. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33439. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  33440. __decorate([
  33441. BABYLON.serialize(),
  33442. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  33443. ], PBRMaterial.prototype, "disableLighting", void 0);
  33444. __decorate([
  33445. BABYLON.serialize(),
  33446. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33447. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  33448. __decorate([
  33449. BABYLON.serialize(),
  33450. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  33451. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  33452. __decorate([
  33453. BABYLON.serialize(),
  33454. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33455. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  33456. __decorate([
  33457. BABYLON.serialize(),
  33458. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33459. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  33460. __decorate([
  33461. BABYLON.serialize(),
  33462. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33463. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  33464. __decorate([
  33465. BABYLON.serialize(),
  33466. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33467. ], PBRMaterial.prototype, "preMultiplyAlpha", void 0);
  33468. __decorate([
  33469. BABYLON.serialize(),
  33470. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33471. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  33472. __decorate([
  33473. BABYLON.serializeAsTexture(),
  33474. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33475. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  33476. __decorate([
  33477. BABYLON.serialize(),
  33478. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33479. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  33480. return PBRMaterial;
  33481. }(BABYLON.PBRBaseMaterial));
  33482. BABYLON.PBRMaterial = PBRMaterial;
  33483. })(BABYLON || (BABYLON = {}));
  33484. //# sourceMappingURL=babylon.pbrMaterial.js.map
  33485. var BABYLON;
  33486. (function (BABYLON) {
  33487. /**
  33488. * The PBR material of BJS following the metal roughness convention.
  33489. *
  33490. * This fits to the PBR convention in the GLTF definition:
  33491. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  33492. */
  33493. var PBRMetallicRoughnessMaterial = (function (_super) {
  33494. __extends(PBRMetallicRoughnessMaterial, _super);
  33495. /**
  33496. * Instantiates a new PBRMetalRoughnessMaterial instance.
  33497. *
  33498. * @param name The material name
  33499. * @param scene The scene the material will be use in.
  33500. */
  33501. function PBRMetallicRoughnessMaterial(name, scene) {
  33502. var _this = _super.call(this, name, scene) || this;
  33503. _this._useRoughnessFromMetallicTextureAlpha = false;
  33504. _this._useRoughnessFromMetallicTextureGreen = true;
  33505. _this._useMetallnessFromMetallicTextureBlue = true;
  33506. return _this;
  33507. }
  33508. /**
  33509. * Return the currrent class name of the material.
  33510. */
  33511. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  33512. return "PBRMetallicRoughnessMaterial";
  33513. };
  33514. /**
  33515. * Return the active textures of the material.
  33516. */
  33517. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  33518. var activeTextures = _super.prototype.getActiveTextures.call(this);
  33519. if (this.baseTexture) {
  33520. activeTextures.push(this.baseTexture);
  33521. }
  33522. if (this.metallicRoughnessTexture) {
  33523. activeTextures.push(this.metallicRoughnessTexture);
  33524. }
  33525. return activeTextures;
  33526. };
  33527. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  33528. if (_super.prototype.hasTexture.call(this, texture)) {
  33529. return true;
  33530. }
  33531. if (this.baseTexture === texture) {
  33532. return true;
  33533. }
  33534. if (this.metallicRoughnessTexture === texture) {
  33535. return true;
  33536. }
  33537. return false;
  33538. };
  33539. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  33540. var _this = this;
  33541. return BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  33542. };
  33543. /**
  33544. * Serialize the material to a parsable JSON object.
  33545. */
  33546. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  33547. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  33548. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  33549. return serializationObject;
  33550. };
  33551. /**
  33552. * Parses a JSON object correponding to the serialize function.
  33553. */
  33554. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  33555. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  33556. };
  33557. __decorate([
  33558. BABYLON.serializeAsColor3(),
  33559. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  33560. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  33561. __decorate([
  33562. BABYLON.serializeAsTexture(),
  33563. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  33564. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  33565. __decorate([
  33566. BABYLON.serialize(),
  33567. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33568. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  33569. __decorate([
  33570. BABYLON.serialize(),
  33571. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33572. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  33573. __decorate([
  33574. BABYLON.serializeAsTexture(),
  33575. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  33576. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  33577. return PBRMetallicRoughnessMaterial;
  33578. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  33579. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  33580. })(BABYLON || (BABYLON = {}));
  33581. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  33582. var BABYLON;
  33583. (function (BABYLON) {
  33584. /**
  33585. * The PBR material of BJS following the specular glossiness convention.
  33586. *
  33587. * This fits to the PBR convention in the GLTF definition:
  33588. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  33589. */
  33590. var PBRSpecularGlossinessMaterial = (function (_super) {
  33591. __extends(PBRSpecularGlossinessMaterial, _super);
  33592. /**
  33593. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  33594. *
  33595. * @param name The material name
  33596. * @param scene The scene the material will be use in.
  33597. */
  33598. function PBRSpecularGlossinessMaterial(name, scene) {
  33599. var _this = _super.call(this, name, scene) || this;
  33600. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  33601. return _this;
  33602. }
  33603. /**
  33604. * Return the currrent class name of the material.
  33605. */
  33606. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  33607. return "PBRSpecularGlossinessMaterial";
  33608. };
  33609. /**
  33610. * Return the active textures of the material.
  33611. */
  33612. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  33613. var activeTextures = _super.prototype.getActiveTextures.call(this);
  33614. if (this.diffuseTexture) {
  33615. activeTextures.push(this.diffuseTexture);
  33616. }
  33617. if (this.specularGlossinessTexture) {
  33618. activeTextures.push(this.specularGlossinessTexture);
  33619. }
  33620. return activeTextures;
  33621. };
  33622. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  33623. if (_super.prototype.hasTexture.call(this, texture)) {
  33624. return true;
  33625. }
  33626. if (this.diffuseTexture === texture) {
  33627. return true;
  33628. }
  33629. if (this.specularGlossinessTexture === texture) {
  33630. return true;
  33631. }
  33632. return false;
  33633. };
  33634. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  33635. var _this = this;
  33636. return BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  33637. };
  33638. /**
  33639. * Serialize the material to a parsable JSON object.
  33640. */
  33641. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  33642. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  33643. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  33644. return serializationObject;
  33645. };
  33646. /**
  33647. * Parses a JSON object correponding to the serialize function.
  33648. */
  33649. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  33650. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  33651. };
  33652. __decorate([
  33653. BABYLON.serializeAsColor3("diffuse"),
  33654. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  33655. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  33656. __decorate([
  33657. BABYLON.serializeAsTexture(),
  33658. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  33659. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  33660. __decorate([
  33661. BABYLON.serializeAsColor3("specular"),
  33662. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  33663. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  33664. __decorate([
  33665. BABYLON.serialize(),
  33666. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  33667. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  33668. __decorate([
  33669. BABYLON.serializeAsTexture(),
  33670. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  33671. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  33672. return PBRSpecularGlossinessMaterial;
  33673. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  33674. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  33675. })(BABYLON || (BABYLON = {}));
  33676. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  33677. var BABYLON;
  33678. (function (BABYLON) {
  33679. BABYLON.CameraInputTypes = {};
  33680. var CameraInputsManager = (function () {
  33681. function CameraInputsManager(camera) {
  33682. this.attached = {};
  33683. this.camera = camera;
  33684. this.checkInputs = function () { };
  33685. }
  33686. CameraInputsManager.prototype.add = function (input) {
  33687. var type = input.getSimpleName();
  33688. if (this.attached[type]) {
  33689. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  33690. return;
  33691. }
  33692. this.attached[type] = input;
  33693. input.camera = this.camera;
  33694. //for checkInputs, we are dynamically creating a function
  33695. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  33696. if (input.checkInputs) {
  33697. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  33698. }
  33699. if (this.attachedElement) {
  33700. input.attachControl(this.attachedElement);
  33701. }
  33702. };
  33703. CameraInputsManager.prototype.remove = function (inputToRemove) {
  33704. for (var cam in this.attached) {
  33705. var input = this.attached[cam];
  33706. if (input === inputToRemove) {
  33707. input.detachControl(this.attachedElement);
  33708. input.camera = null;
  33709. delete this.attached[cam];
  33710. this.rebuildInputCheck();
  33711. }
  33712. }
  33713. };
  33714. CameraInputsManager.prototype.removeByType = function (inputType) {
  33715. for (var cam in this.attached) {
  33716. var input = this.attached[cam];
  33717. if (input.getClassName() === inputType) {
  33718. input.detachControl(this.attachedElement);
  33719. input.camera = null;
  33720. delete this.attached[cam];
  33721. this.rebuildInputCheck();
  33722. }
  33723. }
  33724. };
  33725. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  33726. var current = this.checkInputs;
  33727. return function () {
  33728. current();
  33729. fn();
  33730. };
  33731. };
  33732. CameraInputsManager.prototype.attachInput = function (input) {
  33733. input.attachControl(this.attachedElement, this.noPreventDefault);
  33734. };
  33735. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  33736. if (this.attachedElement) {
  33737. return;
  33738. }
  33739. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  33740. this.attachedElement = element;
  33741. this.noPreventDefault = noPreventDefault;
  33742. for (var cam in this.attached) {
  33743. var input = this.attached[cam];
  33744. this.attached[cam].attachControl(element, noPreventDefault);
  33745. }
  33746. };
  33747. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  33748. if (disconnect === void 0) { disconnect = false; }
  33749. if (this.attachedElement !== element) {
  33750. return;
  33751. }
  33752. for (var cam in this.attached) {
  33753. var input = this.attached[cam];
  33754. this.attached[cam].detachControl(element);
  33755. if (disconnect) {
  33756. this.attached[cam].camera = null;
  33757. }
  33758. }
  33759. this.attachedElement = null;
  33760. };
  33761. CameraInputsManager.prototype.rebuildInputCheck = function () {
  33762. this.checkInputs = function () { };
  33763. for (var cam in this.attached) {
  33764. var input = this.attached[cam];
  33765. if (input.checkInputs) {
  33766. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  33767. }
  33768. }
  33769. };
  33770. CameraInputsManager.prototype.clear = function () {
  33771. if (this.attachedElement) {
  33772. this.detachElement(this.attachedElement, true);
  33773. }
  33774. this.attached = {};
  33775. this.attachedElement = null;
  33776. this.checkInputs = function () { };
  33777. };
  33778. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  33779. var inputs = {};
  33780. for (var cam in this.attached) {
  33781. var input = this.attached[cam];
  33782. var res = BABYLON.SerializationHelper.Serialize(input);
  33783. inputs[input.getClassName()] = res;
  33784. }
  33785. serializedCamera.inputsmgr = inputs;
  33786. };
  33787. CameraInputsManager.prototype.parse = function (parsedCamera) {
  33788. var parsedInputs = parsedCamera.inputsmgr;
  33789. if (parsedInputs) {
  33790. this.clear();
  33791. for (var n in parsedInputs) {
  33792. var construct = BABYLON.CameraInputTypes[n];
  33793. if (construct) {
  33794. var parsedinput = parsedInputs[n];
  33795. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  33796. this.add(input);
  33797. }
  33798. }
  33799. }
  33800. else {
  33801. //2016-03-08 this part is for managing backward compatibility
  33802. for (var n in this.attached) {
  33803. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  33804. if (construct) {
  33805. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  33806. this.remove(this.attached[n]);
  33807. this.add(input);
  33808. }
  33809. }
  33810. }
  33811. };
  33812. return CameraInputsManager;
  33813. }());
  33814. BABYLON.CameraInputsManager = CameraInputsManager;
  33815. })(BABYLON || (BABYLON = {}));
  33816. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  33817. var BABYLON;
  33818. (function (BABYLON) {
  33819. var FreeCameraMouseInput = (function () {
  33820. function FreeCameraMouseInput(touchEnabled) {
  33821. if (touchEnabled === void 0) { touchEnabled = true; }
  33822. this.touchEnabled = touchEnabled;
  33823. this.buttons = [0, 1, 2];
  33824. this.angularSensibility = 2000.0;
  33825. }
  33826. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  33827. var _this = this;
  33828. var engine = this.camera.getEngine();
  33829. if (!this._pointerInput) {
  33830. this._pointerInput = function (p, s) {
  33831. var evt = p.event;
  33832. if (!_this.touchEnabled && evt.pointerType === "touch") {
  33833. return;
  33834. }
  33835. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  33836. return;
  33837. }
  33838. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  33839. try {
  33840. evt.srcElement.setPointerCapture(evt.pointerId);
  33841. }
  33842. catch (e) {
  33843. //Nothing to do with the error. Execution will continue.
  33844. }
  33845. _this.previousPosition = {
  33846. x: evt.clientX,
  33847. y: evt.clientY
  33848. };
  33849. if (!noPreventDefault) {
  33850. evt.preventDefault();
  33851. element.focus();
  33852. }
  33853. }
  33854. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  33855. try {
  33856. evt.srcElement.releasePointerCapture(evt.pointerId);
  33857. }
  33858. catch (e) {
  33859. //Nothing to do with the error.
  33860. }
  33861. _this.previousPosition = null;
  33862. if (!noPreventDefault) {
  33863. evt.preventDefault();
  33864. }
  33865. }
  33866. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  33867. if (!_this.previousPosition || engine.isPointerLock) {
  33868. return;
  33869. }
  33870. var offsetX = evt.clientX - _this.previousPosition.x;
  33871. var offsetY = evt.clientY - _this.previousPosition.y;
  33872. if (_this.camera.getScene().useRightHandedSystem) {
  33873. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  33874. }
  33875. else {
  33876. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  33877. }
  33878. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  33879. _this.previousPosition = {
  33880. x: evt.clientX,
  33881. y: evt.clientY
  33882. };
  33883. if (!noPreventDefault) {
  33884. evt.preventDefault();
  33885. }
  33886. }
  33887. };
  33888. }
  33889. this._onMouseMove = function (evt) {
  33890. if (!engine.isPointerLock) {
  33891. return;
  33892. }
  33893. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  33894. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  33895. if (_this.camera.getScene().useRightHandedSystem) {
  33896. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  33897. }
  33898. else {
  33899. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  33900. }
  33901. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  33902. _this.previousPosition = null;
  33903. if (!noPreventDefault) {
  33904. evt.preventDefault();
  33905. }
  33906. };
  33907. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  33908. element.addEventListener("mousemove", this._onMouseMove, false);
  33909. };
  33910. FreeCameraMouseInput.prototype.detachControl = function (element) {
  33911. if (this._observer && element) {
  33912. this.camera.getScene().onPointerObservable.remove(this._observer);
  33913. element.removeEventListener("mousemove", this._onMouseMove);
  33914. this._observer = null;
  33915. this._onMouseMove = null;
  33916. this.previousPosition = null;
  33917. }
  33918. };
  33919. FreeCameraMouseInput.prototype.getClassName = function () {
  33920. return "FreeCameraMouseInput";
  33921. };
  33922. FreeCameraMouseInput.prototype.getSimpleName = function () {
  33923. return "mouse";
  33924. };
  33925. __decorate([
  33926. BABYLON.serialize()
  33927. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  33928. __decorate([
  33929. BABYLON.serialize()
  33930. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  33931. return FreeCameraMouseInput;
  33932. }());
  33933. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  33934. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  33935. })(BABYLON || (BABYLON = {}));
  33936. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  33937. var BABYLON;
  33938. (function (BABYLON) {
  33939. var FreeCameraKeyboardMoveInput = (function () {
  33940. function FreeCameraKeyboardMoveInput() {
  33941. this._keys = [];
  33942. this.keysUp = [38];
  33943. this.keysDown = [40];
  33944. this.keysLeft = [37];
  33945. this.keysRight = [39];
  33946. }
  33947. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  33948. var _this = this;
  33949. if (!this._onKeyDown) {
  33950. element.tabIndex = 1;
  33951. this._onKeyDown = function (evt) {
  33952. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  33953. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  33954. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  33955. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  33956. var index = _this._keys.indexOf(evt.keyCode);
  33957. if (index === -1) {
  33958. _this._keys.push(evt.keyCode);
  33959. }
  33960. if (!noPreventDefault) {
  33961. evt.preventDefault();
  33962. }
  33963. }
  33964. };
  33965. this._onKeyUp = function (evt) {
  33966. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  33967. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  33968. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  33969. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  33970. var index = _this._keys.indexOf(evt.keyCode);
  33971. if (index >= 0) {
  33972. _this._keys.splice(index, 1);
  33973. }
  33974. if (!noPreventDefault) {
  33975. evt.preventDefault();
  33976. }
  33977. }
  33978. };
  33979. element.addEventListener("keydown", this._onKeyDown, false);
  33980. element.addEventListener("keyup", this._onKeyUp, false);
  33981. BABYLON.Tools.RegisterTopRootEvents([
  33982. { name: "blur", handler: this._onLostFocus }
  33983. ]);
  33984. }
  33985. };
  33986. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  33987. if (this._onKeyDown) {
  33988. element.removeEventListener("keydown", this._onKeyDown);
  33989. element.removeEventListener("keyup", this._onKeyUp);
  33990. BABYLON.Tools.UnregisterTopRootEvents([
  33991. { name: "blur", handler: this._onLostFocus }
  33992. ]);
  33993. this._keys = [];
  33994. this._onKeyDown = null;
  33995. this._onKeyUp = null;
  33996. }
  33997. };
  33998. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  33999. if (this._onKeyDown) {
  34000. var camera = this.camera;
  34001. // Keyboard
  34002. for (var index = 0; index < this._keys.length; index++) {
  34003. var keyCode = this._keys[index];
  34004. var speed = camera._computeLocalCameraSpeed();
  34005. if (this.keysLeft.indexOf(keyCode) !== -1) {
  34006. camera._localDirection.copyFromFloats(-speed, 0, 0);
  34007. }
  34008. else if (this.keysUp.indexOf(keyCode) !== -1) {
  34009. camera._localDirection.copyFromFloats(0, 0, speed);
  34010. }
  34011. else if (this.keysRight.indexOf(keyCode) !== -1) {
  34012. camera._localDirection.copyFromFloats(speed, 0, 0);
  34013. }
  34014. else if (this.keysDown.indexOf(keyCode) !== -1) {
  34015. camera._localDirection.copyFromFloats(0, 0, -speed);
  34016. }
  34017. if (camera.getScene().useRightHandedSystem) {
  34018. camera._localDirection.z *= -1;
  34019. }
  34020. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  34021. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  34022. camera.cameraDirection.addInPlace(camera._transformedDirection);
  34023. }
  34024. }
  34025. };
  34026. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  34027. return "FreeCameraKeyboardMoveInput";
  34028. };
  34029. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  34030. this._keys = [];
  34031. };
  34032. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  34033. return "keyboard";
  34034. };
  34035. __decorate([
  34036. BABYLON.serialize()
  34037. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  34038. __decorate([
  34039. BABYLON.serialize()
  34040. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  34041. __decorate([
  34042. BABYLON.serialize()
  34043. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  34044. __decorate([
  34045. BABYLON.serialize()
  34046. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  34047. return FreeCameraKeyboardMoveInput;
  34048. }());
  34049. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  34050. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  34051. })(BABYLON || (BABYLON = {}));
  34052. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  34053. var BABYLON;
  34054. (function (BABYLON) {
  34055. var FreeCameraInputsManager = (function (_super) {
  34056. __extends(FreeCameraInputsManager, _super);
  34057. function FreeCameraInputsManager(camera) {
  34058. return _super.call(this, camera) || this;
  34059. }
  34060. FreeCameraInputsManager.prototype.addKeyboard = function () {
  34061. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  34062. return this;
  34063. };
  34064. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  34065. if (touchEnabled === void 0) { touchEnabled = true; }
  34066. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  34067. return this;
  34068. };
  34069. FreeCameraInputsManager.prototype.addGamepad = function () {
  34070. this.add(new BABYLON.FreeCameraGamepadInput());
  34071. return this;
  34072. };
  34073. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  34074. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  34075. return this;
  34076. };
  34077. FreeCameraInputsManager.prototype.addTouch = function () {
  34078. this.add(new BABYLON.FreeCameraTouchInput());
  34079. return this;
  34080. };
  34081. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  34082. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  34083. return this;
  34084. };
  34085. return FreeCameraInputsManager;
  34086. }(BABYLON.CameraInputsManager));
  34087. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  34088. })(BABYLON || (BABYLON = {}));
  34089. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  34090. /// <reference path="babylon.camera.ts" />
  34091. var BABYLON;
  34092. (function (BABYLON) {
  34093. var TargetCamera = (function (_super) {
  34094. __extends(TargetCamera, _super);
  34095. function TargetCamera(name, position, scene) {
  34096. var _this = _super.call(this, name, position, scene) || this;
  34097. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  34098. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  34099. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  34100. _this.speed = 2.0;
  34101. _this.noRotationConstraint = false;
  34102. _this.lockedTarget = null;
  34103. _this._currentTarget = BABYLON.Vector3.Zero();
  34104. _this._viewMatrix = BABYLON.Matrix.Zero();
  34105. _this._camMatrix = BABYLON.Matrix.Zero();
  34106. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  34107. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  34108. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  34109. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  34110. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  34111. _this._lookAtTemp = BABYLON.Matrix.Zero();
  34112. _this._tempMatrix = BABYLON.Matrix.Zero();
  34113. return _this;
  34114. }
  34115. TargetCamera.prototype.getFrontPosition = function (distance) {
  34116. var direction = this.getTarget().subtract(this.position);
  34117. direction.normalize();
  34118. direction.scaleInPlace(distance);
  34119. return this.globalPosition.add(direction);
  34120. };
  34121. TargetCamera.prototype._getLockedTargetPosition = function () {
  34122. if (!this.lockedTarget) {
  34123. return null;
  34124. }
  34125. if (this.lockedTarget.absolutePosition) {
  34126. this.lockedTarget.computeWorldMatrix();
  34127. }
  34128. return this.lockedTarget.absolutePosition || this.lockedTarget;
  34129. };
  34130. TargetCamera.prototype.storeState = function () {
  34131. this._storedPosition = this.position.clone();
  34132. this._storedRotation = this.rotation.clone();
  34133. if (this.rotationQuaternion) {
  34134. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  34135. }
  34136. return _super.prototype.storeState.call(this);
  34137. };
  34138. /**
  34139. * Restored camera state. You must call storeState() first
  34140. */
  34141. TargetCamera.prototype.restoreState = function () {
  34142. if (!_super.prototype.restoreState.call(this)) {
  34143. return false;
  34144. }
  34145. this.position = this._storedPosition.clone();
  34146. this.rotation = this._storedRotation.clone();
  34147. if (this.rotationQuaternion) {
  34148. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  34149. }
  34150. this.cameraDirection.copyFromFloats(0, 0, 0);
  34151. this.cameraRotation.copyFromFloats(0, 0);
  34152. return true;
  34153. };
  34154. // Cache
  34155. TargetCamera.prototype._initCache = function () {
  34156. _super.prototype._initCache.call(this);
  34157. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  34158. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  34159. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  34160. };
  34161. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  34162. if (!ignoreParentClass) {
  34163. _super.prototype._updateCache.call(this);
  34164. }
  34165. var lockedTargetPosition = this._getLockedTargetPosition();
  34166. if (!lockedTargetPosition) {
  34167. this._cache.lockedTarget = null;
  34168. }
  34169. else {
  34170. if (!this._cache.lockedTarget) {
  34171. this._cache.lockedTarget = lockedTargetPosition.clone();
  34172. }
  34173. else {
  34174. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  34175. }
  34176. }
  34177. this._cache.rotation.copyFrom(this.rotation);
  34178. if (this.rotationQuaternion)
  34179. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  34180. };
  34181. // Synchronized
  34182. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  34183. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  34184. return false;
  34185. }
  34186. var lockedTargetPosition = this._getLockedTargetPosition();
  34187. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  34188. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  34189. };
  34190. // Methods
  34191. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  34192. var engine = this.getEngine();
  34193. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  34194. };
  34195. // Target
  34196. TargetCamera.prototype.setTarget = function (target) {
  34197. this.upVector.normalize();
  34198. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  34199. this._camMatrix.invert();
  34200. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  34201. var vDir = target.subtract(this.position);
  34202. if (vDir.x >= 0.0) {
  34203. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  34204. }
  34205. else {
  34206. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  34207. }
  34208. this.rotation.z = 0;
  34209. if (isNaN(this.rotation.x)) {
  34210. this.rotation.x = 0;
  34211. }
  34212. if (isNaN(this.rotation.y)) {
  34213. this.rotation.y = 0;
  34214. }
  34215. if (isNaN(this.rotation.z)) {
  34216. this.rotation.z = 0;
  34217. }
  34218. if (this.rotationQuaternion) {
  34219. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  34220. }
  34221. };
  34222. /**
  34223. * Return the current target position of the camera. This value is expressed in local space.
  34224. */
  34225. TargetCamera.prototype.getTarget = function () {
  34226. return this._currentTarget;
  34227. };
  34228. TargetCamera.prototype._decideIfNeedsToMove = function () {
  34229. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  34230. };
  34231. TargetCamera.prototype._updatePosition = function () {
  34232. if (this.parent) {
  34233. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  34234. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  34235. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  34236. return;
  34237. }
  34238. this.position.addInPlace(this.cameraDirection);
  34239. };
  34240. TargetCamera.prototype._checkInputs = function () {
  34241. var needToMove = this._decideIfNeedsToMove();
  34242. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  34243. // Move
  34244. if (needToMove) {
  34245. this._updatePosition();
  34246. }
  34247. // Rotate
  34248. if (needToRotate) {
  34249. this.rotation.x += this.cameraRotation.x;
  34250. this.rotation.y += this.cameraRotation.y;
  34251. //rotate, if quaternion is set and rotation was used
  34252. if (this.rotationQuaternion) {
  34253. var len = this.rotation.lengthSquared();
  34254. if (len) {
  34255. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  34256. }
  34257. }
  34258. if (!this.noRotationConstraint) {
  34259. var limit = (Math.PI / 2) * 0.95;
  34260. if (this.rotation.x > limit)
  34261. this.rotation.x = limit;
  34262. if (this.rotation.x < -limit)
  34263. this.rotation.x = -limit;
  34264. }
  34265. }
  34266. // Inertia
  34267. if (needToMove) {
  34268. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  34269. this.cameraDirection.x = 0;
  34270. }
  34271. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  34272. this.cameraDirection.y = 0;
  34273. }
  34274. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  34275. this.cameraDirection.z = 0;
  34276. }
  34277. this.cameraDirection.scaleInPlace(this.inertia);
  34278. }
  34279. if (needToRotate) {
  34280. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  34281. this.cameraRotation.x = 0;
  34282. }
  34283. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  34284. this.cameraRotation.y = 0;
  34285. }
  34286. this.cameraRotation.scaleInPlace(this.inertia);
  34287. }
  34288. _super.prototype._checkInputs.call(this);
  34289. };
  34290. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  34291. if (this.rotationQuaternion) {
  34292. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  34293. //update the up vector!
  34294. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  34295. }
  34296. else {
  34297. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  34298. }
  34299. };
  34300. TargetCamera.prototype._getViewMatrix = function () {
  34301. if (!this.lockedTarget) {
  34302. // Compute
  34303. this._updateCameraRotationMatrix();
  34304. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  34305. // Computing target and final matrix
  34306. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  34307. }
  34308. else {
  34309. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  34310. }
  34311. if (this.getScene().useRightHandedSystem) {
  34312. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  34313. }
  34314. else {
  34315. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  34316. }
  34317. return this._viewMatrix;
  34318. };
  34319. /**
  34320. * @override
  34321. * Override Camera.createRigCamera
  34322. */
  34323. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  34324. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  34325. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  34326. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  34327. if (!this.rotationQuaternion) {
  34328. this.rotationQuaternion = new BABYLON.Quaternion();
  34329. }
  34330. rigCamera._cameraRigParams = {};
  34331. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  34332. }
  34333. return rigCamera;
  34334. }
  34335. return null;
  34336. };
  34337. /**
  34338. * @override
  34339. * Override Camera._updateRigCameras
  34340. */
  34341. TargetCamera.prototype._updateRigCameras = function () {
  34342. var camLeft = this._rigCameras[0];
  34343. var camRight = this._rigCameras[1];
  34344. switch (this.cameraRigMode) {
  34345. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  34346. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  34347. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  34348. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  34349. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  34350. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  34351. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  34352. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  34353. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  34354. camLeft.setTarget(this.getTarget());
  34355. camRight.setTarget(this.getTarget());
  34356. break;
  34357. case BABYLON.Camera.RIG_MODE_VR:
  34358. if (camLeft.rotationQuaternion) {
  34359. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  34360. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  34361. }
  34362. else {
  34363. camLeft.rotation.copyFrom(this.rotation);
  34364. camRight.rotation.copyFrom(this.rotation);
  34365. }
  34366. camLeft.position.copyFrom(this.position);
  34367. camRight.position.copyFrom(this.position);
  34368. break;
  34369. }
  34370. _super.prototype._updateRigCameras.call(this);
  34371. };
  34372. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  34373. if (!this._rigCamTransformMatrix) {
  34374. this._rigCamTransformMatrix = new BABYLON.Matrix();
  34375. }
  34376. var target = this.getTarget();
  34377. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  34378. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  34379. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  34380. };
  34381. TargetCamera.prototype.getClassName = function () {
  34382. return "TargetCamera";
  34383. };
  34384. __decorate([
  34385. BABYLON.serializeAsVector3()
  34386. ], TargetCamera.prototype, "rotation", void 0);
  34387. __decorate([
  34388. BABYLON.serialize()
  34389. ], TargetCamera.prototype, "speed", void 0);
  34390. __decorate([
  34391. BABYLON.serializeAsMeshReference("lockedTargetId")
  34392. ], TargetCamera.prototype, "lockedTarget", void 0);
  34393. return TargetCamera;
  34394. }(BABYLON.Camera));
  34395. BABYLON.TargetCamera = TargetCamera;
  34396. })(BABYLON || (BABYLON = {}));
  34397. //# sourceMappingURL=babylon.targetCamera.js.map
  34398. var BABYLON;
  34399. (function (BABYLON) {
  34400. var FreeCamera = (function (_super) {
  34401. __extends(FreeCamera, _super);
  34402. function FreeCamera(name, position, scene) {
  34403. var _this = _super.call(this, name, position, scene) || this;
  34404. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  34405. _this.checkCollisions = false;
  34406. _this.applyGravity = false;
  34407. _this._needMoveForGravity = false;
  34408. _this._oldPosition = BABYLON.Vector3.Zero();
  34409. _this._diffPosition = BABYLON.Vector3.Zero();
  34410. _this._newPosition = BABYLON.Vector3.Zero();
  34411. // Collisions
  34412. _this._collisionMask = -1;
  34413. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  34414. if (collidedMesh === void 0) { collidedMesh = null; }
  34415. //TODO move this to the collision coordinator!
  34416. if (_this.getScene().workerCollisions)
  34417. newPosition.multiplyInPlace(_this._collider.radius);
  34418. var updatePosition = function (newPos) {
  34419. _this._newPosition.copyFrom(newPos);
  34420. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  34421. var oldPosition = _this.position.clone();
  34422. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  34423. _this.position.addInPlace(_this._diffPosition);
  34424. if (_this.onCollide && collidedMesh) {
  34425. _this.onCollide(collidedMesh);
  34426. }
  34427. }
  34428. };
  34429. updatePosition(newPosition);
  34430. };
  34431. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  34432. _this.inputs.addKeyboard().addMouse();
  34433. return _this;
  34434. }
  34435. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  34436. //-- begin properties for backward compatibility for inputs
  34437. get: function () {
  34438. var mouse = this.inputs.attached["mouse"];
  34439. if (mouse)
  34440. return mouse.angularSensibility;
  34441. },
  34442. set: function (value) {
  34443. var mouse = this.inputs.attached["mouse"];
  34444. if (mouse)
  34445. mouse.angularSensibility = value;
  34446. },
  34447. enumerable: true,
  34448. configurable: true
  34449. });
  34450. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  34451. get: function () {
  34452. var keyboard = this.inputs.attached["keyboard"];
  34453. if (keyboard)
  34454. return keyboard.keysUp;
  34455. },
  34456. set: function (value) {
  34457. var keyboard = this.inputs.attached["keyboard"];
  34458. if (keyboard)
  34459. keyboard.keysUp = value;
  34460. },
  34461. enumerable: true,
  34462. configurable: true
  34463. });
  34464. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  34465. get: function () {
  34466. var keyboard = this.inputs.attached["keyboard"];
  34467. if (keyboard)
  34468. return keyboard.keysDown;
  34469. },
  34470. set: function (value) {
  34471. var keyboard = this.inputs.attached["keyboard"];
  34472. if (keyboard)
  34473. keyboard.keysDown = value;
  34474. },
  34475. enumerable: true,
  34476. configurable: true
  34477. });
  34478. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  34479. get: function () {
  34480. var keyboard = this.inputs.attached["keyboard"];
  34481. if (keyboard)
  34482. return keyboard.keysLeft;
  34483. },
  34484. set: function (value) {
  34485. var keyboard = this.inputs.attached["keyboard"];
  34486. if (keyboard)
  34487. keyboard.keysLeft = value;
  34488. },
  34489. enumerable: true,
  34490. configurable: true
  34491. });
  34492. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  34493. get: function () {
  34494. var keyboard = this.inputs.attached["keyboard"];
  34495. if (keyboard)
  34496. return keyboard.keysRight;
  34497. },
  34498. set: function (value) {
  34499. var keyboard = this.inputs.attached["keyboard"];
  34500. if (keyboard)
  34501. keyboard.keysRight = value;
  34502. },
  34503. enumerable: true,
  34504. configurable: true
  34505. });
  34506. // Controls
  34507. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  34508. this.inputs.attachElement(element, noPreventDefault);
  34509. };
  34510. FreeCamera.prototype.detachControl = function (element) {
  34511. this.inputs.detachElement(element);
  34512. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  34513. this.cameraRotation = new BABYLON.Vector2(0, 0);
  34514. };
  34515. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  34516. get: function () {
  34517. return this._collisionMask;
  34518. },
  34519. set: function (mask) {
  34520. this._collisionMask = !isNaN(mask) ? mask : -1;
  34521. },
  34522. enumerable: true,
  34523. configurable: true
  34524. });
  34525. FreeCamera.prototype._collideWithWorld = function (direction) {
  34526. var globalPosition;
  34527. if (this.parent) {
  34528. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  34529. }
  34530. else {
  34531. globalPosition = this.position;
  34532. }
  34533. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  34534. if (!this._collider) {
  34535. this._collider = new BABYLON.Collider();
  34536. }
  34537. this._collider.radius = this.ellipsoid;
  34538. this._collider.collisionMask = this._collisionMask;
  34539. //no need for clone, as long as gravity is not on.
  34540. var actualDirection = direction;
  34541. //add gravity to the direction to prevent the dual-collision checking
  34542. if (this.applyGravity) {
  34543. //this prevents mending with cameraDirection, a global variable of the free camera class.
  34544. actualDirection = direction.add(this.getScene().gravity);
  34545. }
  34546. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDirection, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  34547. };
  34548. FreeCamera.prototype._checkInputs = function () {
  34549. if (!this._localDirection) {
  34550. this._localDirection = BABYLON.Vector3.Zero();
  34551. this._transformedDirection = BABYLON.Vector3.Zero();
  34552. }
  34553. this.inputs.checkInputs();
  34554. _super.prototype._checkInputs.call(this);
  34555. };
  34556. FreeCamera.prototype._decideIfNeedsToMove = function () {
  34557. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  34558. };
  34559. FreeCamera.prototype._updatePosition = function () {
  34560. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  34561. this._collideWithWorld(this.cameraDirection);
  34562. }
  34563. else {
  34564. _super.prototype._updatePosition.call(this);
  34565. }
  34566. };
  34567. FreeCamera.prototype.dispose = function () {
  34568. this.inputs.clear();
  34569. _super.prototype.dispose.call(this);
  34570. };
  34571. FreeCamera.prototype.getClassName = function () {
  34572. return "FreeCamera";
  34573. };
  34574. __decorate([
  34575. BABYLON.serializeAsVector3()
  34576. ], FreeCamera.prototype, "ellipsoid", void 0);
  34577. __decorate([
  34578. BABYLON.serialize()
  34579. ], FreeCamera.prototype, "checkCollisions", void 0);
  34580. __decorate([
  34581. BABYLON.serialize()
  34582. ], FreeCamera.prototype, "applyGravity", void 0);
  34583. return FreeCamera;
  34584. }(BABYLON.TargetCamera));
  34585. BABYLON.FreeCamera = FreeCamera;
  34586. })(BABYLON || (BABYLON = {}));
  34587. //# sourceMappingURL=babylon.freeCamera.js.map
  34588. var BABYLON;
  34589. (function (BABYLON) {
  34590. var ArcRotateCameraKeyboardMoveInput = (function () {
  34591. function ArcRotateCameraKeyboardMoveInput() {
  34592. this._keys = [];
  34593. this.keysUp = [38];
  34594. this.keysDown = [40];
  34595. this.keysLeft = [37];
  34596. this.keysRight = [39];
  34597. this.keysReset = [111];
  34598. this.panningSensibility = 50.0;
  34599. }
  34600. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  34601. var _this = this;
  34602. element.tabIndex = 1;
  34603. this._onKeyDown = function (evt) {
  34604. _this._ctrlPressed = evt.ctrlKey;
  34605. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  34606. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  34607. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  34608. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  34609. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  34610. var index = _this._keys.indexOf(evt.keyCode);
  34611. if (index === -1) {
  34612. _this._keys.push(evt.keyCode);
  34613. }
  34614. if (evt.preventDefault) {
  34615. if (!noPreventDefault) {
  34616. evt.preventDefault();
  34617. }
  34618. }
  34619. }
  34620. };
  34621. this._onKeyUp = function (evt) {
  34622. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  34623. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  34624. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  34625. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  34626. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  34627. var index = _this._keys.indexOf(evt.keyCode);
  34628. if (index >= 0) {
  34629. _this._keys.splice(index, 1);
  34630. }
  34631. if (evt.preventDefault) {
  34632. if (!noPreventDefault) {
  34633. evt.preventDefault();
  34634. }
  34635. }
  34636. }
  34637. };
  34638. this._onLostFocus = function () {
  34639. _this._keys = [];
  34640. };
  34641. this._onFocus = function () {
  34642. element.addEventListener("keydown", _this._onKeyDown, false);
  34643. element.addEventListener("keyup", _this._onKeyUp, false);
  34644. };
  34645. this._onBlur = function () {
  34646. element.removeEventListener("keydown", _this._onKeyDown);
  34647. element.removeEventListener("keyup", _this._onKeyUp);
  34648. };
  34649. element.addEventListener("focus", this._onFocus);
  34650. element.addEventListener("blur", this._onBlur);
  34651. BABYLON.Tools.RegisterTopRootEvents([
  34652. { name: "blur", handler: this._onLostFocus }
  34653. ]);
  34654. };
  34655. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  34656. if (element && this._onBlur) {
  34657. this._onBlur();
  34658. element.removeEventListener("focus", this._onFocus);
  34659. element.removeEventListener("blur", this._onBlur);
  34660. }
  34661. BABYLON.Tools.UnregisterTopRootEvents([
  34662. { name: "blur", handler: this._onLostFocus }
  34663. ]);
  34664. this._keys = [];
  34665. this._onKeyDown = null;
  34666. this._onKeyUp = null;
  34667. this._onLostFocus = null;
  34668. this._onBlur = null;
  34669. this._onFocus = null;
  34670. };
  34671. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  34672. if (this._onKeyDown) {
  34673. var camera = this.camera;
  34674. for (var index = 0; index < this._keys.length; index++) {
  34675. var keyCode = this._keys[index];
  34676. if (this.keysLeft.indexOf(keyCode) !== -1) {
  34677. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  34678. camera.inertialPanningX -= 1 / this.panningSensibility;
  34679. }
  34680. else {
  34681. camera.inertialAlphaOffset -= 0.01;
  34682. }
  34683. }
  34684. else if (this.keysUp.indexOf(keyCode) !== -1) {
  34685. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  34686. camera.inertialPanningY += 1 / this.panningSensibility;
  34687. }
  34688. else {
  34689. camera.inertialBetaOffset -= 0.01;
  34690. }
  34691. }
  34692. else if (this.keysRight.indexOf(keyCode) !== -1) {
  34693. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  34694. camera.inertialPanningX += 1 / this.panningSensibility;
  34695. }
  34696. else {
  34697. camera.inertialAlphaOffset += 0.01;
  34698. }
  34699. }
  34700. else if (this.keysDown.indexOf(keyCode) !== -1) {
  34701. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  34702. camera.inertialPanningY -= 1 / this.panningSensibility;
  34703. }
  34704. else {
  34705. camera.inertialBetaOffset += 0.01;
  34706. }
  34707. }
  34708. else if (this.keysReset.indexOf(keyCode) !== -1) {
  34709. camera.restoreState();
  34710. }
  34711. }
  34712. }
  34713. };
  34714. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  34715. return "ArcRotateCameraKeyboardMoveInput";
  34716. };
  34717. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  34718. return "keyboard";
  34719. };
  34720. __decorate([
  34721. BABYLON.serialize()
  34722. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  34723. __decorate([
  34724. BABYLON.serialize()
  34725. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  34726. __decorate([
  34727. BABYLON.serialize()
  34728. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  34729. __decorate([
  34730. BABYLON.serialize()
  34731. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  34732. __decorate([
  34733. BABYLON.serialize()
  34734. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  34735. __decorate([
  34736. BABYLON.serialize()
  34737. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  34738. return ArcRotateCameraKeyboardMoveInput;
  34739. }());
  34740. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  34741. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  34742. })(BABYLON || (BABYLON = {}));
  34743. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  34744. var BABYLON;
  34745. (function (BABYLON) {
  34746. var ArcRotateCameraMouseWheelInput = (function () {
  34747. function ArcRotateCameraMouseWheelInput() {
  34748. this.wheelPrecision = 3.0;
  34749. }
  34750. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  34751. var _this = this;
  34752. this._wheel = function (p, s) {
  34753. //sanity check - this should be a PointerWheel event.
  34754. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  34755. return;
  34756. var event = p.event;
  34757. var delta = 0;
  34758. if (event.wheelDelta) {
  34759. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  34760. }
  34761. else if (event.detail) {
  34762. delta = -event.detail / _this.wheelPrecision;
  34763. }
  34764. if (delta)
  34765. _this.camera.inertialRadiusOffset += delta;
  34766. if (event.preventDefault) {
  34767. if (!noPreventDefault) {
  34768. event.preventDefault();
  34769. }
  34770. }
  34771. };
  34772. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  34773. };
  34774. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  34775. if (this._observer && element) {
  34776. this.camera.getScene().onPointerObservable.remove(this._observer);
  34777. this._observer = null;
  34778. this._wheel = null;
  34779. }
  34780. };
  34781. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  34782. return "ArcRotateCameraMouseWheelInput";
  34783. };
  34784. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  34785. return "mousewheel";
  34786. };
  34787. __decorate([
  34788. BABYLON.serialize()
  34789. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  34790. return ArcRotateCameraMouseWheelInput;
  34791. }());
  34792. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  34793. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  34794. })(BABYLON || (BABYLON = {}));
  34795. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  34796. var BABYLON;
  34797. (function (BABYLON) {
  34798. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  34799. var ArcRotateCameraPointersInput = (function () {
  34800. function ArcRotateCameraPointersInput() {
  34801. this.buttons = [0, 1, 2];
  34802. this.angularSensibilityX = 1000.0;
  34803. this.angularSensibilityY = 1000.0;
  34804. this.pinchPrecision = 6.0;
  34805. this.panningSensibility = 50.0;
  34806. this._isPanClick = false;
  34807. this.pinchInwards = true;
  34808. }
  34809. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  34810. var _this = this;
  34811. var engine = this.camera.getEngine();
  34812. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  34813. var pointA, pointB;
  34814. var previousPinchDistance = 0;
  34815. this._pointerInput = function (p, s) {
  34816. var evt = p.event;
  34817. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  34818. return;
  34819. }
  34820. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  34821. try {
  34822. evt.srcElement.setPointerCapture(evt.pointerId);
  34823. }
  34824. catch (e) {
  34825. //Nothing to do with the error. Execution will continue.
  34826. }
  34827. // Manage panning with pan button click
  34828. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  34829. // manage pointers
  34830. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  34831. if (pointA === undefined) {
  34832. pointA = cacheSoloPointer;
  34833. }
  34834. else if (pointB === undefined) {
  34835. pointB = cacheSoloPointer;
  34836. }
  34837. if (!noPreventDefault) {
  34838. evt.preventDefault();
  34839. element.focus();
  34840. }
  34841. }
  34842. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  34843. _this.camera.restoreState();
  34844. }
  34845. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  34846. try {
  34847. evt.srcElement.releasePointerCapture(evt.pointerId);
  34848. }
  34849. catch (e) {
  34850. //Nothing to do with the error.
  34851. }
  34852. cacheSoloPointer = null;
  34853. previousPinchDistance = 0;
  34854. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  34855. //but emptying completly pointers collection is required to fix a bug on iPhone :
  34856. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  34857. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  34858. pointA = pointB = undefined;
  34859. if (!noPreventDefault) {
  34860. evt.preventDefault();
  34861. }
  34862. }
  34863. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  34864. if (!noPreventDefault) {
  34865. evt.preventDefault();
  34866. }
  34867. // One button down
  34868. if (pointA && pointB === undefined) {
  34869. if (_this.panningSensibility !== 0 &&
  34870. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  34871. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  34872. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  34873. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  34874. }
  34875. else {
  34876. var offsetX = evt.clientX - cacheSoloPointer.x;
  34877. var offsetY = evt.clientY - cacheSoloPointer.y;
  34878. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  34879. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  34880. }
  34881. cacheSoloPointer.x = evt.clientX;
  34882. cacheSoloPointer.y = evt.clientY;
  34883. }
  34884. else if (pointA && pointB) {
  34885. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  34886. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  34887. ed.x = evt.clientX;
  34888. ed.y = evt.clientY;
  34889. var direction = _this.pinchInwards ? 1 : -1;
  34890. var distX = pointA.x - pointB.x;
  34891. var distY = pointA.y - pointB.y;
  34892. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  34893. if (previousPinchDistance === 0) {
  34894. previousPinchDistance = pinchSquaredDistance;
  34895. return;
  34896. }
  34897. if (pinchSquaredDistance !== previousPinchDistance) {
  34898. _this.camera
  34899. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  34900. (_this.pinchPrecision *
  34901. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  34902. direction);
  34903. previousPinchDistance = pinchSquaredDistance;
  34904. }
  34905. }
  34906. }
  34907. };
  34908. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  34909. this._onContextMenu = function (evt) {
  34910. evt.preventDefault();
  34911. };
  34912. if (!this.camera._useCtrlForPanning) {
  34913. element.addEventListener("contextmenu", this._onContextMenu, false);
  34914. }
  34915. this._onLostFocus = function () {
  34916. //this._keys = [];
  34917. pointA = pointB = undefined;
  34918. previousPinchDistance = 0;
  34919. cacheSoloPointer = null;
  34920. };
  34921. this._onMouseMove = function (evt) {
  34922. if (!engine.isPointerLock) {
  34923. return;
  34924. }
  34925. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  34926. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  34927. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  34928. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  34929. if (!noPreventDefault) {
  34930. evt.preventDefault();
  34931. }
  34932. };
  34933. this._onGestureStart = function (e) {
  34934. if (window.MSGesture === undefined) {
  34935. return;
  34936. }
  34937. if (!_this._MSGestureHandler) {
  34938. _this._MSGestureHandler = new MSGesture();
  34939. _this._MSGestureHandler.target = element;
  34940. }
  34941. _this._MSGestureHandler.addPointer(e.pointerId);
  34942. };
  34943. this._onGesture = function (e) {
  34944. _this.camera.radius *= e.scale;
  34945. if (e.preventDefault) {
  34946. if (!noPreventDefault) {
  34947. e.stopPropagation();
  34948. e.preventDefault();
  34949. }
  34950. }
  34951. };
  34952. element.addEventListener("mousemove", this._onMouseMove, false);
  34953. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  34954. element.addEventListener("MSGestureChange", this._onGesture, false);
  34955. BABYLON.Tools.RegisterTopRootEvents([
  34956. { name: "blur", handler: this._onLostFocus }
  34957. ]);
  34958. };
  34959. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  34960. BABYLON.Tools.UnregisterTopRootEvents([
  34961. { name: "blur", handler: this._onLostFocus }
  34962. ]);
  34963. if (element && this._observer) {
  34964. this.camera.getScene().onPointerObservable.remove(this._observer);
  34965. this._observer = null;
  34966. element.removeEventListener("contextmenu", this._onContextMenu);
  34967. element.removeEventListener("mousemove", this._onMouseMove);
  34968. element.removeEventListener("MSPointerDown", this._onGestureStart);
  34969. element.removeEventListener("MSGestureChange", this._onGesture);
  34970. this._isPanClick = false;
  34971. this.pinchInwards = true;
  34972. this._onMouseMove = null;
  34973. this._onGestureStart = null;
  34974. this._onGesture = null;
  34975. this._MSGestureHandler = null;
  34976. this._onLostFocus = null;
  34977. this._onContextMenu = null;
  34978. }
  34979. };
  34980. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  34981. return "ArcRotateCameraPointersInput";
  34982. };
  34983. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  34984. return "pointers";
  34985. };
  34986. __decorate([
  34987. BABYLON.serialize()
  34988. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  34989. __decorate([
  34990. BABYLON.serialize()
  34991. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  34992. __decorate([
  34993. BABYLON.serialize()
  34994. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  34995. __decorate([
  34996. BABYLON.serialize()
  34997. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  34998. __decorate([
  34999. BABYLON.serialize()
  35000. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  35001. return ArcRotateCameraPointersInput;
  35002. }());
  35003. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  35004. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  35005. })(BABYLON || (BABYLON = {}));
  35006. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  35007. /// <reference path="babylon.targetCamera.ts" />
  35008. /// <reference path="..\Tools\babylon.tools.ts" />
  35009. var BABYLON;
  35010. (function (BABYLON) {
  35011. var ArcRotateCamera = (function (_super) {
  35012. __extends(ArcRotateCamera, _super);
  35013. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  35014. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  35015. _this.inertialAlphaOffset = 0;
  35016. _this.inertialBetaOffset = 0;
  35017. _this.inertialRadiusOffset = 0;
  35018. _this.lowerAlphaLimit = null;
  35019. _this.upperAlphaLimit = null;
  35020. _this.lowerBetaLimit = 0.01;
  35021. _this.upperBetaLimit = Math.PI;
  35022. _this.lowerRadiusLimit = null;
  35023. _this.upperRadiusLimit = null;
  35024. _this.inertialPanningX = 0;
  35025. _this.inertialPanningY = 0;
  35026. _this.panningInertia = 0.9;
  35027. //-- end properties for backward compatibility for inputs
  35028. _this.zoomOnFactor = 1;
  35029. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  35030. _this.allowUpsideDown = true;
  35031. _this._viewMatrix = new BABYLON.Matrix();
  35032. // Panning
  35033. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  35034. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  35035. _this.checkCollisions = false;
  35036. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  35037. _this._previousPosition = BABYLON.Vector3.Zero();
  35038. _this._collisionVelocity = BABYLON.Vector3.Zero();
  35039. _this._newPosition = BABYLON.Vector3.Zero();
  35040. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  35041. if (collidedMesh === void 0) { collidedMesh = null; }
  35042. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  35043. newPosition.multiplyInPlace(_this._collider.radius);
  35044. }
  35045. if (!collidedMesh) {
  35046. _this._previousPosition.copyFrom(_this.position);
  35047. }
  35048. else {
  35049. _this.setPosition(newPosition);
  35050. if (_this.onCollide) {
  35051. _this.onCollide(collidedMesh);
  35052. }
  35053. }
  35054. // Recompute because of constraints
  35055. var cosa = Math.cos(_this.alpha);
  35056. var sina = Math.sin(_this.alpha);
  35057. var cosb = Math.cos(_this.beta);
  35058. var sinb = Math.sin(_this.beta);
  35059. if (sinb === 0) {
  35060. sinb = 0.0001;
  35061. }
  35062. var target = _this._getTargetPosition();
  35063. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  35064. _this.position.copyFrom(_this._newPosition);
  35065. var up = _this.upVector;
  35066. if (_this.allowUpsideDown && _this.beta < 0) {
  35067. up = up.clone();
  35068. up = up.negate();
  35069. }
  35070. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  35071. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  35072. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  35073. _this._collisionTriggered = false;
  35074. };
  35075. _this._target = BABYLON.Vector3.Zero();
  35076. if (target) {
  35077. _this.setTarget(target);
  35078. }
  35079. _this.alpha = alpha;
  35080. _this.beta = beta;
  35081. _this.radius = radius;
  35082. _this.getViewMatrix();
  35083. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  35084. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  35085. return _this;
  35086. }
  35087. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  35088. get: function () {
  35089. return this._target;
  35090. },
  35091. set: function (value) {
  35092. this.setTarget(value);
  35093. },
  35094. enumerable: true,
  35095. configurable: true
  35096. });
  35097. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  35098. //-- begin properties for backward compatibility for inputs
  35099. get: function () {
  35100. var pointers = this.inputs.attached["pointers"];
  35101. if (pointers)
  35102. return pointers.angularSensibilityX;
  35103. },
  35104. set: function (value) {
  35105. var pointers = this.inputs.attached["pointers"];
  35106. if (pointers) {
  35107. pointers.angularSensibilityX = value;
  35108. }
  35109. },
  35110. enumerable: true,
  35111. configurable: true
  35112. });
  35113. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  35114. get: function () {
  35115. var pointers = this.inputs.attached["pointers"];
  35116. if (pointers)
  35117. return pointers.angularSensibilityY;
  35118. },
  35119. set: function (value) {
  35120. var pointers = this.inputs.attached["pointers"];
  35121. if (pointers) {
  35122. pointers.angularSensibilityY = value;
  35123. }
  35124. },
  35125. enumerable: true,
  35126. configurable: true
  35127. });
  35128. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  35129. get: function () {
  35130. var pointers = this.inputs.attached["pointers"];
  35131. if (pointers)
  35132. return pointers.pinchPrecision;
  35133. },
  35134. set: function (value) {
  35135. var pointers = this.inputs.attached["pointers"];
  35136. if (pointers) {
  35137. pointers.pinchPrecision = value;
  35138. }
  35139. },
  35140. enumerable: true,
  35141. configurable: true
  35142. });
  35143. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  35144. get: function () {
  35145. var pointers = this.inputs.attached["pointers"];
  35146. if (pointers)
  35147. return pointers.panningSensibility;
  35148. },
  35149. set: function (value) {
  35150. var pointers = this.inputs.attached["pointers"];
  35151. if (pointers) {
  35152. pointers.panningSensibility = value;
  35153. }
  35154. },
  35155. enumerable: true,
  35156. configurable: true
  35157. });
  35158. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  35159. get: function () {
  35160. var keyboard = this.inputs.attached["keyboard"];
  35161. if (keyboard)
  35162. return keyboard.keysUp;
  35163. },
  35164. set: function (value) {
  35165. var keyboard = this.inputs.attached["keyboard"];
  35166. if (keyboard)
  35167. keyboard.keysUp = value;
  35168. },
  35169. enumerable: true,
  35170. configurable: true
  35171. });
  35172. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  35173. get: function () {
  35174. var keyboard = this.inputs.attached["keyboard"];
  35175. if (keyboard)
  35176. return keyboard.keysDown;
  35177. },
  35178. set: function (value) {
  35179. var keyboard = this.inputs.attached["keyboard"];
  35180. if (keyboard)
  35181. keyboard.keysDown = value;
  35182. },
  35183. enumerable: true,
  35184. configurable: true
  35185. });
  35186. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  35187. get: function () {
  35188. var keyboard = this.inputs.attached["keyboard"];
  35189. if (keyboard)
  35190. return keyboard.keysLeft;
  35191. },
  35192. set: function (value) {
  35193. var keyboard = this.inputs.attached["keyboard"];
  35194. if (keyboard)
  35195. keyboard.keysLeft = value;
  35196. },
  35197. enumerable: true,
  35198. configurable: true
  35199. });
  35200. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  35201. get: function () {
  35202. var keyboard = this.inputs.attached["keyboard"];
  35203. if (keyboard)
  35204. return keyboard.keysRight;
  35205. },
  35206. set: function (value) {
  35207. var keyboard = this.inputs.attached["keyboard"];
  35208. if (keyboard)
  35209. keyboard.keysRight = value;
  35210. },
  35211. enumerable: true,
  35212. configurable: true
  35213. });
  35214. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  35215. get: function () {
  35216. var mousewheel = this.inputs.attached["mousewheel"];
  35217. if (mousewheel)
  35218. return mousewheel.wheelPrecision;
  35219. },
  35220. set: function (value) {
  35221. var mousewheel = this.inputs.attached["mousewheel"];
  35222. if (mousewheel)
  35223. mousewheel.wheelPrecision = value;
  35224. },
  35225. enumerable: true,
  35226. configurable: true
  35227. });
  35228. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  35229. get: function () {
  35230. return this._bouncingBehavior;
  35231. },
  35232. enumerable: true,
  35233. configurable: true
  35234. });
  35235. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  35236. get: function () {
  35237. return this._bouncingBehavior != null;
  35238. },
  35239. set: function (value) {
  35240. if (value === this.useBouncingBehavior) {
  35241. return;
  35242. }
  35243. if (value) {
  35244. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  35245. this.addBehavior(this._bouncingBehavior);
  35246. }
  35247. else {
  35248. this.removeBehavior(this._bouncingBehavior);
  35249. this._bouncingBehavior = null;
  35250. }
  35251. },
  35252. enumerable: true,
  35253. configurable: true
  35254. });
  35255. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  35256. get: function () {
  35257. return this._framingBehavior;
  35258. },
  35259. enumerable: true,
  35260. configurable: true
  35261. });
  35262. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  35263. get: function () {
  35264. return this._framingBehavior != null;
  35265. },
  35266. set: function (value) {
  35267. if (value === this.useFramingBehavior) {
  35268. return;
  35269. }
  35270. if (value) {
  35271. this._framingBehavior = new BABYLON.FramingBehavior();
  35272. this.addBehavior(this._framingBehavior);
  35273. }
  35274. else {
  35275. this.removeBehavior(this._framingBehavior);
  35276. this._framingBehavior = null;
  35277. }
  35278. },
  35279. enumerable: true,
  35280. configurable: true
  35281. });
  35282. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  35283. get: function () {
  35284. return this._autoRotationBehavior;
  35285. },
  35286. enumerable: true,
  35287. configurable: true
  35288. });
  35289. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  35290. get: function () {
  35291. return this._autoRotationBehavior != null;
  35292. },
  35293. set: function (value) {
  35294. if (value === this.useAutoRotationBehavior) {
  35295. return;
  35296. }
  35297. if (value) {
  35298. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  35299. this.addBehavior(this._autoRotationBehavior);
  35300. }
  35301. else {
  35302. this.removeBehavior(this._autoRotationBehavior);
  35303. this._autoRotationBehavior = null;
  35304. }
  35305. },
  35306. enumerable: true,
  35307. configurable: true
  35308. });
  35309. // Cache
  35310. ArcRotateCamera.prototype._initCache = function () {
  35311. _super.prototype._initCache.call(this);
  35312. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  35313. this._cache.alpha = undefined;
  35314. this._cache.beta = undefined;
  35315. this._cache.radius = undefined;
  35316. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  35317. };
  35318. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  35319. if (!ignoreParentClass) {
  35320. _super.prototype._updateCache.call(this);
  35321. }
  35322. this._cache._target.copyFrom(this._getTargetPosition());
  35323. this._cache.alpha = this.alpha;
  35324. this._cache.beta = this.beta;
  35325. this._cache.radius = this.radius;
  35326. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  35327. };
  35328. ArcRotateCamera.prototype._getTargetPosition = function () {
  35329. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  35330. var pos = this._targetHost.getAbsolutePosition();
  35331. if (this._targetBoundingCenter) {
  35332. pos.addToRef(this._targetBoundingCenter, this._target);
  35333. }
  35334. else {
  35335. this._target.copyFrom(pos);
  35336. }
  35337. }
  35338. var lockedTargetPosition = this._getLockedTargetPosition();
  35339. if (lockedTargetPosition) {
  35340. return lockedTargetPosition;
  35341. }
  35342. return this._target;
  35343. };
  35344. ArcRotateCamera.prototype.storeState = function () {
  35345. this._storedAlpha = this.alpha;
  35346. this._storedBeta = this.beta;
  35347. this._storedRadius = this.radius;
  35348. this._storedTarget = this._getTargetPosition().clone();
  35349. return _super.prototype.storeState.call(this);
  35350. };
  35351. /**
  35352. * Restored camera state. You must call storeState() first
  35353. */
  35354. ArcRotateCamera.prototype.restoreState = function () {
  35355. if (!_super.prototype.restoreState.call(this)) {
  35356. return false;
  35357. }
  35358. this.alpha = this._storedAlpha;
  35359. this.beta = this._storedBeta;
  35360. this.radius = this._storedRadius;
  35361. this.setTarget(this._storedTarget);
  35362. this.inertialAlphaOffset = 0;
  35363. this.inertialBetaOffset = 0;
  35364. this.inertialRadiusOffset = 0;
  35365. this.inertialPanningX = 0;
  35366. this.inertialPanningY = 0;
  35367. return true;
  35368. };
  35369. // Synchronized
  35370. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  35371. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  35372. return false;
  35373. return this._cache._target.equals(this._getTargetPosition())
  35374. && this._cache.alpha === this.alpha
  35375. && this._cache.beta === this.beta
  35376. && this._cache.radius === this.radius
  35377. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  35378. };
  35379. // Methods
  35380. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  35381. var _this = this;
  35382. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  35383. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  35384. this._useCtrlForPanning = useCtrlForPanning;
  35385. this._panningMouseButton = panningMouseButton;
  35386. this.inputs.attachElement(element, noPreventDefault);
  35387. this._reset = function () {
  35388. _this.inertialAlphaOffset = 0;
  35389. _this.inertialBetaOffset = 0;
  35390. _this.inertialRadiusOffset = 0;
  35391. _this.inertialPanningX = 0;
  35392. _this.inertialPanningY = 0;
  35393. };
  35394. };
  35395. ArcRotateCamera.prototype.detachControl = function (element) {
  35396. this.inputs.detachElement(element);
  35397. if (this._reset) {
  35398. this._reset();
  35399. }
  35400. };
  35401. ArcRotateCamera.prototype._checkInputs = function () {
  35402. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  35403. if (this._collisionTriggered) {
  35404. return;
  35405. }
  35406. this.inputs.checkInputs();
  35407. // Inertia
  35408. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  35409. if (this.getScene().useRightHandedSystem) {
  35410. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  35411. }
  35412. else {
  35413. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  35414. }
  35415. this.beta += this.inertialBetaOffset;
  35416. this.radius -= this.inertialRadiusOffset;
  35417. this.inertialAlphaOffset *= this.inertia;
  35418. this.inertialBetaOffset *= this.inertia;
  35419. this.inertialRadiusOffset *= this.inertia;
  35420. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  35421. this.inertialAlphaOffset = 0;
  35422. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  35423. this.inertialBetaOffset = 0;
  35424. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  35425. this.inertialRadiusOffset = 0;
  35426. }
  35427. // Panning inertia
  35428. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  35429. if (!this._localDirection) {
  35430. this._localDirection = BABYLON.Vector3.Zero();
  35431. this._transformedDirection = BABYLON.Vector3.Zero();
  35432. }
  35433. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  35434. this._localDirection.multiplyInPlace(this.panningAxis);
  35435. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  35436. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  35437. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  35438. if (!this.panningAxis.y) {
  35439. this._transformedDirection.y = 0;
  35440. }
  35441. if (!this._targetHost) {
  35442. this._target.addInPlace(this._transformedDirection);
  35443. }
  35444. this.inertialPanningX *= this.panningInertia;
  35445. this.inertialPanningY *= this.panningInertia;
  35446. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  35447. this.inertialPanningX = 0;
  35448. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  35449. this.inertialPanningY = 0;
  35450. }
  35451. // Limits
  35452. this._checkLimits();
  35453. _super.prototype._checkInputs.call(this);
  35454. };
  35455. ArcRotateCamera.prototype._checkLimits = function () {
  35456. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  35457. if (this.allowUpsideDown && this.beta > Math.PI) {
  35458. this.beta = this.beta - (2 * Math.PI);
  35459. }
  35460. }
  35461. else {
  35462. if (this.beta < this.lowerBetaLimit) {
  35463. this.beta = this.lowerBetaLimit;
  35464. }
  35465. }
  35466. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  35467. if (this.allowUpsideDown && this.beta < -Math.PI) {
  35468. this.beta = this.beta + (2 * Math.PI);
  35469. }
  35470. }
  35471. else {
  35472. if (this.beta > this.upperBetaLimit) {
  35473. this.beta = this.upperBetaLimit;
  35474. }
  35475. }
  35476. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  35477. this.alpha = this.lowerAlphaLimit;
  35478. }
  35479. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  35480. this.alpha = this.upperAlphaLimit;
  35481. }
  35482. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  35483. this.radius = this.lowerRadiusLimit;
  35484. }
  35485. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  35486. this.radius = this.upperRadiusLimit;
  35487. }
  35488. };
  35489. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  35490. var radiusv3 = this.position.subtract(this._getTargetPosition());
  35491. this.radius = radiusv3.length();
  35492. if (this.radius === 0) {
  35493. this.radius = 0.0001; // Just to avoid division by zero
  35494. }
  35495. // Alpha
  35496. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  35497. if (radiusv3.z < 0) {
  35498. this.alpha = 2 * Math.PI - this.alpha;
  35499. }
  35500. // Beta
  35501. this.beta = Math.acos(radiusv3.y / this.radius);
  35502. this._checkLimits();
  35503. };
  35504. ArcRotateCamera.prototype.setPosition = function (position) {
  35505. if (this.position.equals(position)) {
  35506. return;
  35507. }
  35508. this.position.copyFrom(position);
  35509. this.rebuildAnglesAndRadius();
  35510. };
  35511. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  35512. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  35513. if (allowSamePosition === void 0) { allowSamePosition = false; }
  35514. if (target.getBoundingInfo) {
  35515. if (toBoundingCenter) {
  35516. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  35517. }
  35518. else {
  35519. this._targetBoundingCenter = null;
  35520. }
  35521. this._targetHost = target;
  35522. this._target = this._getTargetPosition();
  35523. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  35524. }
  35525. else {
  35526. var newTarget = target;
  35527. var currentTarget = this._getTargetPosition();
  35528. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  35529. return;
  35530. }
  35531. this._targetHost = null;
  35532. this._target = newTarget;
  35533. this._targetBoundingCenter = null;
  35534. this.onMeshTargetChangedObservable.notifyObservers(null);
  35535. }
  35536. this.rebuildAnglesAndRadius();
  35537. };
  35538. ArcRotateCamera.prototype._getViewMatrix = function () {
  35539. // Compute
  35540. var cosa = Math.cos(this.alpha);
  35541. var sina = Math.sin(this.alpha);
  35542. var cosb = Math.cos(this.beta);
  35543. var sinb = Math.sin(this.beta);
  35544. if (sinb === 0) {
  35545. sinb = 0.0001;
  35546. }
  35547. var target = this._getTargetPosition();
  35548. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  35549. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  35550. if (!this._collider) {
  35551. this._collider = new BABYLON.Collider();
  35552. }
  35553. this._collider.radius = this.collisionRadius;
  35554. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  35555. this._collisionTriggered = true;
  35556. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  35557. }
  35558. else {
  35559. this.position.copyFrom(this._newPosition);
  35560. var up = this.upVector;
  35561. if (this.allowUpsideDown && sinb < 0) {
  35562. up = up.clone();
  35563. up = up.negate();
  35564. }
  35565. if (this.getScene().useRightHandedSystem) {
  35566. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  35567. }
  35568. else {
  35569. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  35570. }
  35571. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  35572. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  35573. }
  35574. this._currentTarget = target;
  35575. return this._viewMatrix;
  35576. };
  35577. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  35578. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  35579. meshes = meshes || this.getScene().meshes;
  35580. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  35581. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  35582. this.radius = distance * this.zoomOnFactor;
  35583. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  35584. };
  35585. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  35586. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  35587. var meshesOrMinMaxVector;
  35588. var distance;
  35589. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  35590. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  35591. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  35592. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  35593. }
  35594. else {
  35595. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  35596. distance = meshesOrMinMaxVectorAndDistance.distance;
  35597. }
  35598. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  35599. if (!doNotUpdateMaxZ) {
  35600. this.maxZ = distance * 2;
  35601. }
  35602. };
  35603. /**
  35604. * @override
  35605. * Override Camera.createRigCamera
  35606. */
  35607. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  35608. var alphaShift;
  35609. switch (this.cameraRigMode) {
  35610. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  35611. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  35612. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  35613. case BABYLON.Camera.RIG_MODE_VR:
  35614. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  35615. break;
  35616. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  35617. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  35618. break;
  35619. }
  35620. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  35621. rigCam._cameraRigParams = {};
  35622. return rigCam;
  35623. };
  35624. /**
  35625. * @override
  35626. * Override Camera._updateRigCameras
  35627. */
  35628. ArcRotateCamera.prototype._updateRigCameras = function () {
  35629. var camLeft = this._rigCameras[0];
  35630. var camRight = this._rigCameras[1];
  35631. camLeft.beta = camRight.beta = this.beta;
  35632. camLeft.radius = camRight.radius = this.radius;
  35633. switch (this.cameraRigMode) {
  35634. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  35635. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  35636. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  35637. case BABYLON.Camera.RIG_MODE_VR:
  35638. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  35639. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  35640. break;
  35641. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  35642. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  35643. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  35644. break;
  35645. }
  35646. _super.prototype._updateRigCameras.call(this);
  35647. };
  35648. ArcRotateCamera.prototype.dispose = function () {
  35649. this.inputs.clear();
  35650. _super.prototype.dispose.call(this);
  35651. };
  35652. ArcRotateCamera.prototype.getClassName = function () {
  35653. return "ArcRotateCamera";
  35654. };
  35655. __decorate([
  35656. BABYLON.serialize()
  35657. ], ArcRotateCamera.prototype, "alpha", void 0);
  35658. __decorate([
  35659. BABYLON.serialize()
  35660. ], ArcRotateCamera.prototype, "beta", void 0);
  35661. __decorate([
  35662. BABYLON.serialize()
  35663. ], ArcRotateCamera.prototype, "radius", void 0);
  35664. __decorate([
  35665. BABYLON.serializeAsVector3("target")
  35666. ], ArcRotateCamera.prototype, "_target", void 0);
  35667. __decorate([
  35668. BABYLON.serialize()
  35669. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  35670. __decorate([
  35671. BABYLON.serialize()
  35672. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  35673. __decorate([
  35674. BABYLON.serialize()
  35675. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  35676. __decorate([
  35677. BABYLON.serialize()
  35678. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  35679. __decorate([
  35680. BABYLON.serialize()
  35681. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  35682. __decorate([
  35683. BABYLON.serialize()
  35684. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  35685. __decorate([
  35686. BABYLON.serialize()
  35687. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  35688. __decorate([
  35689. BABYLON.serialize()
  35690. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  35691. __decorate([
  35692. BABYLON.serialize()
  35693. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  35694. __decorate([
  35695. BABYLON.serialize()
  35696. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  35697. __decorate([
  35698. BABYLON.serialize()
  35699. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  35700. __decorate([
  35701. BABYLON.serialize()
  35702. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  35703. __decorate([
  35704. BABYLON.serialize()
  35705. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  35706. __decorate([
  35707. BABYLON.serialize()
  35708. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  35709. return ArcRotateCamera;
  35710. }(BABYLON.TargetCamera));
  35711. BABYLON.ArcRotateCamera = ArcRotateCamera;
  35712. })(BABYLON || (BABYLON = {}));
  35713. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  35714. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  35715. var BABYLON;
  35716. (function (BABYLON) {
  35717. var ArcRotateCameraInputsManager = (function (_super) {
  35718. __extends(ArcRotateCameraInputsManager, _super);
  35719. function ArcRotateCameraInputsManager(camera) {
  35720. return _super.call(this, camera) || this;
  35721. }
  35722. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  35723. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  35724. return this;
  35725. };
  35726. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  35727. this.add(new BABYLON.ArcRotateCameraPointersInput());
  35728. return this;
  35729. };
  35730. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  35731. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  35732. return this;
  35733. };
  35734. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  35735. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  35736. return this;
  35737. };
  35738. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  35739. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  35740. return this;
  35741. };
  35742. return ArcRotateCameraInputsManager;
  35743. }(BABYLON.CameraInputsManager));
  35744. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  35745. })(BABYLON || (BABYLON = {}));
  35746. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  35747. var BABYLON;
  35748. (function (BABYLON) {
  35749. var HemisphericLight = (function (_super) {
  35750. __extends(HemisphericLight, _super);
  35751. /**
  35752. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  35753. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  35754. * The HemisphericLight can't cast shadows.
  35755. * Documentation : http://doc.babylonjs.com/tutorials/lights
  35756. */
  35757. function HemisphericLight(name, direction, scene) {
  35758. var _this = _super.call(this, name, scene) || this;
  35759. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  35760. _this.direction = direction || BABYLON.Vector3.Up();
  35761. return _this;
  35762. }
  35763. HemisphericLight.prototype._buildUniformLayout = function () {
  35764. this._uniformBuffer.addUniform("vLightData", 4);
  35765. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  35766. this._uniformBuffer.addUniform("vLightSpecular", 3);
  35767. this._uniformBuffer.addUniform("vLightGround", 3);
  35768. this._uniformBuffer.addUniform("shadowsInfo", 3);
  35769. this._uniformBuffer.addUniform("depthValues", 2);
  35770. this._uniformBuffer.create();
  35771. };
  35772. /**
  35773. * Returns the string "HemisphericLight".
  35774. */
  35775. HemisphericLight.prototype.getClassName = function () {
  35776. return "HemisphericLight";
  35777. };
  35778. /**
  35779. * Sets the HemisphericLight direction towards the passed target (Vector3).
  35780. * Returns the updated direction.
  35781. */
  35782. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  35783. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  35784. return this.direction;
  35785. };
  35786. HemisphericLight.prototype.getShadowGenerator = function () {
  35787. return null;
  35788. };
  35789. /**
  35790. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  35791. * Returns the HemisphericLight.
  35792. */
  35793. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  35794. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  35795. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  35796. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  35797. return this;
  35798. };
  35799. HemisphericLight.prototype._getWorldMatrix = function () {
  35800. if (!this._worldMatrix) {
  35801. this._worldMatrix = BABYLON.Matrix.Identity();
  35802. }
  35803. return this._worldMatrix;
  35804. };
  35805. /**
  35806. * Returns the integer 3.
  35807. */
  35808. HemisphericLight.prototype.getTypeID = function () {
  35809. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  35810. };
  35811. __decorate([
  35812. BABYLON.serializeAsColor3()
  35813. ], HemisphericLight.prototype, "groundColor", void 0);
  35814. __decorate([
  35815. BABYLON.serializeAsVector3()
  35816. ], HemisphericLight.prototype, "direction", void 0);
  35817. return HemisphericLight;
  35818. }(BABYLON.Light));
  35819. BABYLON.HemisphericLight = HemisphericLight;
  35820. })(BABYLON || (BABYLON = {}));
  35821. //# sourceMappingURL=babylon.hemisphericLight.js.map
  35822. var BABYLON;
  35823. (function (BABYLON) {
  35824. var ShadowLight = (function (_super) {
  35825. __extends(ShadowLight, _super);
  35826. function ShadowLight() {
  35827. var _this = _super !== null && _super.apply(this, arguments) || this;
  35828. _this._needProjectionMatrixCompute = true;
  35829. return _this;
  35830. }
  35831. Object.defineProperty(ShadowLight.prototype, "direction", {
  35832. get: function () {
  35833. return this._direction;
  35834. },
  35835. set: function (value) {
  35836. this._direction = value;
  35837. },
  35838. enumerable: true,
  35839. configurable: true
  35840. });
  35841. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  35842. get: function () {
  35843. return this._shadowMinZ;
  35844. },
  35845. set: function (value) {
  35846. this._shadowMinZ = value;
  35847. this.forceProjectionMatrixCompute();
  35848. },
  35849. enumerable: true,
  35850. configurable: true
  35851. });
  35852. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  35853. get: function () {
  35854. return this._shadowMaxZ;
  35855. },
  35856. set: function (value) {
  35857. this._shadowMaxZ = value;
  35858. this.forceProjectionMatrixCompute();
  35859. },
  35860. enumerable: true,
  35861. configurable: true
  35862. });
  35863. /**
  35864. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  35865. */
  35866. ShadowLight.prototype.computeTransformedInformation = function () {
  35867. if (this.parent && this.parent.getWorldMatrix) {
  35868. if (!this.transformedPosition) {
  35869. this.transformedPosition = BABYLON.Vector3.Zero();
  35870. }
  35871. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  35872. // In case the direction is present.
  35873. if (this.direction) {
  35874. if (!this.transformedDirection) {
  35875. this.transformedDirection = BABYLON.Vector3.Zero();
  35876. }
  35877. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  35878. }
  35879. return true;
  35880. }
  35881. return false;
  35882. };
  35883. /**
  35884. * Return the depth scale used for the shadow map.
  35885. */
  35886. ShadowLight.prototype.getDepthScale = function () {
  35887. return 50.0;
  35888. };
  35889. /**
  35890. * Returns the light direction (Vector3) for any passed face index.
  35891. */
  35892. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  35893. return this.transformedDirection ? this.transformedDirection : this.direction;
  35894. };
  35895. /**
  35896. * Returns the DirectionalLight absolute position in the World.
  35897. */
  35898. ShadowLight.prototype.getAbsolutePosition = function () {
  35899. return this.transformedPosition ? this.transformedPosition : this.position;
  35900. };
  35901. /**
  35902. * Sets the DirectionalLight direction toward the passed target (Vector3).
  35903. * Returns the updated DirectionalLight direction (Vector3).
  35904. */
  35905. ShadowLight.prototype.setDirectionToTarget = function (target) {
  35906. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  35907. return this.direction;
  35908. };
  35909. /**
  35910. * Returns the light rotation (Vector3).
  35911. */
  35912. ShadowLight.prototype.getRotation = function () {
  35913. this.direction.normalize();
  35914. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  35915. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  35916. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  35917. };
  35918. /**
  35919. * Boolean : false by default.
  35920. */
  35921. ShadowLight.prototype.needCube = function () {
  35922. return false;
  35923. };
  35924. /**
  35925. * Specifies wether or not the projection matrix should be recomputed this frame.
  35926. */
  35927. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  35928. return this._needProjectionMatrixCompute;
  35929. };
  35930. /**
  35931. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  35932. */
  35933. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  35934. this._needProjectionMatrixCompute = true;
  35935. };
  35936. /**
  35937. * Get the world matrix of the sahdow lights.
  35938. */
  35939. ShadowLight.prototype._getWorldMatrix = function () {
  35940. if (!this._worldMatrix) {
  35941. this._worldMatrix = BABYLON.Matrix.Identity();
  35942. }
  35943. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  35944. return this._worldMatrix;
  35945. };
  35946. /**
  35947. * Gets the minZ used for shadow according to both the scene and the light.
  35948. * @param activeCamera
  35949. */
  35950. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  35951. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  35952. };
  35953. /**
  35954. * Gets the maxZ used for shadow according to both the scene and the light.
  35955. * @param activeCamera
  35956. */
  35957. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  35958. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  35959. };
  35960. /**
  35961. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  35962. * Returns the light.
  35963. */
  35964. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  35965. if (this.customProjectionMatrixBuilder) {
  35966. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  35967. }
  35968. else {
  35969. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  35970. }
  35971. return this;
  35972. };
  35973. __decorate([
  35974. BABYLON.serializeAsVector3()
  35975. ], ShadowLight.prototype, "position", void 0);
  35976. __decorate([
  35977. BABYLON.serializeAsVector3()
  35978. ], ShadowLight.prototype, "direction", null);
  35979. __decorate([
  35980. BABYLON.serialize()
  35981. ], ShadowLight.prototype, "shadowMinZ", null);
  35982. __decorate([
  35983. BABYLON.serialize()
  35984. ], ShadowLight.prototype, "shadowMaxZ", null);
  35985. return ShadowLight;
  35986. }(BABYLON.Light));
  35987. BABYLON.ShadowLight = ShadowLight;
  35988. })(BABYLON || (BABYLON = {}));
  35989. //# sourceMappingURL=babylon.shadowLight.js.map
  35990. var BABYLON;
  35991. (function (BABYLON) {
  35992. var PointLight = (function (_super) {
  35993. __extends(PointLight, _super);
  35994. /**
  35995. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  35996. * A PointLight emits the light in every direction.
  35997. * It can cast shadows.
  35998. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  35999. * ```javascript
  36000. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  36001. * ```
  36002. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36003. */
  36004. function PointLight(name, position, scene) {
  36005. var _this = _super.call(this, name, scene) || this;
  36006. _this._shadowAngle = Math.PI / 2;
  36007. _this.position = position;
  36008. return _this;
  36009. }
  36010. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  36011. /**
  36012. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36013. * This specifies what angle the shadow will use to be created.
  36014. *
  36015. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  36016. */
  36017. get: function () {
  36018. return this._shadowAngle;
  36019. },
  36020. /**
  36021. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36022. * This specifies what angle the shadow will use to be created.
  36023. *
  36024. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  36025. */
  36026. set: function (value) {
  36027. this._shadowAngle = value;
  36028. this.forceProjectionMatrixCompute();
  36029. },
  36030. enumerable: true,
  36031. configurable: true
  36032. });
  36033. Object.defineProperty(PointLight.prototype, "direction", {
  36034. get: function () {
  36035. return this._direction;
  36036. },
  36037. /**
  36038. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36039. */
  36040. set: function (value) {
  36041. var previousNeedCube = this.needCube();
  36042. this._direction = value;
  36043. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  36044. this._shadowGenerator.recreateShadowMap();
  36045. }
  36046. },
  36047. enumerable: true,
  36048. configurable: true
  36049. });
  36050. /**
  36051. * Returns the string "PointLight"
  36052. */
  36053. PointLight.prototype.getClassName = function () {
  36054. return "PointLight";
  36055. };
  36056. /**
  36057. * Returns the integer 0.
  36058. */
  36059. PointLight.prototype.getTypeID = function () {
  36060. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  36061. };
  36062. /**
  36063. * Specifies wether or not the shadowmap should be a cube texture.
  36064. */
  36065. PointLight.prototype.needCube = function () {
  36066. return !this.direction;
  36067. };
  36068. /**
  36069. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  36070. */
  36071. PointLight.prototype.getShadowDirection = function (faceIndex) {
  36072. if (this.direction) {
  36073. return _super.prototype.getShadowDirection.call(this, faceIndex);
  36074. }
  36075. else {
  36076. switch (faceIndex) {
  36077. case 0:
  36078. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  36079. case 1:
  36080. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  36081. case 2:
  36082. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  36083. case 3:
  36084. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  36085. case 4:
  36086. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  36087. case 5:
  36088. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  36089. }
  36090. }
  36091. return BABYLON.Vector3.Zero();
  36092. };
  36093. /**
  36094. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  36095. * - fov = PI / 2
  36096. * - aspect ratio : 1.0
  36097. * - z-near and far equal to the active camera minZ and maxZ.
  36098. * Returns the PointLight.
  36099. */
  36100. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36101. var activeCamera = this.getScene().activeCamera;
  36102. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  36103. };
  36104. PointLight.prototype._buildUniformLayout = function () {
  36105. this._uniformBuffer.addUniform("vLightData", 4);
  36106. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36107. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36108. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36109. this._uniformBuffer.addUniform("depthValues", 2);
  36110. this._uniformBuffer.create();
  36111. };
  36112. /**
  36113. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  36114. * Returns the PointLight.
  36115. */
  36116. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  36117. if (this.computeTransformedInformation()) {
  36118. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  36119. return this;
  36120. }
  36121. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  36122. return this;
  36123. };
  36124. __decorate([
  36125. BABYLON.serialize()
  36126. ], PointLight.prototype, "shadowAngle", null);
  36127. return PointLight;
  36128. }(BABYLON.ShadowLight));
  36129. BABYLON.PointLight = PointLight;
  36130. })(BABYLON || (BABYLON = {}));
  36131. //# sourceMappingURL=babylon.pointLight.js.map
  36132. /// <reference path="babylon.light.ts" />
  36133. var BABYLON;
  36134. (function (BABYLON) {
  36135. var DirectionalLight = (function (_super) {
  36136. __extends(DirectionalLight, _super);
  36137. /**
  36138. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  36139. * The directional light is emitted from everywhere in the given direction.
  36140. * It can cast shawdows.
  36141. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36142. */
  36143. function DirectionalLight(name, direction, scene) {
  36144. var _this = _super.call(this, name, scene) || this;
  36145. _this._shadowFrustumSize = 0;
  36146. _this._shadowOrthoScale = 0.5;
  36147. _this.autoUpdateExtends = true;
  36148. // Cache
  36149. _this._orthoLeft = Number.MAX_VALUE;
  36150. _this._orthoRight = Number.MIN_VALUE;
  36151. _this._orthoTop = Number.MIN_VALUE;
  36152. _this._orthoBottom = Number.MAX_VALUE;
  36153. _this.position = direction.scale(-1.0);
  36154. _this.direction = direction;
  36155. return _this;
  36156. }
  36157. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  36158. /**
  36159. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  36160. */
  36161. get: function () {
  36162. return this._shadowFrustumSize;
  36163. },
  36164. /**
  36165. * Specifies a fix frustum size for the shadow generation.
  36166. */
  36167. set: function (value) {
  36168. this._shadowFrustumSize = value;
  36169. this.forceProjectionMatrixCompute();
  36170. },
  36171. enumerable: true,
  36172. configurable: true
  36173. });
  36174. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  36175. get: function () {
  36176. return this._shadowOrthoScale;
  36177. },
  36178. set: function (value) {
  36179. this._shadowOrthoScale = value;
  36180. this.forceProjectionMatrixCompute();
  36181. },
  36182. enumerable: true,
  36183. configurable: true
  36184. });
  36185. /**
  36186. * Returns the string "DirectionalLight".
  36187. */
  36188. DirectionalLight.prototype.getClassName = function () {
  36189. return "DirectionalLight";
  36190. };
  36191. /**
  36192. * Returns the integer 1.
  36193. */
  36194. DirectionalLight.prototype.getTypeID = function () {
  36195. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  36196. };
  36197. /**
  36198. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  36199. * Returns the DirectionalLight Shadow projection matrix.
  36200. */
  36201. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36202. if (this.shadowFrustumSize > 0) {
  36203. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  36204. }
  36205. else {
  36206. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  36207. }
  36208. };
  36209. /**
  36210. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  36211. * Returns the DirectionalLight Shadow projection matrix.
  36212. */
  36213. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  36214. var activeCamera = this.getScene().activeCamera;
  36215. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  36216. };
  36217. /**
  36218. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  36219. * Returns the DirectionalLight Shadow projection matrix.
  36220. */
  36221. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36222. var activeCamera = this.getScene().activeCamera;
  36223. // Check extends
  36224. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  36225. var tempVector3 = BABYLON.Vector3.Zero();
  36226. this._orthoLeft = Number.MAX_VALUE;
  36227. this._orthoRight = Number.MIN_VALUE;
  36228. this._orthoTop = Number.MIN_VALUE;
  36229. this._orthoBottom = Number.MAX_VALUE;
  36230. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  36231. var mesh = renderList[meshIndex];
  36232. if (!mesh) {
  36233. continue;
  36234. }
  36235. var boundingInfo = mesh.getBoundingInfo();
  36236. if (!boundingInfo) {
  36237. continue;
  36238. }
  36239. var boundingBox = boundingInfo.boundingBox;
  36240. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  36241. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  36242. if (tempVector3.x < this._orthoLeft)
  36243. this._orthoLeft = tempVector3.x;
  36244. if (tempVector3.y < this._orthoBottom)
  36245. this._orthoBottom = tempVector3.y;
  36246. if (tempVector3.x > this._orthoRight)
  36247. this._orthoRight = tempVector3.x;
  36248. if (tempVector3.y > this._orthoTop)
  36249. this._orthoTop = tempVector3.y;
  36250. }
  36251. }
  36252. }
  36253. var xOffset = this._orthoRight - this._orthoLeft;
  36254. var yOffset = this._orthoTop - this._orthoBottom;
  36255. 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);
  36256. };
  36257. DirectionalLight.prototype._buildUniformLayout = function () {
  36258. this._uniformBuffer.addUniform("vLightData", 4);
  36259. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36260. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36261. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36262. this._uniformBuffer.addUniform("depthValues", 2);
  36263. this._uniformBuffer.create();
  36264. };
  36265. /**
  36266. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  36267. * Returns the DirectionalLight.
  36268. */
  36269. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  36270. if (this.computeTransformedInformation()) {
  36271. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  36272. return this;
  36273. }
  36274. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  36275. return this;
  36276. };
  36277. /**
  36278. * Gets the minZ used for shadow according to both the scene and the light.
  36279. *
  36280. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  36281. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  36282. * @param activeCamera
  36283. */
  36284. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  36285. return 1;
  36286. };
  36287. /**
  36288. * Gets the maxZ used for shadow according to both the scene and the light.
  36289. *
  36290. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  36291. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  36292. * @param activeCamera
  36293. */
  36294. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  36295. return 1;
  36296. };
  36297. __decorate([
  36298. BABYLON.serialize()
  36299. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  36300. __decorate([
  36301. BABYLON.serialize()
  36302. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  36303. __decorate([
  36304. BABYLON.serialize()
  36305. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  36306. return DirectionalLight;
  36307. }(BABYLON.ShadowLight));
  36308. BABYLON.DirectionalLight = DirectionalLight;
  36309. })(BABYLON || (BABYLON = {}));
  36310. //# sourceMappingURL=babylon.directionalLight.js.map
  36311. var BABYLON;
  36312. (function (BABYLON) {
  36313. var SpotLight = (function (_super) {
  36314. __extends(SpotLight, _super);
  36315. /**
  36316. * Creates a SpotLight object in the scene with the passed parameters :
  36317. * - `position` (Vector3) is the initial SpotLight position,
  36318. * - `direction` (Vector3) is the initial SpotLight direction,
  36319. * - `angle` (float, in radians) is the spot light cone angle,
  36320. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  36321. * A spot light is a simply light oriented cone.
  36322. * It can cast shadows.
  36323. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36324. */
  36325. function SpotLight(name, position, direction, angle, exponent, scene) {
  36326. var _this = _super.call(this, name, scene) || this;
  36327. _this.position = position;
  36328. _this.direction = direction;
  36329. _this.angle = angle;
  36330. _this.exponent = exponent;
  36331. return _this;
  36332. }
  36333. Object.defineProperty(SpotLight.prototype, "angle", {
  36334. get: function () {
  36335. return this._angle;
  36336. },
  36337. set: function (value) {
  36338. this._angle = value;
  36339. this.forceProjectionMatrixCompute();
  36340. },
  36341. enumerable: true,
  36342. configurable: true
  36343. });
  36344. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  36345. get: function () {
  36346. return this._shadowAngleScale;
  36347. },
  36348. /**
  36349. * Allows scaling the angle of the light for shadow generation only.
  36350. */
  36351. set: function (value) {
  36352. this._shadowAngleScale = value;
  36353. this.forceProjectionMatrixCompute();
  36354. },
  36355. enumerable: true,
  36356. configurable: true
  36357. });
  36358. /**
  36359. * Returns the string "SpotLight".
  36360. */
  36361. SpotLight.prototype.getClassName = function () {
  36362. return "SpotLight";
  36363. };
  36364. /**
  36365. * Returns the integer 2.
  36366. */
  36367. SpotLight.prototype.getTypeID = function () {
  36368. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  36369. };
  36370. /**
  36371. * 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.
  36372. * Returns the SpotLight.
  36373. */
  36374. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36375. var activeCamera = this.getScene().activeCamera;
  36376. this._shadowAngleScale = this._shadowAngleScale || 1;
  36377. var angle = this._shadowAngleScale * this._angle;
  36378. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  36379. };
  36380. SpotLight.prototype._buildUniformLayout = function () {
  36381. this._uniformBuffer.addUniform("vLightData", 4);
  36382. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36383. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36384. this._uniformBuffer.addUniform("vLightDirection", 3);
  36385. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36386. this._uniformBuffer.addUniform("depthValues", 2);
  36387. this._uniformBuffer.create();
  36388. };
  36389. /**
  36390. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  36391. * Return the SpotLight.
  36392. */
  36393. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  36394. var normalizeDirection;
  36395. if (this.computeTransformedInformation()) {
  36396. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  36397. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  36398. }
  36399. else {
  36400. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  36401. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  36402. }
  36403. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  36404. return this;
  36405. };
  36406. __decorate([
  36407. BABYLON.serialize()
  36408. ], SpotLight.prototype, "angle", null);
  36409. __decorate([
  36410. BABYLON.serialize()
  36411. /**
  36412. * Allows scaling the angle of the light for shadow generation only.
  36413. */
  36414. ], SpotLight.prototype, "shadowAngleScale", null);
  36415. __decorate([
  36416. BABYLON.serialize()
  36417. ], SpotLight.prototype, "exponent", void 0);
  36418. return SpotLight;
  36419. }(BABYLON.ShadowLight));
  36420. BABYLON.SpotLight = SpotLight;
  36421. })(BABYLON || (BABYLON = {}));
  36422. //# sourceMappingURL=babylon.spotLight.js.map
  36423. var BABYLON;
  36424. (function (BABYLON) {
  36425. var AnimationRange = (function () {
  36426. function AnimationRange(name, from, to) {
  36427. this.name = name;
  36428. this.from = from;
  36429. this.to = to;
  36430. }
  36431. AnimationRange.prototype.clone = function () {
  36432. return new AnimationRange(this.name, this.from, this.to);
  36433. };
  36434. return AnimationRange;
  36435. }());
  36436. BABYLON.AnimationRange = AnimationRange;
  36437. /**
  36438. * Composed of a frame, and an action function
  36439. */
  36440. var AnimationEvent = (function () {
  36441. function AnimationEvent(frame, action, onlyOnce) {
  36442. this.frame = frame;
  36443. this.action = action;
  36444. this.onlyOnce = onlyOnce;
  36445. this.isDone = false;
  36446. }
  36447. return AnimationEvent;
  36448. }());
  36449. BABYLON.AnimationEvent = AnimationEvent;
  36450. var PathCursor = (function () {
  36451. function PathCursor(path) {
  36452. this.path = path;
  36453. this._onchange = new Array();
  36454. this.value = 0;
  36455. this.animations = new Array();
  36456. }
  36457. PathCursor.prototype.getPoint = function () {
  36458. var point = this.path.getPointAtLengthPosition(this.value);
  36459. return new BABYLON.Vector3(point.x, 0, point.y);
  36460. };
  36461. PathCursor.prototype.moveAhead = function (step) {
  36462. if (step === void 0) { step = 0.002; }
  36463. this.move(step);
  36464. return this;
  36465. };
  36466. PathCursor.prototype.moveBack = function (step) {
  36467. if (step === void 0) { step = 0.002; }
  36468. this.move(-step);
  36469. return this;
  36470. };
  36471. PathCursor.prototype.move = function (step) {
  36472. if (Math.abs(step) > 1) {
  36473. throw "step size should be less than 1.";
  36474. }
  36475. this.value += step;
  36476. this.ensureLimits();
  36477. this.raiseOnChange();
  36478. return this;
  36479. };
  36480. PathCursor.prototype.ensureLimits = function () {
  36481. while (this.value > 1) {
  36482. this.value -= 1;
  36483. }
  36484. while (this.value < 0) {
  36485. this.value += 1;
  36486. }
  36487. return this;
  36488. };
  36489. // used by animation engine
  36490. PathCursor.prototype.markAsDirty = function (propertyName) {
  36491. this.ensureLimits();
  36492. this.raiseOnChange();
  36493. return this;
  36494. };
  36495. PathCursor.prototype.raiseOnChange = function () {
  36496. var _this = this;
  36497. this._onchange.forEach(function (f) { return f(_this); });
  36498. return this;
  36499. };
  36500. PathCursor.prototype.onchange = function (f) {
  36501. this._onchange.push(f);
  36502. return this;
  36503. };
  36504. return PathCursor;
  36505. }());
  36506. BABYLON.PathCursor = PathCursor;
  36507. var Animation = (function () {
  36508. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  36509. this.name = name;
  36510. this.targetProperty = targetProperty;
  36511. this.framePerSecond = framePerSecond;
  36512. this.dataType = dataType;
  36513. this.loopMode = loopMode;
  36514. this.enableBlending = enableBlending;
  36515. this._offsetsCache = {};
  36516. this._highLimitsCache = {};
  36517. this._stopped = false;
  36518. this._blendingFactor = 0;
  36519. // The set of event that will be linked to this animation
  36520. this._events = new Array();
  36521. this.allowMatricesInterpolation = false;
  36522. this.blendingSpeed = 0.01;
  36523. this._ranges = {};
  36524. this.targetPropertyPath = targetProperty.split(".");
  36525. this.dataType = dataType;
  36526. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  36527. }
  36528. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  36529. var dataType = undefined;
  36530. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  36531. dataType = Animation.ANIMATIONTYPE_FLOAT;
  36532. }
  36533. else if (from instanceof BABYLON.Quaternion) {
  36534. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  36535. }
  36536. else if (from instanceof BABYLON.Vector3) {
  36537. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  36538. }
  36539. else if (from instanceof BABYLON.Vector2) {
  36540. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  36541. }
  36542. else if (from instanceof BABYLON.Color3) {
  36543. dataType = Animation.ANIMATIONTYPE_COLOR3;
  36544. }
  36545. else if (from instanceof BABYLON.Size) {
  36546. dataType = Animation.ANIMATIONTYPE_SIZE;
  36547. }
  36548. if (dataType == undefined) {
  36549. return null;
  36550. }
  36551. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  36552. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  36553. animation.setKeys(keys);
  36554. if (easingFunction !== undefined) {
  36555. animation.setEasingFunction(easingFunction);
  36556. }
  36557. return animation;
  36558. };
  36559. /**
  36560. * Sets up an animation.
  36561. * @param property the property to animate
  36562. * @param animationType the animation type to apply
  36563. * @param easingFunction the easing function used in the animation
  36564. * @returns The created animation
  36565. */
  36566. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  36567. var animation = new BABYLON.Animation(property + "Animation", property, framePerSecond, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  36568. animation.setEasingFunction(easingFunction);
  36569. return animation;
  36570. };
  36571. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  36572. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  36573. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  36574. };
  36575. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  36576. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  36577. node.animations.push(animation);
  36578. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  36579. };
  36580. /**
  36581. * Transition property of the Camera to the target Value.
  36582. * @param property The property to transition
  36583. * @param targetValue The target Value of the property
  36584. * @param host The object where the property to animate belongs
  36585. * @param scene Scene used to run the animation
  36586. * @param frameRate Framerate (in frame/s) to use
  36587. * @param transition The transition type we want to use
  36588. * @param duration The duration of the animation, in milliseconds
  36589. * @param onAnimationEnd Call back trigger at the end of the animation.
  36590. */
  36591. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  36592. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  36593. if (duration <= 0) {
  36594. host[property] = targetValue;
  36595. if (onAnimationEnd) {
  36596. onAnimationEnd();
  36597. }
  36598. return;
  36599. }
  36600. var endFrame = frameRate * (duration / 1000);
  36601. transition.setKeys([{
  36602. frame: 0,
  36603. value: host[property].clone ? host[property].clone() : host[property]
  36604. },
  36605. {
  36606. frame: endFrame,
  36607. value: targetValue
  36608. }]);
  36609. if (!host.animations) {
  36610. host.animations = [];
  36611. }
  36612. host.animations.push(transition);
  36613. var animation = scene.beginAnimation(host, 0, endFrame, false);
  36614. animation.onAnimationEnd = onAnimationEnd;
  36615. return animation;
  36616. };
  36617. // Methods
  36618. /**
  36619. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  36620. */
  36621. Animation.prototype.toString = function (fullDetails) {
  36622. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  36623. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  36624. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  36625. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  36626. if (fullDetails) {
  36627. ret += ", Ranges: {";
  36628. var first = true;
  36629. for (var name in this._ranges) {
  36630. if (first) {
  36631. ret += ", ";
  36632. first = false;
  36633. }
  36634. ret += name;
  36635. }
  36636. ret += "}";
  36637. }
  36638. return ret;
  36639. };
  36640. /**
  36641. * Add an event to this animation.
  36642. */
  36643. Animation.prototype.addEvent = function (event) {
  36644. this._events.push(event);
  36645. };
  36646. /**
  36647. * Remove all events found at the given frame
  36648. * @param frame
  36649. */
  36650. Animation.prototype.removeEvents = function (frame) {
  36651. for (var index = 0; index < this._events.length; index++) {
  36652. if (this._events[index].frame === frame) {
  36653. this._events.splice(index, 1);
  36654. index--;
  36655. }
  36656. }
  36657. };
  36658. Animation.prototype.createRange = function (name, from, to) {
  36659. // check name not already in use; could happen for bones after serialized
  36660. if (!this._ranges[name]) {
  36661. this._ranges[name] = new AnimationRange(name, from, to);
  36662. }
  36663. };
  36664. Animation.prototype.deleteRange = function (name, deleteFrames) {
  36665. if (deleteFrames === void 0) { deleteFrames = true; }
  36666. if (this._ranges[name]) {
  36667. if (deleteFrames) {
  36668. var from = this._ranges[name].from;
  36669. var to = this._ranges[name].to;
  36670. // this loop MUST go high to low for multiple splices to work
  36671. for (var key = this._keys.length - 1; key >= 0; key--) {
  36672. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  36673. this._keys.splice(key, 1);
  36674. }
  36675. }
  36676. }
  36677. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  36678. }
  36679. };
  36680. Animation.prototype.getRange = function (name) {
  36681. return this._ranges[name];
  36682. };
  36683. Animation.prototype.reset = function () {
  36684. this._offsetsCache = {};
  36685. this._highLimitsCache = {};
  36686. this.currentFrame = 0;
  36687. this._blendingFactor = 0;
  36688. this._originalBlendValue = null;
  36689. };
  36690. Animation.prototype.isStopped = function () {
  36691. return this._stopped;
  36692. };
  36693. Animation.prototype.getKeys = function () {
  36694. return this._keys;
  36695. };
  36696. Animation.prototype.getHighestFrame = function () {
  36697. var ret = 0;
  36698. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  36699. if (ret < this._keys[key].frame) {
  36700. ret = this._keys[key].frame;
  36701. }
  36702. }
  36703. return ret;
  36704. };
  36705. Animation.prototype.getEasingFunction = function () {
  36706. return this._easingFunction;
  36707. };
  36708. Animation.prototype.setEasingFunction = function (easingFunction) {
  36709. this._easingFunction = easingFunction;
  36710. };
  36711. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  36712. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  36713. };
  36714. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  36715. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  36716. };
  36717. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  36718. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  36719. };
  36720. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  36721. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  36722. };
  36723. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  36724. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  36725. };
  36726. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  36727. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  36728. };
  36729. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  36730. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  36731. };
  36732. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  36733. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  36734. };
  36735. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  36736. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  36737. };
  36738. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  36739. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  36740. };
  36741. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  36742. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  36743. };
  36744. Animation.prototype.clone = function () {
  36745. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  36746. clone.enableBlending = this.enableBlending;
  36747. clone.blendingSpeed = this.blendingSpeed;
  36748. if (this._keys) {
  36749. clone.setKeys(this._keys);
  36750. }
  36751. if (this._ranges) {
  36752. clone._ranges = {};
  36753. for (var name in this._ranges) {
  36754. clone._ranges[name] = this._ranges[name].clone();
  36755. }
  36756. }
  36757. return clone;
  36758. };
  36759. Animation.prototype.setKeys = function (values) {
  36760. this._keys = values.slice(0);
  36761. this._offsetsCache = {};
  36762. this._highLimitsCache = {};
  36763. };
  36764. Animation.prototype._getKeyValue = function (value) {
  36765. if (typeof value === "function") {
  36766. return value();
  36767. }
  36768. return value;
  36769. };
  36770. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  36771. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  36772. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  36773. }
  36774. this.currentFrame = currentFrame;
  36775. // Try to get a hash to find the right key
  36776. 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));
  36777. if (this._keys[startKeyIndex].frame >= currentFrame) {
  36778. while (startKeyIndex - 1 >= 0 && this._keys[startKeyIndex].frame >= currentFrame) {
  36779. startKeyIndex--;
  36780. }
  36781. }
  36782. for (var key = startKeyIndex; key < this._keys.length; key++) {
  36783. var endKey = this._keys[key + 1];
  36784. if (endKey.frame >= currentFrame) {
  36785. var startKey = this._keys[key];
  36786. var startValue = this._getKeyValue(startKey.value);
  36787. var endValue = this._getKeyValue(endKey.value);
  36788. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  36789. var frameDelta = endKey.frame - startKey.frame;
  36790. // gradient : percent of currentFrame between the frame inf and the frame sup
  36791. var gradient = (currentFrame - startKey.frame) / frameDelta;
  36792. // check for easingFunction and correction of gradient
  36793. if (this._easingFunction != null) {
  36794. gradient = this._easingFunction.ease(gradient);
  36795. }
  36796. switch (this.dataType) {
  36797. // Float
  36798. case Animation.ANIMATIONTYPE_FLOAT:
  36799. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  36800. switch (loopMode) {
  36801. case Animation.ANIMATIONLOOPMODE_CYCLE:
  36802. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  36803. return floatValue;
  36804. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  36805. return offsetValue * repeatCount + floatValue;
  36806. }
  36807. break;
  36808. // Quaternion
  36809. case Animation.ANIMATIONTYPE_QUATERNION:
  36810. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  36811. switch (loopMode) {
  36812. case Animation.ANIMATIONLOOPMODE_CYCLE:
  36813. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  36814. return quatValue;
  36815. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  36816. return quatValue.add(offsetValue.scale(repeatCount));
  36817. }
  36818. return quatValue;
  36819. // Vector3
  36820. case Animation.ANIMATIONTYPE_VECTOR3:
  36821. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  36822. switch (loopMode) {
  36823. case Animation.ANIMATIONLOOPMODE_CYCLE:
  36824. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  36825. return vec3Value;
  36826. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  36827. return vec3Value.add(offsetValue.scale(repeatCount));
  36828. }
  36829. // Vector2
  36830. case Animation.ANIMATIONTYPE_VECTOR2:
  36831. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  36832. switch (loopMode) {
  36833. case Animation.ANIMATIONLOOPMODE_CYCLE:
  36834. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  36835. return vec2Value;
  36836. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  36837. return vec2Value.add(offsetValue.scale(repeatCount));
  36838. }
  36839. // Size
  36840. case Animation.ANIMATIONTYPE_SIZE:
  36841. switch (loopMode) {
  36842. case Animation.ANIMATIONLOOPMODE_CYCLE:
  36843. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  36844. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  36845. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  36846. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  36847. }
  36848. // Color3
  36849. case Animation.ANIMATIONTYPE_COLOR3:
  36850. switch (loopMode) {
  36851. case Animation.ANIMATIONLOOPMODE_CYCLE:
  36852. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  36853. return this.color3InterpolateFunction(startValue, endValue, gradient);
  36854. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  36855. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  36856. }
  36857. // Matrix
  36858. case Animation.ANIMATIONTYPE_MATRIX:
  36859. switch (loopMode) {
  36860. case Animation.ANIMATIONLOOPMODE_CYCLE:
  36861. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  36862. if (this.allowMatricesInterpolation) {
  36863. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  36864. }
  36865. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  36866. return startValue;
  36867. }
  36868. default:
  36869. break;
  36870. }
  36871. break;
  36872. }
  36873. }
  36874. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  36875. };
  36876. Animation.prototype.setValue = function (currentValue, blend) {
  36877. if (blend === void 0) { blend = false; }
  36878. // Set value
  36879. var path;
  36880. var destination;
  36881. if (this.targetPropertyPath.length > 1) {
  36882. var property = this._target[this.targetPropertyPath[0]];
  36883. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  36884. property = property[this.targetPropertyPath[index]];
  36885. }
  36886. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  36887. destination = property;
  36888. }
  36889. else {
  36890. path = this.targetPropertyPath[0];
  36891. destination = this._target;
  36892. }
  36893. // Blending
  36894. if (this.enableBlending && this._blendingFactor <= 1.0) {
  36895. if (!this._originalBlendValue) {
  36896. if (destination[path].clone) {
  36897. this._originalBlendValue = destination[path].clone();
  36898. }
  36899. else {
  36900. this._originalBlendValue = destination[path];
  36901. }
  36902. }
  36903. if (this._originalBlendValue.prototype) {
  36904. if (this._originalBlendValue.prototype.Lerp) {
  36905. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  36906. }
  36907. else {
  36908. destination[path] = currentValue;
  36909. }
  36910. }
  36911. else if (this._originalBlendValue.m) {
  36912. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  36913. }
  36914. else {
  36915. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  36916. }
  36917. this._blendingFactor += this.blendingSpeed;
  36918. }
  36919. else {
  36920. destination[path] = currentValue;
  36921. }
  36922. if (this._target.markAsDirty) {
  36923. this._target.markAsDirty(this.targetProperty);
  36924. }
  36925. };
  36926. Animation.prototype.goToFrame = function (frame) {
  36927. if (frame < this._keys[0].frame) {
  36928. frame = this._keys[0].frame;
  36929. }
  36930. else if (frame > this._keys[this._keys.length - 1].frame) {
  36931. frame = this._keys[this._keys.length - 1].frame;
  36932. }
  36933. var currentValue = this._interpolate(frame, 0, this.loopMode);
  36934. this.setValue(currentValue);
  36935. };
  36936. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  36937. if (blend === void 0) { blend = false; }
  36938. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  36939. this._stopped = true;
  36940. return false;
  36941. }
  36942. var returnValue = true;
  36943. // Adding a start key at frame 0 if missing
  36944. if (this._keys[0].frame !== 0) {
  36945. var newKey = { frame: 0, value: this._keys[0].value };
  36946. this._keys.splice(0, 0, newKey);
  36947. }
  36948. // Check limits
  36949. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  36950. from = this._keys[0].frame;
  36951. }
  36952. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  36953. to = this._keys[this._keys.length - 1].frame;
  36954. }
  36955. //to and from cannot be the same key
  36956. if (from === to) {
  36957. from++;
  36958. }
  36959. // Compute ratio
  36960. var range = to - from;
  36961. var offsetValue;
  36962. // ratio represents the frame delta between from and to
  36963. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  36964. var highLimitValue = 0;
  36965. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  36966. returnValue = false;
  36967. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  36968. }
  36969. else {
  36970. // Get max value if required
  36971. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  36972. var keyOffset = to.toString() + from.toString();
  36973. if (!this._offsetsCache[keyOffset]) {
  36974. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  36975. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  36976. switch (this.dataType) {
  36977. // Float
  36978. case Animation.ANIMATIONTYPE_FLOAT:
  36979. this._offsetsCache[keyOffset] = toValue - fromValue;
  36980. break;
  36981. // Quaternion
  36982. case Animation.ANIMATIONTYPE_QUATERNION:
  36983. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  36984. break;
  36985. // Vector3
  36986. case Animation.ANIMATIONTYPE_VECTOR3:
  36987. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  36988. // Vector2
  36989. case Animation.ANIMATIONTYPE_VECTOR2:
  36990. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  36991. // Size
  36992. case Animation.ANIMATIONTYPE_SIZE:
  36993. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  36994. // Color3
  36995. case Animation.ANIMATIONTYPE_COLOR3:
  36996. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  36997. default:
  36998. break;
  36999. }
  37000. this._highLimitsCache[keyOffset] = toValue;
  37001. }
  37002. highLimitValue = this._highLimitsCache[keyOffset];
  37003. offsetValue = this._offsetsCache[keyOffset];
  37004. }
  37005. }
  37006. if (offsetValue === undefined) {
  37007. switch (this.dataType) {
  37008. // Float
  37009. case Animation.ANIMATIONTYPE_FLOAT:
  37010. offsetValue = 0;
  37011. break;
  37012. // Quaternion
  37013. case Animation.ANIMATIONTYPE_QUATERNION:
  37014. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  37015. break;
  37016. // Vector3
  37017. case Animation.ANIMATIONTYPE_VECTOR3:
  37018. offsetValue = BABYLON.Vector3.Zero();
  37019. break;
  37020. // Vector2
  37021. case Animation.ANIMATIONTYPE_VECTOR2:
  37022. offsetValue = BABYLON.Vector2.Zero();
  37023. break;
  37024. // Size
  37025. case Animation.ANIMATIONTYPE_SIZE:
  37026. offsetValue = BABYLON.Size.Zero();
  37027. break;
  37028. // Color3
  37029. case Animation.ANIMATIONTYPE_COLOR3:
  37030. offsetValue = BABYLON.Color3.Black();
  37031. }
  37032. }
  37033. // Compute value
  37034. var repeatCount = (ratio / range) >> 0;
  37035. var currentFrame = returnValue ? from + ratio % range : to;
  37036. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  37037. // Set value
  37038. this.setValue(currentValue);
  37039. // Check events
  37040. for (var index = 0; index < this._events.length; index++) {
  37041. // Make sure current frame has passed event frame and that event frame is within the current range
  37042. // Also, handle both forward and reverse animations
  37043. if ((range > 0 && currentFrame >= this._events[index].frame && this._events[index].frame >= from) ||
  37044. (range < 0 && currentFrame <= this._events[index].frame && this._events[index].frame <= from)) {
  37045. var event = this._events[index];
  37046. if (!event.isDone) {
  37047. // If event should be done only once, remove it.
  37048. if (event.onlyOnce) {
  37049. this._events.splice(index, 1);
  37050. index--;
  37051. }
  37052. event.isDone = true;
  37053. event.action();
  37054. } // Don't do anything if the event has already be done.
  37055. }
  37056. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  37057. // reset event, the animation is looping
  37058. this._events[index].isDone = false;
  37059. }
  37060. }
  37061. if (!returnValue) {
  37062. this._stopped = true;
  37063. }
  37064. return returnValue;
  37065. };
  37066. Animation.prototype.serialize = function () {
  37067. var serializationObject = {};
  37068. serializationObject.name = this.name;
  37069. serializationObject.property = this.targetProperty;
  37070. serializationObject.framePerSecond = this.framePerSecond;
  37071. serializationObject.dataType = this.dataType;
  37072. serializationObject.loopBehavior = this.loopMode;
  37073. serializationObject.enableBlending = this.enableBlending;
  37074. serializationObject.blendingSpeed = this.blendingSpeed;
  37075. var dataType = this.dataType;
  37076. serializationObject.keys = [];
  37077. var keys = this.getKeys();
  37078. for (var index = 0; index < keys.length; index++) {
  37079. var animationKey = keys[index];
  37080. var key = {};
  37081. key.frame = animationKey.frame;
  37082. switch (dataType) {
  37083. case Animation.ANIMATIONTYPE_FLOAT:
  37084. key.values = [animationKey.value];
  37085. break;
  37086. case Animation.ANIMATIONTYPE_QUATERNION:
  37087. case Animation.ANIMATIONTYPE_MATRIX:
  37088. case Animation.ANIMATIONTYPE_VECTOR3:
  37089. case Animation.ANIMATIONTYPE_COLOR3:
  37090. key.values = animationKey.value.asArray();
  37091. break;
  37092. }
  37093. serializationObject.keys.push(key);
  37094. }
  37095. serializationObject.ranges = [];
  37096. for (var name in this._ranges) {
  37097. var range = {};
  37098. range.name = name;
  37099. range.from = this._ranges[name].from;
  37100. range.to = this._ranges[name].to;
  37101. serializationObject.ranges.push(range);
  37102. }
  37103. return serializationObject;
  37104. };
  37105. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  37106. get: function () {
  37107. return Animation._ANIMATIONTYPE_FLOAT;
  37108. },
  37109. enumerable: true,
  37110. configurable: true
  37111. });
  37112. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  37113. get: function () {
  37114. return Animation._ANIMATIONTYPE_VECTOR3;
  37115. },
  37116. enumerable: true,
  37117. configurable: true
  37118. });
  37119. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  37120. get: function () {
  37121. return Animation._ANIMATIONTYPE_VECTOR2;
  37122. },
  37123. enumerable: true,
  37124. configurable: true
  37125. });
  37126. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  37127. get: function () {
  37128. return Animation._ANIMATIONTYPE_SIZE;
  37129. },
  37130. enumerable: true,
  37131. configurable: true
  37132. });
  37133. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  37134. get: function () {
  37135. return Animation._ANIMATIONTYPE_QUATERNION;
  37136. },
  37137. enumerable: true,
  37138. configurable: true
  37139. });
  37140. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  37141. get: function () {
  37142. return Animation._ANIMATIONTYPE_MATRIX;
  37143. },
  37144. enumerable: true,
  37145. configurable: true
  37146. });
  37147. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  37148. get: function () {
  37149. return Animation._ANIMATIONTYPE_COLOR3;
  37150. },
  37151. enumerable: true,
  37152. configurable: true
  37153. });
  37154. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  37155. get: function () {
  37156. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  37157. },
  37158. enumerable: true,
  37159. configurable: true
  37160. });
  37161. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  37162. get: function () {
  37163. return Animation._ANIMATIONLOOPMODE_CYCLE;
  37164. },
  37165. enumerable: true,
  37166. configurable: true
  37167. });
  37168. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  37169. get: function () {
  37170. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  37171. },
  37172. enumerable: true,
  37173. configurable: true
  37174. });
  37175. Animation.Parse = function (parsedAnimation) {
  37176. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  37177. var dataType = parsedAnimation.dataType;
  37178. var keys = [];
  37179. var data;
  37180. var index;
  37181. if (parsedAnimation.enableBlending) {
  37182. animation.enableBlending = parsedAnimation.enableBlending;
  37183. }
  37184. if (parsedAnimation.blendingSpeed) {
  37185. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  37186. }
  37187. for (index = 0; index < parsedAnimation.keys.length; index++) {
  37188. var key = parsedAnimation.keys[index];
  37189. switch (dataType) {
  37190. case Animation.ANIMATIONTYPE_FLOAT:
  37191. data = key.values[0];
  37192. break;
  37193. case Animation.ANIMATIONTYPE_QUATERNION:
  37194. data = BABYLON.Quaternion.FromArray(key.values);
  37195. break;
  37196. case Animation.ANIMATIONTYPE_MATRIX:
  37197. data = BABYLON.Matrix.FromArray(key.values);
  37198. break;
  37199. case Animation.ANIMATIONTYPE_COLOR3:
  37200. data = BABYLON.Color3.FromArray(key.values);
  37201. break;
  37202. case Animation.ANIMATIONTYPE_VECTOR3:
  37203. default:
  37204. data = BABYLON.Vector3.FromArray(key.values);
  37205. break;
  37206. }
  37207. keys.push({
  37208. frame: key.frame,
  37209. value: data
  37210. });
  37211. }
  37212. animation.setKeys(keys);
  37213. if (parsedAnimation.ranges) {
  37214. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  37215. data = parsedAnimation.ranges[index];
  37216. animation.createRange(data.name, data.from, data.to);
  37217. }
  37218. }
  37219. return animation;
  37220. };
  37221. Animation.AppendSerializedAnimations = function (source, destination) {
  37222. if (source.animations) {
  37223. destination.animations = [];
  37224. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  37225. var animation = source.animations[animationIndex];
  37226. destination.animations.push(animation.serialize());
  37227. }
  37228. }
  37229. };
  37230. // Statics
  37231. Animation._ANIMATIONTYPE_FLOAT = 0;
  37232. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  37233. Animation._ANIMATIONTYPE_QUATERNION = 2;
  37234. Animation._ANIMATIONTYPE_MATRIX = 3;
  37235. Animation._ANIMATIONTYPE_COLOR3 = 4;
  37236. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  37237. Animation._ANIMATIONTYPE_SIZE = 6;
  37238. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  37239. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  37240. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  37241. return Animation;
  37242. }());
  37243. BABYLON.Animation = Animation;
  37244. })(BABYLON || (BABYLON = {}));
  37245. //# sourceMappingURL=babylon.animation.js.map
  37246. var BABYLON;
  37247. (function (BABYLON) {
  37248. var Animatable = (function () {
  37249. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  37250. if (fromFrame === void 0) { fromFrame = 0; }
  37251. if (toFrame === void 0) { toFrame = 100; }
  37252. if (loopAnimation === void 0) { loopAnimation = false; }
  37253. if (speedRatio === void 0) { speedRatio = 1.0; }
  37254. this.target = target;
  37255. this.fromFrame = fromFrame;
  37256. this.toFrame = toFrame;
  37257. this.loopAnimation = loopAnimation;
  37258. this.speedRatio = speedRatio;
  37259. this.onAnimationEnd = onAnimationEnd;
  37260. this._localDelayOffset = null;
  37261. this._pausedDelay = null;
  37262. this._animations = new Array();
  37263. this._paused = false;
  37264. this.animationStarted = false;
  37265. if (animations) {
  37266. this.appendAnimations(target, animations);
  37267. }
  37268. this._scene = scene;
  37269. scene._activeAnimatables.push(this);
  37270. }
  37271. // Methods
  37272. Animatable.prototype.getAnimations = function () {
  37273. return this._animations;
  37274. };
  37275. Animatable.prototype.appendAnimations = function (target, animations) {
  37276. for (var index = 0; index < animations.length; index++) {
  37277. var animation = animations[index];
  37278. animation._target = target;
  37279. this._animations.push(animation);
  37280. }
  37281. };
  37282. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  37283. var animations = this._animations;
  37284. for (var index = 0; index < animations.length; index++) {
  37285. if (animations[index].targetProperty === property) {
  37286. return animations[index];
  37287. }
  37288. }
  37289. return null;
  37290. };
  37291. Animatable.prototype.reset = function () {
  37292. var animations = this._animations;
  37293. for (var index = 0; index < animations.length; index++) {
  37294. animations[index].reset();
  37295. }
  37296. this._localDelayOffset = null;
  37297. this._pausedDelay = null;
  37298. };
  37299. Animatable.prototype.enableBlending = function (blendingSpeed) {
  37300. var animations = this._animations;
  37301. for (var index = 0; index < animations.length; index++) {
  37302. animations[index].enableBlending = true;
  37303. animations[index].blendingSpeed = blendingSpeed;
  37304. }
  37305. };
  37306. Animatable.prototype.disableBlending = function () {
  37307. var animations = this._animations;
  37308. for (var index = 0; index < animations.length; index++) {
  37309. animations[index].enableBlending = false;
  37310. }
  37311. };
  37312. Animatable.prototype.goToFrame = function (frame) {
  37313. var animations = this._animations;
  37314. if (animations[0]) {
  37315. var fps = animations[0].framePerSecond;
  37316. var currentFrame = animations[0].currentFrame;
  37317. var adjustTime = frame - currentFrame;
  37318. var delay = adjustTime * 1000 / fps;
  37319. this._localDelayOffset -= delay;
  37320. }
  37321. for (var index = 0; index < animations.length; index++) {
  37322. animations[index].goToFrame(frame);
  37323. }
  37324. };
  37325. Animatable.prototype.pause = function () {
  37326. if (this._paused) {
  37327. return;
  37328. }
  37329. this._paused = true;
  37330. };
  37331. Animatable.prototype.restart = function () {
  37332. this._paused = false;
  37333. };
  37334. Animatable.prototype.stop = function (animationName) {
  37335. if (animationName) {
  37336. var idx = this._scene._activeAnimatables.indexOf(this);
  37337. if (idx > -1) {
  37338. var animations = this._animations;
  37339. for (var index = animations.length - 1; index >= 0; index--) {
  37340. if (typeof animationName === "string" && animations[index].name != animationName) {
  37341. continue;
  37342. }
  37343. animations[index].reset();
  37344. animations.splice(index, 1);
  37345. }
  37346. if (animations.length == 0) {
  37347. this._scene._activeAnimatables.splice(idx, 1);
  37348. if (this.onAnimationEnd) {
  37349. this.onAnimationEnd();
  37350. }
  37351. }
  37352. }
  37353. }
  37354. else {
  37355. var index = this._scene._activeAnimatables.indexOf(this);
  37356. if (index > -1) {
  37357. this._scene._activeAnimatables.splice(index, 1);
  37358. var animations = this._animations;
  37359. for (var index = 0; index < animations.length; index++) {
  37360. animations[index].reset();
  37361. }
  37362. if (this.onAnimationEnd) {
  37363. this.onAnimationEnd();
  37364. }
  37365. }
  37366. }
  37367. };
  37368. Animatable.prototype._animate = function (delay) {
  37369. if (this._paused) {
  37370. this.animationStarted = false;
  37371. if (this._pausedDelay === null) {
  37372. this._pausedDelay = delay;
  37373. }
  37374. return true;
  37375. }
  37376. if (this._localDelayOffset === null) {
  37377. this._localDelayOffset = delay;
  37378. }
  37379. else if (this._pausedDelay !== null) {
  37380. this._localDelayOffset += delay - this._pausedDelay;
  37381. this._pausedDelay = null;
  37382. }
  37383. // Animating
  37384. var running = false;
  37385. var animations = this._animations;
  37386. var index;
  37387. for (index = 0; index < animations.length; index++) {
  37388. var animation = animations[index];
  37389. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  37390. running = running || isRunning;
  37391. }
  37392. this.animationStarted = running;
  37393. if (!running) {
  37394. // Remove from active animatables
  37395. index = this._scene._activeAnimatables.indexOf(this);
  37396. this._scene._activeAnimatables.splice(index, 1);
  37397. }
  37398. if (!running && this.onAnimationEnd) {
  37399. this.onAnimationEnd();
  37400. this.onAnimationEnd = null;
  37401. }
  37402. return running;
  37403. };
  37404. return Animatable;
  37405. }());
  37406. BABYLON.Animatable = Animatable;
  37407. })(BABYLON || (BABYLON = {}));
  37408. //# sourceMappingURL=babylon.animatable.js.map
  37409. var BABYLON;
  37410. (function (BABYLON) {
  37411. var EasingFunction = (function () {
  37412. function EasingFunction() {
  37413. // Properties
  37414. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  37415. }
  37416. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  37417. get: function () {
  37418. return EasingFunction._EASINGMODE_EASEIN;
  37419. },
  37420. enumerable: true,
  37421. configurable: true
  37422. });
  37423. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  37424. get: function () {
  37425. return EasingFunction._EASINGMODE_EASEOUT;
  37426. },
  37427. enumerable: true,
  37428. configurable: true
  37429. });
  37430. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  37431. get: function () {
  37432. return EasingFunction._EASINGMODE_EASEINOUT;
  37433. },
  37434. enumerable: true,
  37435. configurable: true
  37436. });
  37437. EasingFunction.prototype.setEasingMode = function (easingMode) {
  37438. var n = Math.min(Math.max(easingMode, 0), 2);
  37439. this._easingMode = n;
  37440. };
  37441. EasingFunction.prototype.getEasingMode = function () {
  37442. return this._easingMode;
  37443. };
  37444. EasingFunction.prototype.easeInCore = function (gradient) {
  37445. throw new Error('You must implement this method');
  37446. };
  37447. EasingFunction.prototype.ease = function (gradient) {
  37448. switch (this._easingMode) {
  37449. case EasingFunction.EASINGMODE_EASEIN:
  37450. return this.easeInCore(gradient);
  37451. case EasingFunction.EASINGMODE_EASEOUT:
  37452. return (1 - this.easeInCore(1 - gradient));
  37453. }
  37454. if (gradient >= 0.5) {
  37455. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  37456. }
  37457. return (this.easeInCore(gradient * 2) * 0.5);
  37458. };
  37459. //Statics
  37460. EasingFunction._EASINGMODE_EASEIN = 0;
  37461. EasingFunction._EASINGMODE_EASEOUT = 1;
  37462. EasingFunction._EASINGMODE_EASEINOUT = 2;
  37463. return EasingFunction;
  37464. }());
  37465. BABYLON.EasingFunction = EasingFunction;
  37466. var CircleEase = (function (_super) {
  37467. __extends(CircleEase, _super);
  37468. function CircleEase() {
  37469. return _super !== null && _super.apply(this, arguments) || this;
  37470. }
  37471. CircleEase.prototype.easeInCore = function (gradient) {
  37472. gradient = Math.max(0, Math.min(1, gradient));
  37473. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  37474. };
  37475. return CircleEase;
  37476. }(EasingFunction));
  37477. BABYLON.CircleEase = CircleEase;
  37478. var BackEase = (function (_super) {
  37479. __extends(BackEase, _super);
  37480. function BackEase(amplitude) {
  37481. if (amplitude === void 0) { amplitude = 1; }
  37482. var _this = _super.call(this) || this;
  37483. _this.amplitude = amplitude;
  37484. return _this;
  37485. }
  37486. BackEase.prototype.easeInCore = function (gradient) {
  37487. var num = Math.max(0, this.amplitude);
  37488. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  37489. };
  37490. return BackEase;
  37491. }(EasingFunction));
  37492. BABYLON.BackEase = BackEase;
  37493. var BounceEase = (function (_super) {
  37494. __extends(BounceEase, _super);
  37495. function BounceEase(bounces, bounciness) {
  37496. if (bounces === void 0) { bounces = 3; }
  37497. if (bounciness === void 0) { bounciness = 2; }
  37498. var _this = _super.call(this) || this;
  37499. _this.bounces = bounces;
  37500. _this.bounciness = bounciness;
  37501. return _this;
  37502. }
  37503. BounceEase.prototype.easeInCore = function (gradient) {
  37504. var y = Math.max(0.0, this.bounces);
  37505. var bounciness = this.bounciness;
  37506. if (bounciness <= 1.0) {
  37507. bounciness = 1.001;
  37508. }
  37509. var num9 = Math.pow(bounciness, y);
  37510. var num5 = 1.0 - bounciness;
  37511. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  37512. var num15 = gradient * num4;
  37513. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  37514. var num3 = Math.floor(num65);
  37515. var num13 = num3 + 1.0;
  37516. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  37517. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  37518. var num7 = (num8 + num12) * 0.5;
  37519. var num6 = gradient - num7;
  37520. var num2 = num7 - num8;
  37521. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  37522. };
  37523. return BounceEase;
  37524. }(EasingFunction));
  37525. BABYLON.BounceEase = BounceEase;
  37526. var CubicEase = (function (_super) {
  37527. __extends(CubicEase, _super);
  37528. function CubicEase() {
  37529. return _super !== null && _super.apply(this, arguments) || this;
  37530. }
  37531. CubicEase.prototype.easeInCore = function (gradient) {
  37532. return (gradient * gradient * gradient);
  37533. };
  37534. return CubicEase;
  37535. }(EasingFunction));
  37536. BABYLON.CubicEase = CubicEase;
  37537. var ElasticEase = (function (_super) {
  37538. __extends(ElasticEase, _super);
  37539. function ElasticEase(oscillations, springiness) {
  37540. if (oscillations === void 0) { oscillations = 3; }
  37541. if (springiness === void 0) { springiness = 3; }
  37542. var _this = _super.call(this) || this;
  37543. _this.oscillations = oscillations;
  37544. _this.springiness = springiness;
  37545. return _this;
  37546. }
  37547. ElasticEase.prototype.easeInCore = function (gradient) {
  37548. var num2;
  37549. var num3 = Math.max(0.0, this.oscillations);
  37550. var num = Math.max(0.0, this.springiness);
  37551. if (num == 0) {
  37552. num2 = gradient;
  37553. }
  37554. else {
  37555. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  37556. }
  37557. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  37558. };
  37559. return ElasticEase;
  37560. }(EasingFunction));
  37561. BABYLON.ElasticEase = ElasticEase;
  37562. var ExponentialEase = (function (_super) {
  37563. __extends(ExponentialEase, _super);
  37564. function ExponentialEase(exponent) {
  37565. if (exponent === void 0) { exponent = 2; }
  37566. var _this = _super.call(this) || this;
  37567. _this.exponent = exponent;
  37568. return _this;
  37569. }
  37570. ExponentialEase.prototype.easeInCore = function (gradient) {
  37571. if (this.exponent <= 0) {
  37572. return gradient;
  37573. }
  37574. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  37575. };
  37576. return ExponentialEase;
  37577. }(EasingFunction));
  37578. BABYLON.ExponentialEase = ExponentialEase;
  37579. var PowerEase = (function (_super) {
  37580. __extends(PowerEase, _super);
  37581. function PowerEase(power) {
  37582. if (power === void 0) { power = 2; }
  37583. var _this = _super.call(this) || this;
  37584. _this.power = power;
  37585. return _this;
  37586. }
  37587. PowerEase.prototype.easeInCore = function (gradient) {
  37588. var y = Math.max(0.0, this.power);
  37589. return Math.pow(gradient, y);
  37590. };
  37591. return PowerEase;
  37592. }(EasingFunction));
  37593. BABYLON.PowerEase = PowerEase;
  37594. var QuadraticEase = (function (_super) {
  37595. __extends(QuadraticEase, _super);
  37596. function QuadraticEase() {
  37597. return _super !== null && _super.apply(this, arguments) || this;
  37598. }
  37599. QuadraticEase.prototype.easeInCore = function (gradient) {
  37600. return (gradient * gradient);
  37601. };
  37602. return QuadraticEase;
  37603. }(EasingFunction));
  37604. BABYLON.QuadraticEase = QuadraticEase;
  37605. var QuarticEase = (function (_super) {
  37606. __extends(QuarticEase, _super);
  37607. function QuarticEase() {
  37608. return _super !== null && _super.apply(this, arguments) || this;
  37609. }
  37610. QuarticEase.prototype.easeInCore = function (gradient) {
  37611. return (gradient * gradient * gradient * gradient);
  37612. };
  37613. return QuarticEase;
  37614. }(EasingFunction));
  37615. BABYLON.QuarticEase = QuarticEase;
  37616. var QuinticEase = (function (_super) {
  37617. __extends(QuinticEase, _super);
  37618. function QuinticEase() {
  37619. return _super !== null && _super.apply(this, arguments) || this;
  37620. }
  37621. QuinticEase.prototype.easeInCore = function (gradient) {
  37622. return (gradient * gradient * gradient * gradient * gradient);
  37623. };
  37624. return QuinticEase;
  37625. }(EasingFunction));
  37626. BABYLON.QuinticEase = QuinticEase;
  37627. var SineEase = (function (_super) {
  37628. __extends(SineEase, _super);
  37629. function SineEase() {
  37630. return _super !== null && _super.apply(this, arguments) || this;
  37631. }
  37632. SineEase.prototype.easeInCore = function (gradient) {
  37633. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  37634. };
  37635. return SineEase;
  37636. }(EasingFunction));
  37637. BABYLON.SineEase = SineEase;
  37638. var BezierCurveEase = (function (_super) {
  37639. __extends(BezierCurveEase, _super);
  37640. function BezierCurveEase(x1, y1, x2, y2) {
  37641. if (x1 === void 0) { x1 = 0; }
  37642. if (y1 === void 0) { y1 = 0; }
  37643. if (x2 === void 0) { x2 = 1; }
  37644. if (y2 === void 0) { y2 = 1; }
  37645. var _this = _super.call(this) || this;
  37646. _this.x1 = x1;
  37647. _this.y1 = y1;
  37648. _this.x2 = x2;
  37649. _this.y2 = y2;
  37650. return _this;
  37651. }
  37652. BezierCurveEase.prototype.easeInCore = function (gradient) {
  37653. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  37654. };
  37655. return BezierCurveEase;
  37656. }(EasingFunction));
  37657. BABYLON.BezierCurveEase = BezierCurveEase;
  37658. })(BABYLON || (BABYLON = {}));
  37659. //# sourceMappingURL=babylon.easing.js.map
  37660. var BABYLON;
  37661. (function (BABYLON) {
  37662. var Condition = (function () {
  37663. function Condition(actionManager) {
  37664. this._actionManager = actionManager;
  37665. }
  37666. Condition.prototype.isValid = function () {
  37667. return true;
  37668. };
  37669. Condition.prototype._getProperty = function (propertyPath) {
  37670. return this._actionManager._getProperty(propertyPath);
  37671. };
  37672. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  37673. return this._actionManager._getEffectiveTarget(target, propertyPath);
  37674. };
  37675. Condition.prototype.serialize = function () {
  37676. };
  37677. Condition.prototype._serialize = function (serializedCondition) {
  37678. return {
  37679. type: 2,
  37680. children: [],
  37681. name: serializedCondition.name,
  37682. properties: serializedCondition.properties
  37683. };
  37684. };
  37685. return Condition;
  37686. }());
  37687. BABYLON.Condition = Condition;
  37688. var ValueCondition = (function (_super) {
  37689. __extends(ValueCondition, _super);
  37690. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  37691. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  37692. var _this = _super.call(this, actionManager) || this;
  37693. _this.propertyPath = propertyPath;
  37694. _this.value = value;
  37695. _this.operator = operator;
  37696. _this._target = target;
  37697. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  37698. _this._property = _this._getProperty(_this.propertyPath);
  37699. return _this;
  37700. }
  37701. Object.defineProperty(ValueCondition, "IsEqual", {
  37702. get: function () {
  37703. return ValueCondition._IsEqual;
  37704. },
  37705. enumerable: true,
  37706. configurable: true
  37707. });
  37708. Object.defineProperty(ValueCondition, "IsDifferent", {
  37709. get: function () {
  37710. return ValueCondition._IsDifferent;
  37711. },
  37712. enumerable: true,
  37713. configurable: true
  37714. });
  37715. Object.defineProperty(ValueCondition, "IsGreater", {
  37716. get: function () {
  37717. return ValueCondition._IsGreater;
  37718. },
  37719. enumerable: true,
  37720. configurable: true
  37721. });
  37722. Object.defineProperty(ValueCondition, "IsLesser", {
  37723. get: function () {
  37724. return ValueCondition._IsLesser;
  37725. },
  37726. enumerable: true,
  37727. configurable: true
  37728. });
  37729. // Methods
  37730. ValueCondition.prototype.isValid = function () {
  37731. switch (this.operator) {
  37732. case ValueCondition.IsGreater:
  37733. return this._effectiveTarget[this._property] > this.value;
  37734. case ValueCondition.IsLesser:
  37735. return this._effectiveTarget[this._property] < this.value;
  37736. case ValueCondition.IsEqual:
  37737. case ValueCondition.IsDifferent:
  37738. var check;
  37739. if (this.value.equals) {
  37740. check = this.value.equals(this._effectiveTarget[this._property]);
  37741. }
  37742. else {
  37743. check = this.value === this._effectiveTarget[this._property];
  37744. }
  37745. return this.operator === ValueCondition.IsEqual ? check : !check;
  37746. }
  37747. return false;
  37748. };
  37749. ValueCondition.prototype.serialize = function () {
  37750. return this._serialize({
  37751. name: "ValueCondition",
  37752. properties: [
  37753. BABYLON.Action._GetTargetProperty(this._target),
  37754. { name: "propertyPath", value: this.propertyPath },
  37755. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  37756. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  37757. ]
  37758. });
  37759. };
  37760. ValueCondition.GetOperatorName = function (operator) {
  37761. switch (operator) {
  37762. case ValueCondition._IsEqual: return "IsEqual";
  37763. case ValueCondition._IsDifferent: return "IsDifferent";
  37764. case ValueCondition._IsGreater: return "IsGreater";
  37765. case ValueCondition._IsLesser: return "IsLesser";
  37766. default: return "";
  37767. }
  37768. };
  37769. // Statics
  37770. ValueCondition._IsEqual = 0;
  37771. ValueCondition._IsDifferent = 1;
  37772. ValueCondition._IsGreater = 2;
  37773. ValueCondition._IsLesser = 3;
  37774. return ValueCondition;
  37775. }(Condition));
  37776. BABYLON.ValueCondition = ValueCondition;
  37777. var PredicateCondition = (function (_super) {
  37778. __extends(PredicateCondition, _super);
  37779. function PredicateCondition(actionManager, predicate) {
  37780. var _this = _super.call(this, actionManager) || this;
  37781. _this.predicate = predicate;
  37782. return _this;
  37783. }
  37784. PredicateCondition.prototype.isValid = function () {
  37785. return this.predicate();
  37786. };
  37787. return PredicateCondition;
  37788. }(Condition));
  37789. BABYLON.PredicateCondition = PredicateCondition;
  37790. var StateCondition = (function (_super) {
  37791. __extends(StateCondition, _super);
  37792. function StateCondition(actionManager, target, value) {
  37793. var _this = _super.call(this, actionManager) || this;
  37794. _this.value = value;
  37795. _this._target = target;
  37796. return _this;
  37797. }
  37798. // Methods
  37799. StateCondition.prototype.isValid = function () {
  37800. return this._target.state === this.value;
  37801. };
  37802. StateCondition.prototype.serialize = function () {
  37803. return this._serialize({
  37804. name: "StateCondition",
  37805. properties: [
  37806. BABYLON.Action._GetTargetProperty(this._target),
  37807. { name: "value", value: this.value }
  37808. ]
  37809. });
  37810. };
  37811. return StateCondition;
  37812. }(Condition));
  37813. BABYLON.StateCondition = StateCondition;
  37814. })(BABYLON || (BABYLON = {}));
  37815. //# sourceMappingURL=babylon.condition.js.map
  37816. var BABYLON;
  37817. (function (BABYLON) {
  37818. var Action = (function () {
  37819. function Action(triggerOptions, condition) {
  37820. this.triggerOptions = triggerOptions;
  37821. if (triggerOptions.parameter) {
  37822. this.trigger = triggerOptions.trigger;
  37823. this._triggerParameter = triggerOptions.parameter;
  37824. }
  37825. else {
  37826. this.trigger = triggerOptions;
  37827. }
  37828. this._nextActiveAction = this;
  37829. this._condition = condition;
  37830. }
  37831. // Methods
  37832. Action.prototype._prepare = function () {
  37833. };
  37834. Action.prototype.getTriggerParameter = function () {
  37835. return this._triggerParameter;
  37836. };
  37837. Action.prototype._executeCurrent = function (evt) {
  37838. if (this._nextActiveAction._condition) {
  37839. var condition = this._nextActiveAction._condition;
  37840. var currentRenderId = this._actionManager.getScene().getRenderId();
  37841. // We cache the current evaluation for the current frame
  37842. if (condition._evaluationId === currentRenderId) {
  37843. if (!condition._currentResult) {
  37844. return;
  37845. }
  37846. }
  37847. else {
  37848. condition._evaluationId = currentRenderId;
  37849. if (!condition.isValid()) {
  37850. condition._currentResult = false;
  37851. return;
  37852. }
  37853. condition._currentResult = true;
  37854. }
  37855. }
  37856. this._nextActiveAction.execute(evt);
  37857. this.skipToNextActiveAction();
  37858. };
  37859. Action.prototype.execute = function (evt) {
  37860. };
  37861. Action.prototype.skipToNextActiveAction = function () {
  37862. if (this._nextActiveAction._child) {
  37863. if (!this._nextActiveAction._child._actionManager) {
  37864. this._nextActiveAction._child._actionManager = this._actionManager;
  37865. }
  37866. this._nextActiveAction = this._nextActiveAction._child;
  37867. }
  37868. else {
  37869. this._nextActiveAction = this;
  37870. }
  37871. };
  37872. Action.prototype.then = function (action) {
  37873. this._child = action;
  37874. action._actionManager = this._actionManager;
  37875. action._prepare();
  37876. return action;
  37877. };
  37878. Action.prototype._getProperty = function (propertyPath) {
  37879. return this._actionManager._getProperty(propertyPath);
  37880. };
  37881. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  37882. return this._actionManager._getEffectiveTarget(target, propertyPath);
  37883. };
  37884. Action.prototype.serialize = function (parent) {
  37885. };
  37886. // Called by BABYLON.Action objects in serialize(...). Internal use
  37887. Action.prototype._serialize = function (serializedAction, parent) {
  37888. var serializationObject = {
  37889. type: 1,
  37890. children: [],
  37891. name: serializedAction.name,
  37892. properties: serializedAction.properties || []
  37893. };
  37894. // Serialize child
  37895. if (this._child) {
  37896. this._child.serialize(serializationObject);
  37897. }
  37898. // Check if "this" has a condition
  37899. if (this._condition) {
  37900. var serializedCondition = this._condition.serialize();
  37901. serializedCondition.children.push(serializationObject);
  37902. if (parent) {
  37903. parent.children.push(serializedCondition);
  37904. }
  37905. return serializedCondition;
  37906. }
  37907. if (parent) {
  37908. parent.children.push(serializationObject);
  37909. }
  37910. return serializationObject;
  37911. };
  37912. Action._SerializeValueAsString = function (value) {
  37913. if (typeof value === "number") {
  37914. return value.toString();
  37915. }
  37916. if (typeof value === "boolean") {
  37917. return value ? "true" : "false";
  37918. }
  37919. if (value instanceof BABYLON.Vector2) {
  37920. return value.x + ", " + value.y;
  37921. }
  37922. if (value instanceof BABYLON.Vector3) {
  37923. return value.x + ", " + value.y + ", " + value.z;
  37924. }
  37925. if (value instanceof BABYLON.Color3) {
  37926. return value.r + ", " + value.g + ", " + value.b;
  37927. }
  37928. if (value instanceof BABYLON.Color4) {
  37929. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  37930. }
  37931. return value; // string
  37932. };
  37933. Action._GetTargetProperty = function (target) {
  37934. return {
  37935. name: "target",
  37936. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  37937. : target instanceof BABYLON.Light ? "LightProperties"
  37938. : target instanceof BABYLON.Camera ? "CameraProperties"
  37939. : "SceneProperties",
  37940. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  37941. };
  37942. };
  37943. return Action;
  37944. }());
  37945. BABYLON.Action = Action;
  37946. })(BABYLON || (BABYLON = {}));
  37947. //# sourceMappingURL=babylon.action.js.map
  37948. var BABYLON;
  37949. (function (BABYLON) {
  37950. /**
  37951. * ActionEvent is the event beint sent when an action is triggered.
  37952. */
  37953. var ActionEvent = (function () {
  37954. /**
  37955. * @param source The mesh or sprite that triggered the action.
  37956. * @param pointerX The X mouse cursor position at the time of the event
  37957. * @param pointerY The Y mouse cursor position at the time of the event
  37958. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  37959. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  37960. */
  37961. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  37962. this.source = source;
  37963. this.pointerX = pointerX;
  37964. this.pointerY = pointerY;
  37965. this.meshUnderPointer = meshUnderPointer;
  37966. this.sourceEvent = sourceEvent;
  37967. this.additionalData = additionalData;
  37968. }
  37969. /**
  37970. * Helper function to auto-create an ActionEvent from a source mesh.
  37971. * @param source The source mesh that triggered the event
  37972. * @param evt {Event} The original (browser) event
  37973. */
  37974. ActionEvent.CreateNew = function (source, evt, additionalData) {
  37975. var scene = source.getScene();
  37976. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  37977. };
  37978. /**
  37979. * Helper function to auto-create an ActionEvent from a source mesh.
  37980. * @param source The source sprite that triggered the event
  37981. * @param scene Scene associated with the sprite
  37982. * @param evt {Event} The original (browser) event
  37983. */
  37984. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  37985. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  37986. };
  37987. /**
  37988. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  37989. * @param scene the scene where the event occurred
  37990. * @param evt {Event} The original (browser) event
  37991. */
  37992. ActionEvent.CreateNewFromScene = function (scene, evt) {
  37993. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  37994. };
  37995. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  37996. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  37997. };
  37998. return ActionEvent;
  37999. }());
  38000. BABYLON.ActionEvent = ActionEvent;
  38001. /**
  38002. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  38003. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  38004. */
  38005. var ActionManager = (function () {
  38006. function ActionManager(scene) {
  38007. // Members
  38008. this.actions = new Array();
  38009. this.hoverCursor = '';
  38010. this._scene = scene;
  38011. scene._actionManagers.push(this);
  38012. }
  38013. Object.defineProperty(ActionManager, "NothingTrigger", {
  38014. get: function () {
  38015. return ActionManager._NothingTrigger;
  38016. },
  38017. enumerable: true,
  38018. configurable: true
  38019. });
  38020. Object.defineProperty(ActionManager, "OnPickTrigger", {
  38021. get: function () {
  38022. return ActionManager._OnPickTrigger;
  38023. },
  38024. enumerable: true,
  38025. configurable: true
  38026. });
  38027. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  38028. get: function () {
  38029. return ActionManager._OnLeftPickTrigger;
  38030. },
  38031. enumerable: true,
  38032. configurable: true
  38033. });
  38034. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  38035. get: function () {
  38036. return ActionManager._OnRightPickTrigger;
  38037. },
  38038. enumerable: true,
  38039. configurable: true
  38040. });
  38041. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  38042. get: function () {
  38043. return ActionManager._OnCenterPickTrigger;
  38044. },
  38045. enumerable: true,
  38046. configurable: true
  38047. });
  38048. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  38049. get: function () {
  38050. return ActionManager._OnPickDownTrigger;
  38051. },
  38052. enumerable: true,
  38053. configurable: true
  38054. });
  38055. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  38056. get: function () {
  38057. return ActionManager._OnDoublePickTrigger;
  38058. },
  38059. enumerable: true,
  38060. configurable: true
  38061. });
  38062. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  38063. get: function () {
  38064. return ActionManager._OnPickUpTrigger;
  38065. },
  38066. enumerable: true,
  38067. configurable: true
  38068. });
  38069. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  38070. /// This trigger will only be raised if you also declared a OnPickDown
  38071. get: function () {
  38072. return ActionManager._OnPickOutTrigger;
  38073. },
  38074. enumerable: true,
  38075. configurable: true
  38076. });
  38077. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  38078. get: function () {
  38079. return ActionManager._OnLongPressTrigger;
  38080. },
  38081. enumerable: true,
  38082. configurable: true
  38083. });
  38084. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  38085. get: function () {
  38086. return ActionManager._OnPointerOverTrigger;
  38087. },
  38088. enumerable: true,
  38089. configurable: true
  38090. });
  38091. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  38092. get: function () {
  38093. return ActionManager._OnPointerOutTrigger;
  38094. },
  38095. enumerable: true,
  38096. configurable: true
  38097. });
  38098. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  38099. get: function () {
  38100. return ActionManager._OnEveryFrameTrigger;
  38101. },
  38102. enumerable: true,
  38103. configurable: true
  38104. });
  38105. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  38106. get: function () {
  38107. return ActionManager._OnIntersectionEnterTrigger;
  38108. },
  38109. enumerable: true,
  38110. configurable: true
  38111. });
  38112. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  38113. get: function () {
  38114. return ActionManager._OnIntersectionExitTrigger;
  38115. },
  38116. enumerable: true,
  38117. configurable: true
  38118. });
  38119. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  38120. get: function () {
  38121. return ActionManager._OnKeyDownTrigger;
  38122. },
  38123. enumerable: true,
  38124. configurable: true
  38125. });
  38126. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  38127. get: function () {
  38128. return ActionManager._OnKeyUpTrigger;
  38129. },
  38130. enumerable: true,
  38131. configurable: true
  38132. });
  38133. // Methods
  38134. ActionManager.prototype.dispose = function () {
  38135. var index = this._scene._actionManagers.indexOf(this);
  38136. for (var i = 0; i < this.actions.length; i++) {
  38137. var action = this.actions[i];
  38138. ActionManager.Triggers[action.trigger]--;
  38139. if (ActionManager.Triggers[action.trigger] === 0) {
  38140. delete ActionManager.Triggers[action.trigger];
  38141. }
  38142. }
  38143. if (index > -1) {
  38144. this._scene._actionManagers.splice(index, 1);
  38145. }
  38146. };
  38147. ActionManager.prototype.getScene = function () {
  38148. return this._scene;
  38149. };
  38150. /**
  38151. * Does this action manager handles actions of any of the given triggers
  38152. * @param {number[]} triggers - the triggers to be tested
  38153. * @return {boolean} whether one (or more) of the triggers is handeled
  38154. */
  38155. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  38156. for (var index = 0; index < this.actions.length; index++) {
  38157. var action = this.actions[index];
  38158. if (triggers.indexOf(action.trigger) > -1) {
  38159. return true;
  38160. }
  38161. }
  38162. return false;
  38163. };
  38164. /**
  38165. * Does this action manager handles actions of a given trigger
  38166. * @param {number} trigger - the trigger to be tested
  38167. * @return {boolean} whether the trigger is handeled
  38168. */
  38169. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  38170. for (var index = 0; index < this.actions.length; index++) {
  38171. var action = this.actions[index];
  38172. if (action.trigger === trigger) {
  38173. return true;
  38174. }
  38175. }
  38176. return false;
  38177. };
  38178. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  38179. /**
  38180. * Does this action manager has pointer triggers
  38181. * @return {boolean} whether or not it has pointer triggers
  38182. */
  38183. get: function () {
  38184. for (var index = 0; index < this.actions.length; index++) {
  38185. var action = this.actions[index];
  38186. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  38187. return true;
  38188. }
  38189. }
  38190. return false;
  38191. },
  38192. enumerable: true,
  38193. configurable: true
  38194. });
  38195. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  38196. /**
  38197. * Does this action manager has pick triggers
  38198. * @return {boolean} whether or not it has pick triggers
  38199. */
  38200. get: function () {
  38201. for (var index = 0; index < this.actions.length; index++) {
  38202. var action = this.actions[index];
  38203. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  38204. return true;
  38205. }
  38206. }
  38207. return false;
  38208. },
  38209. enumerable: true,
  38210. configurable: true
  38211. });
  38212. Object.defineProperty(ActionManager, "HasTriggers", {
  38213. /**
  38214. * Does exist one action manager with at least one trigger
  38215. * @return {boolean} whether or not it exists one action manager with one trigger
  38216. **/
  38217. get: function () {
  38218. for (var t in ActionManager.Triggers) {
  38219. if (ActionManager.Triggers.hasOwnProperty(t)) {
  38220. return true;
  38221. }
  38222. }
  38223. return false;
  38224. },
  38225. enumerable: true,
  38226. configurable: true
  38227. });
  38228. Object.defineProperty(ActionManager, "HasPickTriggers", {
  38229. /**
  38230. * Does exist one action manager with at least one pick trigger
  38231. * @return {boolean} whether or not it exists one action manager with one pick trigger
  38232. **/
  38233. get: function () {
  38234. for (var t in ActionManager.Triggers) {
  38235. if (ActionManager.Triggers.hasOwnProperty(t)) {
  38236. var t_int = parseInt(t);
  38237. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  38238. return true;
  38239. }
  38240. }
  38241. }
  38242. return false;
  38243. },
  38244. enumerable: true,
  38245. configurable: true
  38246. });
  38247. /**
  38248. * Does exist one action manager that handles actions of a given trigger
  38249. * @param {number} trigger - the trigger to be tested
  38250. * @return {boolean} whether the trigger is handeled by at least one action manager
  38251. **/
  38252. ActionManager.HasSpecificTrigger = function (trigger) {
  38253. for (var t in ActionManager.Triggers) {
  38254. if (ActionManager.Triggers.hasOwnProperty(t)) {
  38255. var t_int = parseInt(t);
  38256. if (t_int === trigger) {
  38257. return true;
  38258. }
  38259. }
  38260. }
  38261. return false;
  38262. };
  38263. /**
  38264. * Registers an action to this action manager
  38265. * @param {BABYLON.Action} action - the action to be registered
  38266. * @return {BABYLON.Action} the action amended (prepared) after registration
  38267. */
  38268. ActionManager.prototype.registerAction = function (action) {
  38269. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  38270. if (this.getScene().actionManager !== this) {
  38271. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  38272. return null;
  38273. }
  38274. }
  38275. this.actions.push(action);
  38276. if (ActionManager.Triggers[action.trigger]) {
  38277. ActionManager.Triggers[action.trigger]++;
  38278. }
  38279. else {
  38280. ActionManager.Triggers[action.trigger] = 1;
  38281. }
  38282. action._actionManager = this;
  38283. action._prepare();
  38284. return action;
  38285. };
  38286. /**
  38287. * Process a specific trigger
  38288. * @param {number} trigger - the trigger to process
  38289. * @param evt {BABYLON.ActionEvent} the event details to be processed
  38290. */
  38291. ActionManager.prototype.processTrigger = function (trigger, evt) {
  38292. for (var index = 0; index < this.actions.length; index++) {
  38293. var action = this.actions[index];
  38294. if (action.trigger === trigger) {
  38295. if (trigger === ActionManager.OnKeyUpTrigger
  38296. || trigger === ActionManager.OnKeyDownTrigger) {
  38297. var parameter = action.getTriggerParameter();
  38298. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  38299. if (!parameter.toLowerCase) {
  38300. continue;
  38301. }
  38302. var lowerCase = parameter.toLowerCase();
  38303. if (lowerCase !== evt.sourceEvent.key) {
  38304. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  38305. var actualkey = String.fromCharCode(unicode).toLowerCase();
  38306. if (actualkey !== lowerCase) {
  38307. continue;
  38308. }
  38309. }
  38310. }
  38311. }
  38312. action._executeCurrent(evt);
  38313. }
  38314. }
  38315. };
  38316. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  38317. var properties = propertyPath.split(".");
  38318. for (var index = 0; index < properties.length - 1; index++) {
  38319. target = target[properties[index]];
  38320. }
  38321. return target;
  38322. };
  38323. ActionManager.prototype._getProperty = function (propertyPath) {
  38324. var properties = propertyPath.split(".");
  38325. return properties[properties.length - 1];
  38326. };
  38327. ActionManager.prototype.serialize = function (name) {
  38328. var root = {
  38329. children: [],
  38330. name: name,
  38331. type: 3,
  38332. properties: [] // Empty for root but required
  38333. };
  38334. for (var i = 0; i < this.actions.length; i++) {
  38335. var triggerObject = {
  38336. type: 0,
  38337. children: [],
  38338. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  38339. properties: []
  38340. };
  38341. var triggerOptions = this.actions[i].triggerOptions;
  38342. if (triggerOptions && typeof triggerOptions !== "number") {
  38343. if (triggerOptions.parameter instanceof BABYLON.Node) {
  38344. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  38345. }
  38346. else {
  38347. var parameter = {};
  38348. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  38349. if (triggerOptions.parameter.mesh) {
  38350. parameter._meshId = triggerOptions.parameter.mesh.id;
  38351. }
  38352. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  38353. }
  38354. }
  38355. // Serialize child action, recursively
  38356. this.actions[i].serialize(triggerObject);
  38357. // Add serialized trigger
  38358. root.children.push(triggerObject);
  38359. }
  38360. return root;
  38361. };
  38362. ActionManager.Parse = function (parsedActions, object, scene) {
  38363. var actionManager = new BABYLON.ActionManager(scene);
  38364. if (object === null)
  38365. scene.actionManager = actionManager;
  38366. else
  38367. object.actionManager = actionManager;
  38368. // instanciate a new object
  38369. var instanciate = function (name, params) {
  38370. var newInstance = Object.create(BABYLON[name].prototype);
  38371. newInstance.constructor.apply(newInstance, params);
  38372. return newInstance;
  38373. };
  38374. var parseParameter = function (name, value, target, propertyPath) {
  38375. if (propertyPath === null) {
  38376. // String, boolean or float
  38377. var floatValue = parseFloat(value);
  38378. if (value === "true" || value === "false")
  38379. return value === "true";
  38380. else
  38381. return isNaN(floatValue) ? value : floatValue;
  38382. }
  38383. var effectiveTarget = propertyPath.split(".");
  38384. var values = value.split(",");
  38385. // Get effective Target
  38386. for (var i = 0; i < effectiveTarget.length; i++) {
  38387. target = target[effectiveTarget[i]];
  38388. }
  38389. // Return appropriate value with its type
  38390. if (typeof (target) === "boolean")
  38391. return values[0] === "true";
  38392. if (typeof (target) === "string")
  38393. return values[0];
  38394. // Parameters with multiple values such as Vector3 etc.
  38395. var split = new Array();
  38396. for (var i = 0; i < values.length; i++)
  38397. split.push(parseFloat(values[i]));
  38398. if (target instanceof BABYLON.Vector3)
  38399. return BABYLON.Vector3.FromArray(split);
  38400. if (target instanceof BABYLON.Vector4)
  38401. return BABYLON.Vector4.FromArray(split);
  38402. if (target instanceof BABYLON.Color3)
  38403. return BABYLON.Color3.FromArray(split);
  38404. if (target instanceof BABYLON.Color4)
  38405. return BABYLON.Color4.FromArray(split);
  38406. return parseFloat(values[0]);
  38407. };
  38408. // traverse graph per trigger
  38409. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  38410. if (combineArray === void 0) { combineArray = null; }
  38411. if (parsedAction.detached)
  38412. return;
  38413. var parameters = new Array();
  38414. var target = null;
  38415. var propertyPath = null;
  38416. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  38417. // Parameters
  38418. if (parsedAction.type === 2)
  38419. parameters.push(actionManager);
  38420. else
  38421. parameters.push(trigger);
  38422. if (combine) {
  38423. var actions = new Array();
  38424. for (var j = 0; j < parsedAction.combine.length; j++) {
  38425. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  38426. }
  38427. parameters.push(actions);
  38428. }
  38429. else {
  38430. for (var i = 0; i < parsedAction.properties.length; i++) {
  38431. var value = parsedAction.properties[i].value;
  38432. var name = parsedAction.properties[i].name;
  38433. var targetType = parsedAction.properties[i].targetType;
  38434. if (name === "target")
  38435. if (targetType !== null && targetType === "SceneProperties")
  38436. value = target = scene;
  38437. else
  38438. value = target = scene.getNodeByName(value);
  38439. else if (name === "parent")
  38440. value = scene.getNodeByName(value);
  38441. else if (name === "sound")
  38442. value = scene.getSoundByName(value);
  38443. else if (name !== "propertyPath") {
  38444. if (parsedAction.type === 2 && name === "operator")
  38445. value = BABYLON.ValueCondition[value];
  38446. else
  38447. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  38448. }
  38449. else {
  38450. propertyPath = value;
  38451. }
  38452. parameters.push(value);
  38453. }
  38454. }
  38455. if (combineArray === null) {
  38456. parameters.push(condition);
  38457. }
  38458. else {
  38459. parameters.push(null);
  38460. }
  38461. // If interpolate value action
  38462. if (parsedAction.name === "InterpolateValueAction") {
  38463. var param = parameters[parameters.length - 2];
  38464. parameters[parameters.length - 1] = param;
  38465. parameters[parameters.length - 2] = condition;
  38466. }
  38467. // Action or condition(s) and not CombineAction
  38468. var newAction = instanciate(parsedAction.name, parameters);
  38469. if (newAction instanceof BABYLON.Condition && condition !== null) {
  38470. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  38471. if (action)
  38472. action.then(nothing);
  38473. else
  38474. actionManager.registerAction(nothing);
  38475. action = nothing;
  38476. }
  38477. if (combineArray === null) {
  38478. if (newAction instanceof BABYLON.Condition) {
  38479. condition = newAction;
  38480. newAction = action;
  38481. }
  38482. else {
  38483. condition = null;
  38484. if (action)
  38485. action.then(newAction);
  38486. else
  38487. actionManager.registerAction(newAction);
  38488. }
  38489. }
  38490. else {
  38491. combineArray.push(newAction);
  38492. }
  38493. for (var i = 0; i < parsedAction.children.length; i++)
  38494. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  38495. };
  38496. // triggers
  38497. for (var i = 0; i < parsedActions.children.length; i++) {
  38498. var triggerParams;
  38499. var trigger = parsedActions.children[i];
  38500. if (trigger.properties.length > 0) {
  38501. var param = trigger.properties[0].value;
  38502. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  38503. if (value._meshId) {
  38504. value.mesh = scene.getMeshByID(value._meshId);
  38505. }
  38506. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  38507. }
  38508. else
  38509. triggerParams = BABYLON.ActionManager[trigger.name];
  38510. for (var j = 0; j < trigger.children.length; j++) {
  38511. if (!trigger.detached)
  38512. traverse(trigger.children[j], triggerParams, null, null);
  38513. }
  38514. }
  38515. };
  38516. ActionManager.GetTriggerName = function (trigger) {
  38517. switch (trigger) {
  38518. case 0: return "NothingTrigger";
  38519. case 1: return "OnPickTrigger";
  38520. case 2: return "OnLeftPickTrigger";
  38521. case 3: return "OnRightPickTrigger";
  38522. case 4: return "OnCenterPickTrigger";
  38523. case 5: return "OnPickDownTrigger";
  38524. case 6: return "OnPickUpTrigger";
  38525. case 7: return "OnLongPressTrigger";
  38526. case 8: return "OnPointerOverTrigger";
  38527. case 9: return "OnPointerOutTrigger";
  38528. case 10: return "OnEveryFrameTrigger";
  38529. case 11: return "OnIntersectionEnterTrigger";
  38530. case 12: return "OnIntersectionExitTrigger";
  38531. case 13: return "OnKeyDownTrigger";
  38532. case 14: return "OnKeyUpTrigger";
  38533. case 15: return "OnPickOutTrigger";
  38534. default: return "";
  38535. }
  38536. };
  38537. // Statics
  38538. ActionManager._NothingTrigger = 0;
  38539. ActionManager._OnPickTrigger = 1;
  38540. ActionManager._OnLeftPickTrigger = 2;
  38541. ActionManager._OnRightPickTrigger = 3;
  38542. ActionManager._OnCenterPickTrigger = 4;
  38543. ActionManager._OnPickDownTrigger = 5;
  38544. ActionManager._OnDoublePickTrigger = 6;
  38545. ActionManager._OnPickUpTrigger = 7;
  38546. ActionManager._OnLongPressTrigger = 8;
  38547. ActionManager._OnPointerOverTrigger = 9;
  38548. ActionManager._OnPointerOutTrigger = 10;
  38549. ActionManager._OnEveryFrameTrigger = 11;
  38550. ActionManager._OnIntersectionEnterTrigger = 12;
  38551. ActionManager._OnIntersectionExitTrigger = 13;
  38552. ActionManager._OnKeyDownTrigger = 14;
  38553. ActionManager._OnKeyUpTrigger = 15;
  38554. ActionManager._OnPickOutTrigger = 16;
  38555. ActionManager.Triggers = {};
  38556. return ActionManager;
  38557. }());
  38558. BABYLON.ActionManager = ActionManager;
  38559. })(BABYLON || (BABYLON = {}));
  38560. //# sourceMappingURL=babylon.actionManager.js.map
  38561. var BABYLON;
  38562. (function (BABYLON) {
  38563. var InterpolateValueAction = (function (_super) {
  38564. __extends(InterpolateValueAction, _super);
  38565. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  38566. if (duration === void 0) { duration = 1000; }
  38567. var _this = _super.call(this, triggerOptions, condition) || this;
  38568. _this.propertyPath = propertyPath;
  38569. _this.value = value;
  38570. _this.duration = duration;
  38571. _this.stopOtherAnimations = stopOtherAnimations;
  38572. _this.onInterpolationDone = onInterpolationDone;
  38573. _this._target = _this._effectiveTarget = target;
  38574. return _this;
  38575. }
  38576. InterpolateValueAction.prototype._prepare = function () {
  38577. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  38578. this._property = this._getProperty(this.propertyPath);
  38579. };
  38580. InterpolateValueAction.prototype.execute = function () {
  38581. var scene = this._actionManager.getScene();
  38582. var keys = [
  38583. {
  38584. frame: 0,
  38585. value: this._effectiveTarget[this._property]
  38586. }, {
  38587. frame: 100,
  38588. value: this.value
  38589. }
  38590. ];
  38591. var dataType;
  38592. if (typeof this.value === "number") {
  38593. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  38594. }
  38595. else if (this.value instanceof BABYLON.Color3) {
  38596. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  38597. }
  38598. else if (this.value instanceof BABYLON.Vector3) {
  38599. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  38600. }
  38601. else if (this.value instanceof BABYLON.Matrix) {
  38602. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  38603. }
  38604. else if (this.value instanceof BABYLON.Quaternion) {
  38605. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  38606. }
  38607. else {
  38608. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  38609. return;
  38610. }
  38611. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  38612. animation.setKeys(keys);
  38613. if (this.stopOtherAnimations) {
  38614. scene.stopAnimation(this._effectiveTarget);
  38615. }
  38616. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  38617. };
  38618. InterpolateValueAction.prototype.serialize = function (parent) {
  38619. return _super.prototype._serialize.call(this, {
  38620. name: "InterpolateValueAction",
  38621. properties: [
  38622. BABYLON.Action._GetTargetProperty(this._target),
  38623. { name: "propertyPath", value: this.propertyPath },
  38624. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  38625. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  38626. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  38627. ]
  38628. }, parent);
  38629. };
  38630. return InterpolateValueAction;
  38631. }(BABYLON.Action));
  38632. BABYLON.InterpolateValueAction = InterpolateValueAction;
  38633. })(BABYLON || (BABYLON = {}));
  38634. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  38635. var BABYLON;
  38636. (function (BABYLON) {
  38637. var SwitchBooleanAction = (function (_super) {
  38638. __extends(SwitchBooleanAction, _super);
  38639. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  38640. var _this = _super.call(this, triggerOptions, condition) || this;
  38641. _this.propertyPath = propertyPath;
  38642. _this._target = _this._effectiveTarget = target;
  38643. return _this;
  38644. }
  38645. SwitchBooleanAction.prototype._prepare = function () {
  38646. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  38647. this._property = this._getProperty(this.propertyPath);
  38648. };
  38649. SwitchBooleanAction.prototype.execute = function () {
  38650. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  38651. };
  38652. SwitchBooleanAction.prototype.serialize = function (parent) {
  38653. return _super.prototype._serialize.call(this, {
  38654. name: "SwitchBooleanAction",
  38655. properties: [
  38656. BABYLON.Action._GetTargetProperty(this._target),
  38657. { name: "propertyPath", value: this.propertyPath }
  38658. ]
  38659. }, parent);
  38660. };
  38661. return SwitchBooleanAction;
  38662. }(BABYLON.Action));
  38663. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  38664. var SetStateAction = (function (_super) {
  38665. __extends(SetStateAction, _super);
  38666. function SetStateAction(triggerOptions, target, value, condition) {
  38667. var _this = _super.call(this, triggerOptions, condition) || this;
  38668. _this.value = value;
  38669. _this._target = target;
  38670. return _this;
  38671. }
  38672. SetStateAction.prototype.execute = function () {
  38673. this._target.state = this.value;
  38674. };
  38675. SetStateAction.prototype.serialize = function (parent) {
  38676. return _super.prototype._serialize.call(this, {
  38677. name: "SetStateAction",
  38678. properties: [
  38679. BABYLON.Action._GetTargetProperty(this._target),
  38680. { name: "value", value: this.value }
  38681. ]
  38682. }, parent);
  38683. };
  38684. return SetStateAction;
  38685. }(BABYLON.Action));
  38686. BABYLON.SetStateAction = SetStateAction;
  38687. var SetValueAction = (function (_super) {
  38688. __extends(SetValueAction, _super);
  38689. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  38690. var _this = _super.call(this, triggerOptions, condition) || this;
  38691. _this.propertyPath = propertyPath;
  38692. _this.value = value;
  38693. _this._target = _this._effectiveTarget = target;
  38694. return _this;
  38695. }
  38696. SetValueAction.prototype._prepare = function () {
  38697. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  38698. this._property = this._getProperty(this.propertyPath);
  38699. };
  38700. SetValueAction.prototype.execute = function () {
  38701. this._effectiveTarget[this._property] = this.value;
  38702. if (this._target.markAsDirty) {
  38703. this._target.markAsDirty(this._property);
  38704. }
  38705. };
  38706. SetValueAction.prototype.serialize = function (parent) {
  38707. return _super.prototype._serialize.call(this, {
  38708. name: "SetValueAction",
  38709. properties: [
  38710. BABYLON.Action._GetTargetProperty(this._target),
  38711. { name: "propertyPath", value: this.propertyPath },
  38712. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  38713. ]
  38714. }, parent);
  38715. };
  38716. return SetValueAction;
  38717. }(BABYLON.Action));
  38718. BABYLON.SetValueAction = SetValueAction;
  38719. var IncrementValueAction = (function (_super) {
  38720. __extends(IncrementValueAction, _super);
  38721. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  38722. var _this = _super.call(this, triggerOptions, condition) || this;
  38723. _this.propertyPath = propertyPath;
  38724. _this.value = value;
  38725. _this._target = _this._effectiveTarget = target;
  38726. return _this;
  38727. }
  38728. IncrementValueAction.prototype._prepare = function () {
  38729. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  38730. this._property = this._getProperty(this.propertyPath);
  38731. if (typeof this._effectiveTarget[this._property] !== "number") {
  38732. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  38733. }
  38734. };
  38735. IncrementValueAction.prototype.execute = function () {
  38736. this._effectiveTarget[this._property] += this.value;
  38737. if (this._target.markAsDirty) {
  38738. this._target.markAsDirty(this._property);
  38739. }
  38740. };
  38741. IncrementValueAction.prototype.serialize = function (parent) {
  38742. return _super.prototype._serialize.call(this, {
  38743. name: "IncrementValueAction",
  38744. properties: [
  38745. BABYLON.Action._GetTargetProperty(this._target),
  38746. { name: "propertyPath", value: this.propertyPath },
  38747. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  38748. ]
  38749. }, parent);
  38750. };
  38751. return IncrementValueAction;
  38752. }(BABYLON.Action));
  38753. BABYLON.IncrementValueAction = IncrementValueAction;
  38754. var PlayAnimationAction = (function (_super) {
  38755. __extends(PlayAnimationAction, _super);
  38756. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  38757. var _this = _super.call(this, triggerOptions, condition) || this;
  38758. _this.from = from;
  38759. _this.to = to;
  38760. _this.loop = loop;
  38761. _this._target = target;
  38762. return _this;
  38763. }
  38764. PlayAnimationAction.prototype._prepare = function () {
  38765. };
  38766. PlayAnimationAction.prototype.execute = function () {
  38767. var scene = this._actionManager.getScene();
  38768. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  38769. };
  38770. PlayAnimationAction.prototype.serialize = function (parent) {
  38771. return _super.prototype._serialize.call(this, {
  38772. name: "PlayAnimationAction",
  38773. properties: [
  38774. BABYLON.Action._GetTargetProperty(this._target),
  38775. { name: "from", value: String(this.from) },
  38776. { name: "to", value: String(this.to) },
  38777. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  38778. ]
  38779. }, parent);
  38780. };
  38781. return PlayAnimationAction;
  38782. }(BABYLON.Action));
  38783. BABYLON.PlayAnimationAction = PlayAnimationAction;
  38784. var StopAnimationAction = (function (_super) {
  38785. __extends(StopAnimationAction, _super);
  38786. function StopAnimationAction(triggerOptions, target, condition) {
  38787. var _this = _super.call(this, triggerOptions, condition) || this;
  38788. _this._target = target;
  38789. return _this;
  38790. }
  38791. StopAnimationAction.prototype._prepare = function () {
  38792. };
  38793. StopAnimationAction.prototype.execute = function () {
  38794. var scene = this._actionManager.getScene();
  38795. scene.stopAnimation(this._target);
  38796. };
  38797. StopAnimationAction.prototype.serialize = function (parent) {
  38798. return _super.prototype._serialize.call(this, {
  38799. name: "StopAnimationAction",
  38800. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  38801. }, parent);
  38802. };
  38803. return StopAnimationAction;
  38804. }(BABYLON.Action));
  38805. BABYLON.StopAnimationAction = StopAnimationAction;
  38806. var DoNothingAction = (function (_super) {
  38807. __extends(DoNothingAction, _super);
  38808. function DoNothingAction(triggerOptions, condition) {
  38809. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  38810. return _super.call(this, triggerOptions, condition) || this;
  38811. }
  38812. DoNothingAction.prototype.execute = function () {
  38813. };
  38814. DoNothingAction.prototype.serialize = function (parent) {
  38815. return _super.prototype._serialize.call(this, {
  38816. name: "DoNothingAction",
  38817. properties: []
  38818. }, parent);
  38819. };
  38820. return DoNothingAction;
  38821. }(BABYLON.Action));
  38822. BABYLON.DoNothingAction = DoNothingAction;
  38823. var CombineAction = (function (_super) {
  38824. __extends(CombineAction, _super);
  38825. function CombineAction(triggerOptions, children, condition) {
  38826. var _this = _super.call(this, triggerOptions, condition) || this;
  38827. _this.children = children;
  38828. return _this;
  38829. }
  38830. CombineAction.prototype._prepare = function () {
  38831. for (var index = 0; index < this.children.length; index++) {
  38832. this.children[index]._actionManager = this._actionManager;
  38833. this.children[index]._prepare();
  38834. }
  38835. };
  38836. CombineAction.prototype.execute = function (evt) {
  38837. for (var index = 0; index < this.children.length; index++) {
  38838. this.children[index].execute(evt);
  38839. }
  38840. };
  38841. CombineAction.prototype.serialize = function (parent) {
  38842. var serializationObject = _super.prototype._serialize.call(this, {
  38843. name: "CombineAction",
  38844. properties: [],
  38845. combine: []
  38846. }, parent);
  38847. for (var i = 0; i < this.children.length; i++) {
  38848. serializationObject.combine.push(this.children[i].serialize(null));
  38849. }
  38850. return serializationObject;
  38851. };
  38852. return CombineAction;
  38853. }(BABYLON.Action));
  38854. BABYLON.CombineAction = CombineAction;
  38855. var ExecuteCodeAction = (function (_super) {
  38856. __extends(ExecuteCodeAction, _super);
  38857. function ExecuteCodeAction(triggerOptions, func, condition) {
  38858. var _this = _super.call(this, triggerOptions, condition) || this;
  38859. _this.func = func;
  38860. return _this;
  38861. }
  38862. ExecuteCodeAction.prototype.execute = function (evt) {
  38863. this.func(evt);
  38864. };
  38865. return ExecuteCodeAction;
  38866. }(BABYLON.Action));
  38867. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  38868. var SetParentAction = (function (_super) {
  38869. __extends(SetParentAction, _super);
  38870. function SetParentAction(triggerOptions, target, parent, condition) {
  38871. var _this = _super.call(this, triggerOptions, condition) || this;
  38872. _this._target = target;
  38873. _this._parent = parent;
  38874. return _this;
  38875. }
  38876. SetParentAction.prototype._prepare = function () {
  38877. };
  38878. SetParentAction.prototype.execute = function () {
  38879. if (this._target.parent === this._parent) {
  38880. return;
  38881. }
  38882. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  38883. invertParentWorldMatrix.invert();
  38884. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  38885. this._target.parent = this._parent;
  38886. };
  38887. SetParentAction.prototype.serialize = function (parent) {
  38888. return _super.prototype._serialize.call(this, {
  38889. name: "SetParentAction",
  38890. properties: [
  38891. BABYLON.Action._GetTargetProperty(this._target),
  38892. BABYLON.Action._GetTargetProperty(this._parent),
  38893. ]
  38894. }, parent);
  38895. };
  38896. return SetParentAction;
  38897. }(BABYLON.Action));
  38898. BABYLON.SetParentAction = SetParentAction;
  38899. var PlaySoundAction = (function (_super) {
  38900. __extends(PlaySoundAction, _super);
  38901. function PlaySoundAction(triggerOptions, sound, condition) {
  38902. var _this = _super.call(this, triggerOptions, condition) || this;
  38903. _this._sound = sound;
  38904. return _this;
  38905. }
  38906. PlaySoundAction.prototype._prepare = function () {
  38907. };
  38908. PlaySoundAction.prototype.execute = function () {
  38909. if (this._sound !== undefined)
  38910. this._sound.play();
  38911. };
  38912. PlaySoundAction.prototype.serialize = function (parent) {
  38913. return _super.prototype._serialize.call(this, {
  38914. name: "PlaySoundAction",
  38915. properties: [{ name: "sound", value: this._sound.name }]
  38916. }, parent);
  38917. };
  38918. return PlaySoundAction;
  38919. }(BABYLON.Action));
  38920. BABYLON.PlaySoundAction = PlaySoundAction;
  38921. var StopSoundAction = (function (_super) {
  38922. __extends(StopSoundAction, _super);
  38923. function StopSoundAction(triggerOptions, sound, condition) {
  38924. var _this = _super.call(this, triggerOptions, condition) || this;
  38925. _this._sound = sound;
  38926. return _this;
  38927. }
  38928. StopSoundAction.prototype._prepare = function () {
  38929. };
  38930. StopSoundAction.prototype.execute = function () {
  38931. if (this._sound !== undefined)
  38932. this._sound.stop();
  38933. };
  38934. StopSoundAction.prototype.serialize = function (parent) {
  38935. return _super.prototype._serialize.call(this, {
  38936. name: "StopSoundAction",
  38937. properties: [{ name: "sound", value: this._sound.name }]
  38938. }, parent);
  38939. };
  38940. return StopSoundAction;
  38941. }(BABYLON.Action));
  38942. BABYLON.StopSoundAction = StopSoundAction;
  38943. })(BABYLON || (BABYLON = {}));
  38944. //# sourceMappingURL=babylon.directActions.js.map
  38945. var BABYLON;
  38946. (function (BABYLON) {
  38947. var SpriteManager = (function () {
  38948. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  38949. if (epsilon === void 0) { epsilon = 0.01; }
  38950. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38951. this.name = name;
  38952. this.sprites = new Array();
  38953. this.renderingGroupId = 0;
  38954. this.layerMask = 0x0FFFFFFF;
  38955. this.fogEnabled = true;
  38956. this.isPickable = false;
  38957. /**
  38958. * An event triggered when the manager is disposed.
  38959. * @type {BABYLON.Observable}
  38960. */
  38961. this.onDisposeObservable = new BABYLON.Observable();
  38962. this._vertexBuffers = {};
  38963. this._capacity = capacity;
  38964. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  38965. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38966. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38967. if (cellSize.width && cellSize.height) {
  38968. this.cellWidth = cellSize.width;
  38969. this.cellHeight = cellSize.height;
  38970. }
  38971. else if (cellSize !== undefined) {
  38972. this.cellWidth = cellSize;
  38973. this.cellHeight = cellSize;
  38974. }
  38975. else {
  38976. return;
  38977. }
  38978. this._epsilon = epsilon;
  38979. this._scene = scene;
  38980. this._scene.spriteManagers.push(this);
  38981. var indices = [];
  38982. var index = 0;
  38983. for (var count = 0; count < capacity; count++) {
  38984. indices.push(index);
  38985. indices.push(index + 1);
  38986. indices.push(index + 2);
  38987. indices.push(index);
  38988. indices.push(index + 2);
  38989. indices.push(index + 3);
  38990. index += 4;
  38991. }
  38992. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  38993. // VBO
  38994. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  38995. this._vertexData = new Float32Array(capacity * 16 * 4);
  38996. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  38997. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  38998. var options = this._buffer.createVertexBuffer("options", 4, 4);
  38999. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  39000. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  39001. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  39002. this._vertexBuffers["options"] = options;
  39003. this._vertexBuffers["cellInfo"] = cellInfo;
  39004. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  39005. // Effects
  39006. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  39007. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  39008. }
  39009. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  39010. set: function (callback) {
  39011. if (this._onDisposeObserver) {
  39012. this.onDisposeObservable.remove(this._onDisposeObserver);
  39013. }
  39014. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  39015. },
  39016. enumerable: true,
  39017. configurable: true
  39018. });
  39019. Object.defineProperty(SpriteManager.prototype, "texture", {
  39020. get: function () {
  39021. return this._spriteTexture;
  39022. },
  39023. set: function (value) {
  39024. this._spriteTexture = value;
  39025. },
  39026. enumerable: true,
  39027. configurable: true
  39028. });
  39029. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  39030. var arrayOffset = index * 16;
  39031. if (offsetX === 0)
  39032. offsetX = this._epsilon;
  39033. else if (offsetX === 1)
  39034. offsetX = 1 - this._epsilon;
  39035. if (offsetY === 0)
  39036. offsetY = this._epsilon;
  39037. else if (offsetY === 1)
  39038. offsetY = 1 - this._epsilon;
  39039. this._vertexData[arrayOffset] = sprite.position.x;
  39040. this._vertexData[arrayOffset + 1] = sprite.position.y;
  39041. this._vertexData[arrayOffset + 2] = sprite.position.z;
  39042. this._vertexData[arrayOffset + 3] = sprite.angle;
  39043. this._vertexData[arrayOffset + 4] = sprite.width;
  39044. this._vertexData[arrayOffset + 5] = sprite.height;
  39045. this._vertexData[arrayOffset + 6] = offsetX;
  39046. this._vertexData[arrayOffset + 7] = offsetY;
  39047. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  39048. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  39049. var offset = (sprite.cellIndex / rowSize) >> 0;
  39050. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  39051. this._vertexData[arrayOffset + 11] = offset;
  39052. // Color
  39053. this._vertexData[arrayOffset + 12] = sprite.color.r;
  39054. this._vertexData[arrayOffset + 13] = sprite.color.g;
  39055. this._vertexData[arrayOffset + 14] = sprite.color.b;
  39056. this._vertexData[arrayOffset + 15] = sprite.color.a;
  39057. };
  39058. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  39059. var count = Math.min(this._capacity, this.sprites.length);
  39060. var min = BABYLON.Vector3.Zero();
  39061. var max = BABYLON.Vector3.Zero();
  39062. var distance = Number.MAX_VALUE;
  39063. var currentSprite;
  39064. var cameraSpacePosition = BABYLON.Vector3.Zero();
  39065. var cameraView = camera.getViewMatrix();
  39066. for (var index = 0; index < count; index++) {
  39067. var sprite = this.sprites[index];
  39068. if (!sprite) {
  39069. continue;
  39070. }
  39071. if (predicate) {
  39072. if (!predicate(sprite)) {
  39073. continue;
  39074. }
  39075. }
  39076. else if (!sprite.isPickable) {
  39077. continue;
  39078. }
  39079. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  39080. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  39081. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  39082. if (ray.intersectsBoxMinMax(min, max)) {
  39083. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  39084. if (distance > currentDistance) {
  39085. distance = currentDistance;
  39086. currentSprite = sprite;
  39087. if (fastCheck) {
  39088. break;
  39089. }
  39090. }
  39091. }
  39092. }
  39093. if (currentSprite) {
  39094. var result = new BABYLON.PickingInfo();
  39095. result.hit = true;
  39096. result.pickedSprite = currentSprite;
  39097. result.distance = distance;
  39098. return result;
  39099. }
  39100. return null;
  39101. };
  39102. SpriteManager.prototype.render = function () {
  39103. // Check
  39104. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  39105. return;
  39106. var engine = this._scene.getEngine();
  39107. var baseSize = this._spriteTexture.getBaseSize();
  39108. // Sprites
  39109. var deltaTime = engine.getDeltaTime();
  39110. var max = Math.min(this._capacity, this.sprites.length);
  39111. var rowSize = baseSize.width / this.cellWidth;
  39112. var offset = 0;
  39113. for (var index = 0; index < max; index++) {
  39114. var sprite = this.sprites[index];
  39115. if (!sprite) {
  39116. continue;
  39117. }
  39118. sprite._animate(deltaTime);
  39119. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  39120. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  39121. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  39122. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  39123. }
  39124. this._buffer.update(this._vertexData);
  39125. // Render
  39126. var effect = this._effectBase;
  39127. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  39128. effect = this._effectFog;
  39129. }
  39130. engine.enableEffect(effect);
  39131. var viewMatrix = this._scene.getViewMatrix();
  39132. effect.setTexture("diffuseSampler", this._spriteTexture);
  39133. effect.setMatrix("view", viewMatrix);
  39134. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  39135. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  39136. // Fog
  39137. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  39138. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  39139. effect.setColor3("vFogColor", this._scene.fogColor);
  39140. }
  39141. // VBOs
  39142. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  39143. // Draw order
  39144. engine.setDepthFunctionToLessOrEqual();
  39145. effect.setBool("alphaTest", true);
  39146. engine.setColorWrite(false);
  39147. engine.draw(true, 0, max * 6);
  39148. engine.setColorWrite(true);
  39149. effect.setBool("alphaTest", false);
  39150. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  39151. engine.draw(true, 0, max * 6);
  39152. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  39153. };
  39154. SpriteManager.prototype.dispose = function () {
  39155. if (this._buffer) {
  39156. this._buffer.dispose();
  39157. this._buffer = null;
  39158. }
  39159. if (this._indexBuffer) {
  39160. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  39161. this._indexBuffer = null;
  39162. }
  39163. if (this._spriteTexture) {
  39164. this._spriteTexture.dispose();
  39165. this._spriteTexture = null;
  39166. }
  39167. // Remove from scene
  39168. var index = this._scene.spriteManagers.indexOf(this);
  39169. this._scene.spriteManagers.splice(index, 1);
  39170. // Callback
  39171. this.onDisposeObservable.notifyObservers(this);
  39172. this.onDisposeObservable.clear();
  39173. };
  39174. return SpriteManager;
  39175. }());
  39176. BABYLON.SpriteManager = SpriteManager;
  39177. })(BABYLON || (BABYLON = {}));
  39178. //# sourceMappingURL=babylon.spriteManager.js.map
  39179. var BABYLON;
  39180. (function (BABYLON) {
  39181. var Sprite = (function () {
  39182. function Sprite(name, manager) {
  39183. this.name = name;
  39184. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  39185. this.width = 1.0;
  39186. this.height = 1.0;
  39187. this.angle = 0;
  39188. this.cellIndex = 0;
  39189. this.invertU = 0;
  39190. this.invertV = 0;
  39191. this.animations = new Array();
  39192. this.isPickable = false;
  39193. this._animationStarted = false;
  39194. this._loopAnimation = false;
  39195. this._fromIndex = 0;
  39196. this._toIndex = 0;
  39197. this._delay = 0;
  39198. this._direction = 1;
  39199. this._frameCount = 0;
  39200. this._time = 0;
  39201. this._manager = manager;
  39202. this._manager.sprites.push(this);
  39203. this.position = BABYLON.Vector3.Zero();
  39204. }
  39205. Object.defineProperty(Sprite.prototype, "size", {
  39206. get: function () {
  39207. return this.width;
  39208. },
  39209. set: function (value) {
  39210. this.width = value;
  39211. this.height = value;
  39212. },
  39213. enumerable: true,
  39214. configurable: true
  39215. });
  39216. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  39217. this._fromIndex = from;
  39218. this._toIndex = to;
  39219. this._loopAnimation = loop;
  39220. this._delay = delay;
  39221. this._animationStarted = true;
  39222. this._direction = from < to ? 1 : -1;
  39223. this.cellIndex = from;
  39224. this._time = 0;
  39225. this._onAnimationEnd = onAnimationEnd;
  39226. };
  39227. Sprite.prototype.stopAnimation = function () {
  39228. this._animationStarted = false;
  39229. };
  39230. Sprite.prototype._animate = function (deltaTime) {
  39231. if (!this._animationStarted)
  39232. return;
  39233. this._time += deltaTime;
  39234. if (this._time > this._delay) {
  39235. this._time = this._time % this._delay;
  39236. this.cellIndex += this._direction;
  39237. if (this.cellIndex === this._toIndex) {
  39238. if (this._loopAnimation) {
  39239. this.cellIndex = this._fromIndex;
  39240. }
  39241. else {
  39242. this._animationStarted = false;
  39243. if (this._onAnimationEnd) {
  39244. this._onAnimationEnd();
  39245. }
  39246. if (this.disposeWhenFinishedAnimating) {
  39247. this.dispose();
  39248. }
  39249. }
  39250. }
  39251. }
  39252. };
  39253. Sprite.prototype.dispose = function () {
  39254. for (var i = 0; i < this._manager.sprites.length; i++) {
  39255. if (this._manager.sprites[i] == this) {
  39256. this._manager.sprites.splice(i, 1);
  39257. }
  39258. }
  39259. };
  39260. return Sprite;
  39261. }());
  39262. BABYLON.Sprite = Sprite;
  39263. })(BABYLON || (BABYLON = {}));
  39264. //# sourceMappingURL=babylon.sprite.js.map
  39265. var BABYLON;
  39266. (function (BABYLON) {
  39267. var IntersectionInfo = (function () {
  39268. function IntersectionInfo(bu, bv, distance) {
  39269. this.bu = bu;
  39270. this.bv = bv;
  39271. this.distance = distance;
  39272. this.faceId = 0;
  39273. this.subMeshId = 0;
  39274. }
  39275. return IntersectionInfo;
  39276. }());
  39277. BABYLON.IntersectionInfo = IntersectionInfo;
  39278. var PickingInfo = (function () {
  39279. function PickingInfo() {
  39280. this.hit = false;
  39281. this.distance = 0;
  39282. this.pickedPoint = null;
  39283. this.pickedMesh = null;
  39284. this.bu = 0;
  39285. this.bv = 0;
  39286. this.faceId = -1;
  39287. this.subMeshId = 0;
  39288. this.pickedSprite = null;
  39289. }
  39290. // Methods
  39291. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  39292. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  39293. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  39294. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39295. return null;
  39296. }
  39297. var indices = this.pickedMesh.getIndices();
  39298. var result;
  39299. if (useVerticesNormals) {
  39300. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  39301. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  39302. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  39303. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  39304. normal0 = normal0.scale(this.bu);
  39305. normal1 = normal1.scale(this.bv);
  39306. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  39307. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  39308. }
  39309. else {
  39310. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39311. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  39312. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  39313. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  39314. var p1p2 = vertex1.subtract(vertex2);
  39315. var p3p2 = vertex3.subtract(vertex2);
  39316. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  39317. }
  39318. if (useWorldCoordinates) {
  39319. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  39320. }
  39321. return BABYLON.Vector3.Normalize(result);
  39322. };
  39323. PickingInfo.prototype.getTextureCoordinates = function () {
  39324. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39325. return null;
  39326. }
  39327. var indices = this.pickedMesh.getIndices();
  39328. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  39329. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  39330. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  39331. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  39332. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  39333. uv1 = uv1.scale(this.bu);
  39334. uv2 = uv2.scale(this.bv);
  39335. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  39336. };
  39337. return PickingInfo;
  39338. }());
  39339. BABYLON.PickingInfo = PickingInfo;
  39340. })(BABYLON || (BABYLON = {}));
  39341. //# sourceMappingURL=babylon.pickingInfo.js.map
  39342. var BABYLON;
  39343. (function (BABYLON) {
  39344. var Ray = (function () {
  39345. function Ray(origin, direction, length) {
  39346. if (length === void 0) { length = Number.MAX_VALUE; }
  39347. this.origin = origin;
  39348. this.direction = direction;
  39349. this.length = length;
  39350. }
  39351. // Methods
  39352. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  39353. var d = 0.0;
  39354. var maxValue = Number.MAX_VALUE;
  39355. var inv;
  39356. var min;
  39357. var max;
  39358. var temp;
  39359. if (Math.abs(this.direction.x) < 0.0000001) {
  39360. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  39361. return false;
  39362. }
  39363. }
  39364. else {
  39365. inv = 1.0 / this.direction.x;
  39366. min = (minimum.x - this.origin.x) * inv;
  39367. max = (maximum.x - this.origin.x) * inv;
  39368. if (max === -Infinity) {
  39369. max = Infinity;
  39370. }
  39371. if (min > max) {
  39372. temp = min;
  39373. min = max;
  39374. max = temp;
  39375. }
  39376. d = Math.max(min, d);
  39377. maxValue = Math.min(max, maxValue);
  39378. if (d > maxValue) {
  39379. return false;
  39380. }
  39381. }
  39382. if (Math.abs(this.direction.y) < 0.0000001) {
  39383. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  39384. return false;
  39385. }
  39386. }
  39387. else {
  39388. inv = 1.0 / this.direction.y;
  39389. min = (minimum.y - this.origin.y) * inv;
  39390. max = (maximum.y - this.origin.y) * inv;
  39391. if (max === -Infinity) {
  39392. max = Infinity;
  39393. }
  39394. if (min > max) {
  39395. temp = min;
  39396. min = max;
  39397. max = temp;
  39398. }
  39399. d = Math.max(min, d);
  39400. maxValue = Math.min(max, maxValue);
  39401. if (d > maxValue) {
  39402. return false;
  39403. }
  39404. }
  39405. if (Math.abs(this.direction.z) < 0.0000001) {
  39406. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  39407. return false;
  39408. }
  39409. }
  39410. else {
  39411. inv = 1.0 / this.direction.z;
  39412. min = (minimum.z - this.origin.z) * inv;
  39413. max = (maximum.z - this.origin.z) * inv;
  39414. if (max === -Infinity) {
  39415. max = Infinity;
  39416. }
  39417. if (min > max) {
  39418. temp = min;
  39419. min = max;
  39420. max = temp;
  39421. }
  39422. d = Math.max(min, d);
  39423. maxValue = Math.min(max, maxValue);
  39424. if (d > maxValue) {
  39425. return false;
  39426. }
  39427. }
  39428. return true;
  39429. };
  39430. Ray.prototype.intersectsBox = function (box) {
  39431. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  39432. };
  39433. Ray.prototype.intersectsSphere = function (sphere) {
  39434. var x = sphere.center.x - this.origin.x;
  39435. var y = sphere.center.y - this.origin.y;
  39436. var z = sphere.center.z - this.origin.z;
  39437. var pyth = (x * x) + (y * y) + (z * z);
  39438. var rr = sphere.radius * sphere.radius;
  39439. if (pyth <= rr) {
  39440. return true;
  39441. }
  39442. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  39443. if (dot < 0.0) {
  39444. return false;
  39445. }
  39446. var temp = pyth - (dot * dot);
  39447. return temp <= rr;
  39448. };
  39449. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  39450. if (!this._edge1) {
  39451. this._edge1 = BABYLON.Vector3.Zero();
  39452. this._edge2 = BABYLON.Vector3.Zero();
  39453. this._pvec = BABYLON.Vector3.Zero();
  39454. this._tvec = BABYLON.Vector3.Zero();
  39455. this._qvec = BABYLON.Vector3.Zero();
  39456. }
  39457. vertex1.subtractToRef(vertex0, this._edge1);
  39458. vertex2.subtractToRef(vertex0, this._edge2);
  39459. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  39460. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  39461. if (det === 0) {
  39462. return null;
  39463. }
  39464. var invdet = 1 / det;
  39465. this.origin.subtractToRef(vertex0, this._tvec);
  39466. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  39467. if (bu < 0 || bu > 1.0) {
  39468. return null;
  39469. }
  39470. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  39471. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  39472. if (bv < 0 || bu + bv > 1.0) {
  39473. return null;
  39474. }
  39475. //check if the distance is longer than the predefined length.
  39476. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  39477. if (distance > this.length) {
  39478. return null;
  39479. }
  39480. return new BABYLON.IntersectionInfo(bu, bv, distance);
  39481. };
  39482. Ray.prototype.intersectsPlane = function (plane) {
  39483. var distance;
  39484. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  39485. if (Math.abs(result1) < 9.99999997475243E-07) {
  39486. return null;
  39487. }
  39488. else {
  39489. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  39490. distance = (-plane.d - result2) / result1;
  39491. if (distance < 0.0) {
  39492. if (distance < -9.99999997475243E-07) {
  39493. return null;
  39494. }
  39495. else {
  39496. return 0;
  39497. }
  39498. }
  39499. return distance;
  39500. }
  39501. };
  39502. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  39503. var tm = BABYLON.Tmp.Matrix[0];
  39504. mesh.getWorldMatrix().invertToRef(tm);
  39505. if (this._tmpRay) {
  39506. Ray.TransformToRef(this, tm, this._tmpRay);
  39507. }
  39508. else {
  39509. this._tmpRay = Ray.Transform(this, tm);
  39510. }
  39511. return mesh.intersects(this._tmpRay, fastCheck);
  39512. };
  39513. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  39514. if (results) {
  39515. results.length = 0;
  39516. }
  39517. else {
  39518. results = [];
  39519. }
  39520. for (var i = 0; i < meshes.length; i++) {
  39521. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  39522. if (pickInfo.hit) {
  39523. results.push(pickInfo);
  39524. }
  39525. }
  39526. results.sort(this._comparePickingInfo);
  39527. return results;
  39528. };
  39529. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  39530. if (pickingInfoA.distance < pickingInfoB.distance) {
  39531. return -1;
  39532. }
  39533. else if (pickingInfoA.distance > pickingInfoB.distance) {
  39534. return 1;
  39535. }
  39536. else {
  39537. return 0;
  39538. }
  39539. };
  39540. /**
  39541. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  39542. * @param sega the first point of the segment to test the intersection against
  39543. * @param segb the second point of the segment to test the intersection against
  39544. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  39545. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  39546. */
  39547. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  39548. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  39549. var u = segb.subtract(sega);
  39550. var v = rsegb.subtract(this.origin);
  39551. var w = sega.subtract(this.origin);
  39552. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  39553. var b = BABYLON.Vector3.Dot(u, v);
  39554. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  39555. var d = BABYLON.Vector3.Dot(u, w);
  39556. var e = BABYLON.Vector3.Dot(v, w);
  39557. var D = a * c - b * b; // always >= 0
  39558. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  39559. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  39560. // compute the line parameters of the two closest points
  39561. if (D < Ray.smallnum) {
  39562. sN = 0.0; // force using point P0 on segment S1
  39563. sD = 1.0; // to prevent possible division by 0.0 later
  39564. tN = e;
  39565. tD = c;
  39566. }
  39567. else {
  39568. sN = (b * e - c * d);
  39569. tN = (a * e - b * d);
  39570. if (sN < 0.0) {
  39571. sN = 0.0;
  39572. tN = e;
  39573. tD = c;
  39574. }
  39575. else if (sN > sD) {
  39576. sN = sD;
  39577. tN = e + b;
  39578. tD = c;
  39579. }
  39580. }
  39581. if (tN < 0.0) {
  39582. tN = 0.0;
  39583. // recompute sc for this edge
  39584. if (-d < 0.0) {
  39585. sN = 0.0;
  39586. }
  39587. else if (-d > a)
  39588. sN = sD;
  39589. else {
  39590. sN = -d;
  39591. sD = a;
  39592. }
  39593. }
  39594. else if (tN > tD) {
  39595. tN = tD;
  39596. // recompute sc for this edge
  39597. if ((-d + b) < 0.0) {
  39598. sN = 0;
  39599. }
  39600. else if ((-d + b) > a) {
  39601. sN = sD;
  39602. }
  39603. else {
  39604. sN = (-d + b);
  39605. sD = a;
  39606. }
  39607. }
  39608. // finally do the division to get sc and tc
  39609. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  39610. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  39611. // get the difference of the two closest points
  39612. var qtc = v.multiplyByFloats(tc, tc, tc);
  39613. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  39614. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  39615. if (isIntersected) {
  39616. return qtc.length();
  39617. }
  39618. return -1;
  39619. };
  39620. // Statics
  39621. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  39622. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  39623. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  39624. var direction = end.subtract(start);
  39625. direction.normalize();
  39626. return new Ray(start, direction);
  39627. };
  39628. /**
  39629. * 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
  39630. * transformed to the given world matrix.
  39631. * @param origin The origin point
  39632. * @param end The end point
  39633. * @param world a matrix to transform the ray to. Default is the identity matrix.
  39634. */
  39635. Ray.CreateNewFromTo = function (origin, end, world) {
  39636. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  39637. var direction = end.subtract(origin);
  39638. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  39639. direction.normalize();
  39640. return Ray.Transform(new Ray(origin, direction, length), world);
  39641. };
  39642. Ray.Transform = function (ray, matrix) {
  39643. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  39644. Ray.TransformToRef(ray, matrix, result);
  39645. return result;
  39646. };
  39647. Ray.TransformToRef = function (ray, matrix, result) {
  39648. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  39649. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  39650. result.length = ray.length;
  39651. var dir = result.direction;
  39652. var len = dir.length();
  39653. if (!(len === 0 || len === 1)) {
  39654. var num = 1.0 / len;
  39655. dir.x *= num;
  39656. dir.y *= num;
  39657. dir.z *= num;
  39658. result.length *= len;
  39659. }
  39660. };
  39661. Ray.smallnum = 0.00000001;
  39662. Ray.rayl = 10e8;
  39663. return Ray;
  39664. }());
  39665. BABYLON.Ray = Ray;
  39666. })(BABYLON || (BABYLON = {}));
  39667. //# sourceMappingURL=babylon.ray.js.map
  39668. var BABYLON;
  39669. (function (BABYLON) {
  39670. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  39671. if (boxMin.x > sphereCenter.x + sphereRadius)
  39672. return false;
  39673. if (sphereCenter.x - sphereRadius > boxMax.x)
  39674. return false;
  39675. if (boxMin.y > sphereCenter.y + sphereRadius)
  39676. return false;
  39677. if (sphereCenter.y - sphereRadius > boxMax.y)
  39678. return false;
  39679. if (boxMin.z > sphereCenter.z + sphereRadius)
  39680. return false;
  39681. if (sphereCenter.z - sphereRadius > boxMax.z)
  39682. return false;
  39683. return true;
  39684. };
  39685. var getLowestRoot = (function () {
  39686. var result = { root: 0, found: false };
  39687. return function (a, b, c, maxR) {
  39688. result.root = 0;
  39689. result.found = false;
  39690. var determinant = b * b - 4.0 * a * c;
  39691. if (determinant < 0)
  39692. return result;
  39693. var sqrtD = Math.sqrt(determinant);
  39694. var r1 = (-b - sqrtD) / (2.0 * a);
  39695. var r2 = (-b + sqrtD) / (2.0 * a);
  39696. if (r1 > r2) {
  39697. var temp = r2;
  39698. r2 = r1;
  39699. r1 = temp;
  39700. }
  39701. if (r1 > 0 && r1 < maxR) {
  39702. result.root = r1;
  39703. result.found = true;
  39704. return result;
  39705. }
  39706. if (r2 > 0 && r2 < maxR) {
  39707. result.root = r2;
  39708. result.found = true;
  39709. return result;
  39710. }
  39711. return result;
  39712. };
  39713. })();
  39714. var Collider = (function () {
  39715. function Collider() {
  39716. this.radius = BABYLON.Vector3.One();
  39717. this.retry = 0;
  39718. this.basePointWorld = BABYLON.Vector3.Zero();
  39719. this.velocityWorld = BABYLON.Vector3.Zero();
  39720. this.normalizedVelocity = BABYLON.Vector3.Zero();
  39721. this._collisionPoint = BABYLON.Vector3.Zero();
  39722. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  39723. this._tempVector = BABYLON.Vector3.Zero();
  39724. this._tempVector2 = BABYLON.Vector3.Zero();
  39725. this._tempVector3 = BABYLON.Vector3.Zero();
  39726. this._tempVector4 = BABYLON.Vector3.Zero();
  39727. this._edge = BABYLON.Vector3.Zero();
  39728. this._baseToVertex = BABYLON.Vector3.Zero();
  39729. this._destinationPoint = BABYLON.Vector3.Zero();
  39730. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  39731. this._displacementVector = BABYLON.Vector3.Zero();
  39732. this._collisionMask = -1;
  39733. }
  39734. Object.defineProperty(Collider.prototype, "collisionMask", {
  39735. get: function () {
  39736. return this._collisionMask;
  39737. },
  39738. set: function (mask) {
  39739. this._collisionMask = !isNaN(mask) ? mask : -1;
  39740. },
  39741. enumerable: true,
  39742. configurable: true
  39743. });
  39744. // Methods
  39745. Collider.prototype._initialize = function (source, dir, e) {
  39746. this.velocity = dir;
  39747. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  39748. this.basePoint = source;
  39749. source.multiplyToRef(this.radius, this.basePointWorld);
  39750. dir.multiplyToRef(this.radius, this.velocityWorld);
  39751. this.velocityWorldLength = this.velocityWorld.length();
  39752. this.epsilon = e;
  39753. this.collisionFound = false;
  39754. };
  39755. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  39756. pa.subtractToRef(point, this._tempVector);
  39757. pb.subtractToRef(point, this._tempVector2);
  39758. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  39759. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  39760. if (d < 0)
  39761. return false;
  39762. pc.subtractToRef(point, this._tempVector3);
  39763. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  39764. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  39765. if (d < 0)
  39766. return false;
  39767. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  39768. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  39769. return d >= 0;
  39770. };
  39771. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  39772. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  39773. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  39774. if (distance > this.velocityWorldLength + max + sphereRadius) {
  39775. return false;
  39776. }
  39777. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  39778. return false;
  39779. return true;
  39780. };
  39781. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  39782. var t0;
  39783. var embeddedInPlane = false;
  39784. //defensive programming, actually not needed.
  39785. if (!trianglePlaneArray) {
  39786. trianglePlaneArray = [];
  39787. }
  39788. if (!trianglePlaneArray[faceIndex]) {
  39789. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  39790. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  39791. }
  39792. var trianglePlane = trianglePlaneArray[faceIndex];
  39793. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  39794. return;
  39795. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  39796. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  39797. if (normalDotVelocity == 0) {
  39798. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  39799. return;
  39800. embeddedInPlane = true;
  39801. t0 = 0;
  39802. }
  39803. else {
  39804. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  39805. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  39806. if (t0 > t1) {
  39807. var temp = t1;
  39808. t1 = t0;
  39809. t0 = temp;
  39810. }
  39811. if (t0 > 1.0 || t1 < 0.0)
  39812. return;
  39813. if (t0 < 0)
  39814. t0 = 0;
  39815. if (t0 > 1.0)
  39816. t0 = 1.0;
  39817. }
  39818. this._collisionPoint.copyFromFloats(0, 0, 0);
  39819. var found = false;
  39820. var t = 1.0;
  39821. if (!embeddedInPlane) {
  39822. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  39823. this.velocity.scaleToRef(t0, this._tempVector);
  39824. this._planeIntersectionPoint.addInPlace(this._tempVector);
  39825. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  39826. found = true;
  39827. t = t0;
  39828. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  39829. }
  39830. }
  39831. if (!found) {
  39832. var velocitySquaredLength = this.velocity.lengthSquared();
  39833. var a = velocitySquaredLength;
  39834. this.basePoint.subtractToRef(p1, this._tempVector);
  39835. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  39836. var c = this._tempVector.lengthSquared() - 1.0;
  39837. var lowestRoot = getLowestRoot(a, b, c, t);
  39838. if (lowestRoot.found) {
  39839. t = lowestRoot.root;
  39840. found = true;
  39841. this._collisionPoint.copyFrom(p1);
  39842. }
  39843. this.basePoint.subtractToRef(p2, this._tempVector);
  39844. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  39845. c = this._tempVector.lengthSquared() - 1.0;
  39846. lowestRoot = getLowestRoot(a, b, c, t);
  39847. if (lowestRoot.found) {
  39848. t = lowestRoot.root;
  39849. found = true;
  39850. this._collisionPoint.copyFrom(p2);
  39851. }
  39852. this.basePoint.subtractToRef(p3, this._tempVector);
  39853. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  39854. c = this._tempVector.lengthSquared() - 1.0;
  39855. lowestRoot = getLowestRoot(a, b, c, t);
  39856. if (lowestRoot.found) {
  39857. t = lowestRoot.root;
  39858. found = true;
  39859. this._collisionPoint.copyFrom(p3);
  39860. }
  39861. p2.subtractToRef(p1, this._edge);
  39862. p1.subtractToRef(this.basePoint, this._baseToVertex);
  39863. var edgeSquaredLength = this._edge.lengthSquared();
  39864. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  39865. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  39866. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  39867. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  39868. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  39869. lowestRoot = getLowestRoot(a, b, c, t);
  39870. if (lowestRoot.found) {
  39871. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  39872. if (f >= 0.0 && f <= 1.0) {
  39873. t = lowestRoot.root;
  39874. found = true;
  39875. this._edge.scaleInPlace(f);
  39876. p1.addToRef(this._edge, this._collisionPoint);
  39877. }
  39878. }
  39879. p3.subtractToRef(p2, this._edge);
  39880. p2.subtractToRef(this.basePoint, this._baseToVertex);
  39881. edgeSquaredLength = this._edge.lengthSquared();
  39882. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  39883. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  39884. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  39885. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  39886. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  39887. lowestRoot = getLowestRoot(a, b, c, t);
  39888. if (lowestRoot.found) {
  39889. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  39890. if (f >= 0.0 && f <= 1.0) {
  39891. t = lowestRoot.root;
  39892. found = true;
  39893. this._edge.scaleInPlace(f);
  39894. p2.addToRef(this._edge, this._collisionPoint);
  39895. }
  39896. }
  39897. p1.subtractToRef(p3, this._edge);
  39898. p3.subtractToRef(this.basePoint, this._baseToVertex);
  39899. edgeSquaredLength = this._edge.lengthSquared();
  39900. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  39901. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  39902. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  39903. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  39904. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  39905. lowestRoot = getLowestRoot(a, b, c, t);
  39906. if (lowestRoot.found) {
  39907. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  39908. if (f >= 0.0 && f <= 1.0) {
  39909. t = lowestRoot.root;
  39910. found = true;
  39911. this._edge.scaleInPlace(f);
  39912. p3.addToRef(this._edge, this._collisionPoint);
  39913. }
  39914. }
  39915. }
  39916. if (found) {
  39917. var distToCollision = t * this.velocity.length();
  39918. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  39919. if (!this.intersectionPoint) {
  39920. this.intersectionPoint = this._collisionPoint.clone();
  39921. }
  39922. else {
  39923. this.intersectionPoint.copyFrom(this._collisionPoint);
  39924. }
  39925. this.nearestDistance = distToCollision;
  39926. this.collisionFound = true;
  39927. }
  39928. }
  39929. };
  39930. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  39931. for (var i = indexStart; i < indexEnd; i += 3) {
  39932. var p1 = pts[indices[i] - decal];
  39933. var p2 = pts[indices[i + 1] - decal];
  39934. var p3 = pts[indices[i + 2] - decal];
  39935. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  39936. }
  39937. };
  39938. Collider.prototype._getResponse = function (pos, vel) {
  39939. pos.addToRef(vel, this._destinationPoint);
  39940. vel.scaleInPlace((this.nearestDistance / vel.length()));
  39941. this.basePoint.addToRef(vel, pos);
  39942. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  39943. this._slidePlaneNormal.normalize();
  39944. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  39945. pos.addInPlace(this._displacementVector);
  39946. this.intersectionPoint.addInPlace(this._displacementVector);
  39947. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  39948. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  39949. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  39950. };
  39951. return Collider;
  39952. }());
  39953. BABYLON.Collider = Collider;
  39954. })(BABYLON || (BABYLON = {}));
  39955. //# sourceMappingURL=babylon.collider.js.map
  39956. var BABYLON;
  39957. (function (BABYLON) {
  39958. //WebWorker code will be inserted to this variable.
  39959. BABYLON.CollisionWorker = "";
  39960. var WorkerTaskType;
  39961. (function (WorkerTaskType) {
  39962. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  39963. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  39964. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  39965. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  39966. var WorkerReplyType;
  39967. (function (WorkerReplyType) {
  39968. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  39969. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  39970. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  39971. var CollisionCoordinatorWorker = (function () {
  39972. function CollisionCoordinatorWorker() {
  39973. var _this = this;
  39974. this._scaledPosition = BABYLON.Vector3.Zero();
  39975. this._scaledVelocity = BABYLON.Vector3.Zero();
  39976. this.onMeshUpdated = function (mesh) {
  39977. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  39978. };
  39979. this.onGeometryUpdated = function (geometry) {
  39980. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  39981. };
  39982. this._afterRender = function () {
  39983. if (!_this._init)
  39984. return;
  39985. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  39986. return;
  39987. }
  39988. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  39989. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  39990. if (_this._runningUpdated > 4) {
  39991. return;
  39992. }
  39993. ++_this._runningUpdated;
  39994. var payload = {
  39995. updatedMeshes: _this._addUpdateMeshesList,
  39996. updatedGeometries: _this._addUpdateGeometriesList,
  39997. removedGeometries: _this._toRemoveGeometryArray,
  39998. removedMeshes: _this._toRemoveMeshesArray
  39999. };
  40000. var message = {
  40001. payload: payload,
  40002. taskType: WorkerTaskType.UPDATE
  40003. };
  40004. var serializable = [];
  40005. for (var id in payload.updatedGeometries) {
  40006. if (payload.updatedGeometries.hasOwnProperty(id)) {
  40007. //prepare transferables
  40008. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  40009. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  40010. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  40011. }
  40012. }
  40013. _this._worker.postMessage(message, serializable);
  40014. _this._addUpdateMeshesList = {};
  40015. _this._addUpdateGeometriesList = {};
  40016. _this._toRemoveGeometryArray = [];
  40017. _this._toRemoveMeshesArray = [];
  40018. };
  40019. this._onMessageFromWorker = function (e) {
  40020. var returnData = e.data;
  40021. if (returnData.error != WorkerReplyType.SUCCESS) {
  40022. //TODO what errors can be returned from the worker?
  40023. BABYLON.Tools.Warn("error returned from worker!");
  40024. return;
  40025. }
  40026. switch (returnData.taskType) {
  40027. case WorkerTaskType.INIT:
  40028. _this._init = true;
  40029. //Update the worked with ALL of the scene's current state
  40030. _this._scene.meshes.forEach(function (mesh) {
  40031. _this.onMeshAdded(mesh);
  40032. });
  40033. _this._scene.getGeometries().forEach(function (geometry) {
  40034. _this.onGeometryAdded(geometry);
  40035. });
  40036. break;
  40037. case WorkerTaskType.UPDATE:
  40038. _this._runningUpdated--;
  40039. break;
  40040. case WorkerTaskType.COLLIDE:
  40041. _this._runningCollisionTask = false;
  40042. var returnPayload = returnData.payload;
  40043. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  40044. return;
  40045. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  40046. //cleanup
  40047. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  40048. break;
  40049. }
  40050. };
  40051. this._collisionsCallbackArray = [];
  40052. this._init = false;
  40053. this._runningUpdated = 0;
  40054. this._runningCollisionTask = false;
  40055. this._addUpdateMeshesList = {};
  40056. this._addUpdateGeometriesList = {};
  40057. this._toRemoveGeometryArray = [];
  40058. this._toRemoveMeshesArray = [];
  40059. }
  40060. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  40061. if (!this._init)
  40062. return;
  40063. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  40064. return;
  40065. position.divideToRef(collider.radius, this._scaledPosition);
  40066. velocity.divideToRef(collider.radius, this._scaledVelocity);
  40067. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  40068. var payload = {
  40069. collider: {
  40070. position: this._scaledPosition.asArray(),
  40071. velocity: this._scaledVelocity.asArray(),
  40072. radius: collider.radius.asArray()
  40073. },
  40074. collisionId: collisionIndex,
  40075. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  40076. maximumRetry: maximumRetry
  40077. };
  40078. var message = {
  40079. payload: payload,
  40080. taskType: WorkerTaskType.COLLIDE
  40081. };
  40082. this._worker.postMessage(message);
  40083. };
  40084. CollisionCoordinatorWorker.prototype.init = function (scene) {
  40085. this._scene = scene;
  40086. this._scene.registerAfterRender(this._afterRender);
  40087. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  40088. this._worker = new Worker(workerUrl);
  40089. this._worker.onmessage = this._onMessageFromWorker;
  40090. var message = {
  40091. payload: {},
  40092. taskType: WorkerTaskType.INIT
  40093. };
  40094. this._worker.postMessage(message);
  40095. };
  40096. CollisionCoordinatorWorker.prototype.destroy = function () {
  40097. this._scene.unregisterAfterRender(this._afterRender);
  40098. this._worker.terminate();
  40099. };
  40100. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  40101. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  40102. this.onMeshUpdated(mesh);
  40103. };
  40104. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  40105. this._toRemoveMeshesArray.push(mesh.uniqueId);
  40106. };
  40107. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  40108. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  40109. geometry.onGeometryUpdated = this.onGeometryUpdated;
  40110. this.onGeometryUpdated(geometry);
  40111. };
  40112. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  40113. this._toRemoveGeometryArray.push(geometry.id);
  40114. };
  40115. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  40116. var submeshes = [];
  40117. if (mesh.subMeshes) {
  40118. submeshes = mesh.subMeshes.map(function (sm, idx) {
  40119. return {
  40120. position: idx,
  40121. verticesStart: sm.verticesStart,
  40122. verticesCount: sm.verticesCount,
  40123. indexStart: sm.indexStart,
  40124. indexCount: sm.indexCount,
  40125. hasMaterial: !!sm.getMaterial(),
  40126. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  40127. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  40128. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  40129. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  40130. };
  40131. });
  40132. }
  40133. var geometryId = null;
  40134. if (mesh instanceof BABYLON.Mesh) {
  40135. geometryId = mesh.geometry ? mesh.geometry.id : null;
  40136. }
  40137. else if (mesh instanceof BABYLON.InstancedMesh) {
  40138. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  40139. }
  40140. return {
  40141. uniqueId: mesh.uniqueId,
  40142. id: mesh.id,
  40143. name: mesh.name,
  40144. geometryId: geometryId,
  40145. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  40146. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  40147. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  40148. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  40149. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  40150. subMeshes: submeshes,
  40151. checkCollisions: mesh.checkCollisions
  40152. };
  40153. };
  40154. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  40155. return {
  40156. id: geometry.id,
  40157. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  40158. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  40159. indices: new Uint32Array(geometry.getIndices() || []),
  40160. };
  40161. };
  40162. return CollisionCoordinatorWorker;
  40163. }());
  40164. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  40165. var CollisionCoordinatorLegacy = (function () {
  40166. function CollisionCoordinatorLegacy() {
  40167. this._scaledPosition = BABYLON.Vector3.Zero();
  40168. this._scaledVelocity = BABYLON.Vector3.Zero();
  40169. this._finalPosition = BABYLON.Vector3.Zero();
  40170. }
  40171. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  40172. position.divideToRef(collider.radius, this._scaledPosition);
  40173. velocity.divideToRef(collider.radius, this._scaledVelocity);
  40174. collider.collidedMesh = null;
  40175. collider.retry = 0;
  40176. collider.initialVelocity = this._scaledVelocity;
  40177. collider.initialPosition = this._scaledPosition;
  40178. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  40179. this._finalPosition.multiplyInPlace(collider.radius);
  40180. //run the callback
  40181. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  40182. };
  40183. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  40184. this._scene = scene;
  40185. };
  40186. CollisionCoordinatorLegacy.prototype.destroy = function () {
  40187. //Legacy need no destruction method.
  40188. };
  40189. //No update in legacy mode
  40190. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  40191. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  40192. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  40193. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  40194. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  40195. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  40196. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  40197. if (excludedMesh === void 0) { excludedMesh = null; }
  40198. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  40199. if (collider.retry >= maximumRetry) {
  40200. finalPosition.copyFrom(position);
  40201. return;
  40202. }
  40203. // Check if this is a mesh else camera or -1
  40204. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  40205. collider._initialize(position, velocity, closeDistance);
  40206. // Check all meshes
  40207. for (var index = 0; index < this._scene.meshes.length; index++) {
  40208. var mesh = this._scene.meshes[index];
  40209. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  40210. mesh._checkCollision(collider);
  40211. }
  40212. }
  40213. if (!collider.collisionFound) {
  40214. position.addToRef(velocity, finalPosition);
  40215. return;
  40216. }
  40217. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  40218. collider._getResponse(position, velocity);
  40219. }
  40220. if (velocity.length() <= closeDistance) {
  40221. finalPosition.copyFrom(position);
  40222. return;
  40223. }
  40224. collider.retry++;
  40225. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  40226. };
  40227. return CollisionCoordinatorLegacy;
  40228. }());
  40229. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  40230. })(BABYLON || (BABYLON = {}));
  40231. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  40232. var BABYLON;
  40233. (function (BABYLON) {
  40234. var Particle = (function () {
  40235. function Particle() {
  40236. this.position = BABYLON.Vector3.Zero();
  40237. this.direction = BABYLON.Vector3.Zero();
  40238. this.color = new BABYLON.Color4(0, 0, 0, 0);
  40239. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  40240. this.lifeTime = 1.0;
  40241. this.age = 0;
  40242. this.size = 0;
  40243. this.angle = 0;
  40244. this.angularSpeed = 0;
  40245. }
  40246. Particle.prototype.copyTo = function (other) {
  40247. other.position.copyFrom(this.position);
  40248. other.direction.copyFrom(this.direction);
  40249. other.color.copyFrom(this.color);
  40250. other.colorStep.copyFrom(this.colorStep);
  40251. other.lifeTime = this.lifeTime;
  40252. other.age = this.age;
  40253. other.size = this.size;
  40254. other.angle = this.angle;
  40255. other.angularSpeed = this.angularSpeed;
  40256. };
  40257. return Particle;
  40258. }());
  40259. BABYLON.Particle = Particle;
  40260. })(BABYLON || (BABYLON = {}));
  40261. //# sourceMappingURL=babylon.particle.js.map
  40262. var BABYLON;
  40263. (function (BABYLON) {
  40264. var randomNumber = function (min, max) {
  40265. if (min === max) {
  40266. return (min);
  40267. }
  40268. var random = Math.random();
  40269. return ((random * (max - min)) + min);
  40270. };
  40271. var ParticleSystem = (function () {
  40272. function ParticleSystem(name, capacity, scene, customEffect) {
  40273. var _this = this;
  40274. this.name = name;
  40275. // Members
  40276. this.animations = [];
  40277. this.renderingGroupId = 0;
  40278. this.emitter = null;
  40279. this.emitRate = 10;
  40280. this.manualEmitCount = -1;
  40281. this.updateSpeed = 0.01;
  40282. this.targetStopDuration = 0;
  40283. this.disposeOnStop = false;
  40284. this.minEmitPower = 1;
  40285. this.maxEmitPower = 1;
  40286. this.minLifeTime = 1;
  40287. this.maxLifeTime = 1;
  40288. this.minSize = 1;
  40289. this.maxSize = 1;
  40290. this.minAngularSpeed = 0;
  40291. this.maxAngularSpeed = 0;
  40292. this.layerMask = 0x0FFFFFFF;
  40293. this.customShader = null;
  40294. this.preventAutoStart = false;
  40295. /**
  40296. * An event triggered when the system is disposed.
  40297. * @type {BABYLON.Observable}
  40298. */
  40299. this.onDisposeObservable = new BABYLON.Observable();
  40300. this.onAnimationEnd = null;
  40301. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  40302. this.forceDepthWrite = false;
  40303. this.gravity = BABYLON.Vector3.Zero();
  40304. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  40305. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  40306. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  40307. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  40308. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  40309. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  40310. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  40311. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  40312. this.particles = new Array();
  40313. this._stockParticles = new Array();
  40314. this._newPartsExcess = 0;
  40315. this._vertexBuffers = {};
  40316. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  40317. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  40318. this._scaledDirection = BABYLON.Vector3.Zero();
  40319. this._scaledGravity = BABYLON.Vector3.Zero();
  40320. this._currentRenderId = -1;
  40321. this._started = false;
  40322. this._stopped = false;
  40323. this._actualFrame = 0;
  40324. this.id = name;
  40325. this._capacity = capacity;
  40326. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  40327. this._customEffect = customEffect;
  40328. scene.particleSystems.push(this);
  40329. this._createIndexBuffer();
  40330. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  40331. this._vertexData = new Float32Array(capacity * 11 * 4);
  40332. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  40333. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  40334. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  40335. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  40336. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  40337. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  40338. this._vertexBuffers["options"] = options;
  40339. // Default behaviors
  40340. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  40341. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  40342. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  40343. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  40344. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  40345. };
  40346. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  40347. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  40348. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  40349. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  40350. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  40351. };
  40352. this.updateFunction = function (particles) {
  40353. for (var index = 0; index < particles.length; index++) {
  40354. var particle = particles[index];
  40355. particle.age += _this._scaledUpdateSpeed;
  40356. if (particle.age >= particle.lifeTime) {
  40357. _this.recycleParticle(particle);
  40358. index--;
  40359. continue;
  40360. }
  40361. else {
  40362. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  40363. particle.color.addInPlace(_this._scaledColorStep);
  40364. if (particle.color.a < 0)
  40365. particle.color.a = 0;
  40366. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  40367. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  40368. particle.position.addInPlace(_this._scaledDirection);
  40369. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  40370. particle.direction.addInPlace(_this._scaledGravity);
  40371. }
  40372. }
  40373. };
  40374. }
  40375. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  40376. set: function (callback) {
  40377. if (this._onDisposeObserver) {
  40378. this.onDisposeObservable.remove(this._onDisposeObserver);
  40379. }
  40380. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  40381. },
  40382. enumerable: true,
  40383. configurable: true
  40384. });
  40385. ParticleSystem.prototype._createIndexBuffer = function () {
  40386. var indices = [];
  40387. var index = 0;
  40388. for (var count = 0; count < this._capacity; count++) {
  40389. indices.push(index);
  40390. indices.push(index + 1);
  40391. indices.push(index + 2);
  40392. indices.push(index);
  40393. indices.push(index + 2);
  40394. indices.push(index + 3);
  40395. index += 4;
  40396. }
  40397. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  40398. };
  40399. ParticleSystem.prototype.recycleParticle = function (particle) {
  40400. var lastParticle = this.particles.pop();
  40401. if (lastParticle !== particle) {
  40402. lastParticle.copyTo(particle);
  40403. this._stockParticles.push(lastParticle);
  40404. }
  40405. };
  40406. ParticleSystem.prototype.getCapacity = function () {
  40407. return this._capacity;
  40408. };
  40409. ParticleSystem.prototype.isAlive = function () {
  40410. return this._alive;
  40411. };
  40412. ParticleSystem.prototype.isStarted = function () {
  40413. return this._started;
  40414. };
  40415. ParticleSystem.prototype.start = function () {
  40416. this._started = true;
  40417. this._stopped = false;
  40418. this._actualFrame = 0;
  40419. };
  40420. ParticleSystem.prototype.stop = function () {
  40421. this._stopped = true;
  40422. };
  40423. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  40424. var offset = index * 11;
  40425. this._vertexData[offset] = particle.position.x;
  40426. this._vertexData[offset + 1] = particle.position.y;
  40427. this._vertexData[offset + 2] = particle.position.z;
  40428. this._vertexData[offset + 3] = particle.color.r;
  40429. this._vertexData[offset + 4] = particle.color.g;
  40430. this._vertexData[offset + 5] = particle.color.b;
  40431. this._vertexData[offset + 6] = particle.color.a;
  40432. this._vertexData[offset + 7] = particle.angle;
  40433. this._vertexData[offset + 8] = particle.size;
  40434. this._vertexData[offset + 9] = offsetX;
  40435. this._vertexData[offset + 10] = offsetY;
  40436. };
  40437. ParticleSystem.prototype._update = function (newParticles) {
  40438. // Update current
  40439. this._alive = this.particles.length > 0;
  40440. this.updateFunction(this.particles);
  40441. // Add new ones
  40442. var worldMatrix;
  40443. if (this.emitter.position) {
  40444. var emitterMesh = this.emitter;
  40445. worldMatrix = emitterMesh.getWorldMatrix();
  40446. }
  40447. else {
  40448. var emitterPosition = this.emitter;
  40449. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  40450. }
  40451. var particle;
  40452. for (var index = 0; index < newParticles; index++) {
  40453. if (this.particles.length === this._capacity) {
  40454. break;
  40455. }
  40456. if (this._stockParticles.length !== 0) {
  40457. particle = this._stockParticles.pop();
  40458. particle.age = 0;
  40459. }
  40460. else {
  40461. particle = new BABYLON.Particle();
  40462. }
  40463. this.particles.push(particle);
  40464. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  40465. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  40466. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  40467. particle.size = randomNumber(this.minSize, this.maxSize);
  40468. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  40469. this.startPositionFunction(worldMatrix, particle.position, particle);
  40470. var step = randomNumber(0, 1.0);
  40471. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  40472. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  40473. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  40474. }
  40475. };
  40476. ParticleSystem.prototype._getEffect = function () {
  40477. if (this._customEffect) {
  40478. return this._customEffect;
  40479. }
  40480. ;
  40481. var defines = [];
  40482. if (this._scene.clipPlane) {
  40483. defines.push("#define CLIPPLANE");
  40484. }
  40485. // Effect
  40486. var join = defines.join("\n");
  40487. if (this._cachedDefines !== join) {
  40488. this._cachedDefines = join;
  40489. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  40490. }
  40491. return this._effect;
  40492. };
  40493. ParticleSystem.prototype.animate = function () {
  40494. if (!this._started)
  40495. return;
  40496. var effect = this._getEffect();
  40497. // Check
  40498. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  40499. return;
  40500. if (this._currentRenderId === this._scene.getRenderId()) {
  40501. return;
  40502. }
  40503. this._currentRenderId = this._scene.getRenderId();
  40504. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  40505. // determine the number of particles we need to create
  40506. var newParticles;
  40507. if (this.manualEmitCount > -1) {
  40508. newParticles = this.manualEmitCount;
  40509. this._newPartsExcess = 0;
  40510. this.manualEmitCount = 0;
  40511. }
  40512. else {
  40513. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  40514. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  40515. }
  40516. if (this._newPartsExcess > 1.0) {
  40517. newParticles += this._newPartsExcess >> 0;
  40518. this._newPartsExcess -= this._newPartsExcess >> 0;
  40519. }
  40520. this._alive = false;
  40521. if (!this._stopped) {
  40522. this._actualFrame += this._scaledUpdateSpeed;
  40523. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  40524. this.stop();
  40525. }
  40526. else {
  40527. newParticles = 0;
  40528. }
  40529. this._update(newParticles);
  40530. // Stopped?
  40531. if (this._stopped) {
  40532. if (!this._alive) {
  40533. this._started = false;
  40534. if (this.onAnimationEnd) {
  40535. this.onAnimationEnd();
  40536. }
  40537. if (this.disposeOnStop) {
  40538. this._scene._toBeDisposed.push(this);
  40539. }
  40540. }
  40541. }
  40542. // Update VBO
  40543. var offset = 0;
  40544. for (var index = 0; index < this.particles.length; index++) {
  40545. var particle = this.particles[index];
  40546. this._appendParticleVertex(offset++, particle, 0, 0);
  40547. this._appendParticleVertex(offset++, particle, 1, 0);
  40548. this._appendParticleVertex(offset++, particle, 1, 1);
  40549. this._appendParticleVertex(offset++, particle, 0, 1);
  40550. }
  40551. this._vertexBuffer.update(this._vertexData);
  40552. };
  40553. ParticleSystem.prototype.rebuild = function () {
  40554. this._createIndexBuffer();
  40555. this._vertexBuffer._rebuild();
  40556. };
  40557. ParticleSystem.prototype.render = function () {
  40558. var effect = this._getEffect();
  40559. // Check
  40560. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  40561. return 0;
  40562. var engine = this._scene.getEngine();
  40563. // Render
  40564. engine.enableEffect(effect);
  40565. engine.setState(false);
  40566. var viewMatrix = this._scene.getViewMatrix();
  40567. effect.setTexture("diffuseSampler", this.particleTexture);
  40568. effect.setMatrix("view", viewMatrix);
  40569. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  40570. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  40571. if (this._scene.clipPlane) {
  40572. var clipPlane = this._scene.clipPlane;
  40573. var invView = viewMatrix.clone();
  40574. invView.invert();
  40575. effect.setMatrix("invView", invView);
  40576. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  40577. }
  40578. // VBOs
  40579. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40580. // Draw order
  40581. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  40582. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  40583. }
  40584. else {
  40585. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  40586. }
  40587. if (this.forceDepthWrite) {
  40588. engine.setDepthWrite(true);
  40589. }
  40590. engine.draw(true, 0, this.particles.length * 6);
  40591. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40592. return this.particles.length;
  40593. };
  40594. ParticleSystem.prototype.dispose = function () {
  40595. if (this._vertexBuffer) {
  40596. this._vertexBuffer.dispose();
  40597. this._vertexBuffer = null;
  40598. }
  40599. if (this._indexBuffer) {
  40600. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40601. this._indexBuffer = null;
  40602. }
  40603. if (this.particleTexture) {
  40604. this.particleTexture.dispose();
  40605. this.particleTexture = null;
  40606. }
  40607. // Remove from scene
  40608. var index = this._scene.particleSystems.indexOf(this);
  40609. if (index > -1) {
  40610. this._scene.particleSystems.splice(index, 1);
  40611. }
  40612. // Callback
  40613. this.onDisposeObservable.notifyObservers(this);
  40614. this.onDisposeObservable.clear();
  40615. };
  40616. // Clone
  40617. ParticleSystem.prototype.clone = function (name, newEmitter) {
  40618. var custom = null;
  40619. var program = null;
  40620. if (this.customShader != null) {
  40621. program = this.customShader;
  40622. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  40623. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  40624. }
  40625. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  40626. result.customShader = program;
  40627. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  40628. if (newEmitter === undefined) {
  40629. newEmitter = this.emitter;
  40630. }
  40631. result.emitter = newEmitter;
  40632. if (this.particleTexture) {
  40633. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  40634. }
  40635. if (!this.preventAutoStart) {
  40636. result.start();
  40637. }
  40638. return result;
  40639. };
  40640. ParticleSystem.prototype.serialize = function () {
  40641. var serializationObject = {};
  40642. serializationObject.name = this.name;
  40643. serializationObject.id = this.id;
  40644. // Emitter
  40645. if (this.emitter.position) {
  40646. var emitterMesh = this.emitter;
  40647. serializationObject.emitterId = emitterMesh.id;
  40648. }
  40649. else {
  40650. var emitterPosition = this.emitter;
  40651. serializationObject.emitter = emitterPosition.asArray();
  40652. }
  40653. serializationObject.capacity = this.getCapacity();
  40654. if (this.particleTexture) {
  40655. serializationObject.textureName = this.particleTexture.name;
  40656. }
  40657. // Animations
  40658. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  40659. // Particle system
  40660. serializationObject.minAngularSpeed = this.minAngularSpeed;
  40661. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  40662. serializationObject.minSize = this.minSize;
  40663. serializationObject.maxSize = this.maxSize;
  40664. serializationObject.minEmitPower = this.minEmitPower;
  40665. serializationObject.maxEmitPower = this.maxEmitPower;
  40666. serializationObject.minLifeTime = this.minLifeTime;
  40667. serializationObject.maxLifeTime = this.maxLifeTime;
  40668. serializationObject.emitRate = this.emitRate;
  40669. serializationObject.minEmitBox = this.minEmitBox.asArray();
  40670. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  40671. serializationObject.gravity = this.gravity.asArray();
  40672. serializationObject.direction1 = this.direction1.asArray();
  40673. serializationObject.direction2 = this.direction2.asArray();
  40674. serializationObject.color1 = this.color1.asArray();
  40675. serializationObject.color2 = this.color2.asArray();
  40676. serializationObject.colorDead = this.colorDead.asArray();
  40677. serializationObject.updateSpeed = this.updateSpeed;
  40678. serializationObject.targetStopDuration = this.targetStopDuration;
  40679. serializationObject.textureMask = this.textureMask.asArray();
  40680. serializationObject.blendMode = this.blendMode;
  40681. serializationObject.customShader = this.customShader;
  40682. serializationObject.preventAutoStart = this.preventAutoStart;
  40683. return serializationObject;
  40684. };
  40685. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  40686. var name = parsedParticleSystem.name;
  40687. var custom = null;
  40688. var program = null;
  40689. if (parsedParticleSystem.customShader) {
  40690. program = parsedParticleSystem.customShader;
  40691. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  40692. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  40693. }
  40694. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  40695. particleSystem.customShader = program;
  40696. if (parsedParticleSystem.id) {
  40697. particleSystem.id = parsedParticleSystem.id;
  40698. }
  40699. // Auto start
  40700. if (parsedParticleSystem.preventAutoStart) {
  40701. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  40702. }
  40703. // Texture
  40704. if (parsedParticleSystem.textureName) {
  40705. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  40706. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  40707. }
  40708. // Emitter
  40709. if (parsedParticleSystem.emitterId) {
  40710. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  40711. }
  40712. else {
  40713. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  40714. }
  40715. // Animations
  40716. if (parsedParticleSystem.animations) {
  40717. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  40718. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  40719. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  40720. }
  40721. }
  40722. if (parsedParticleSystem.autoAnimate) {
  40723. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  40724. }
  40725. // Particle system
  40726. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  40727. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  40728. particleSystem.minSize = parsedParticleSystem.minSize;
  40729. particleSystem.maxSize = parsedParticleSystem.maxSize;
  40730. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  40731. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  40732. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  40733. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  40734. particleSystem.emitRate = parsedParticleSystem.emitRate;
  40735. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  40736. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  40737. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  40738. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  40739. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  40740. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  40741. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  40742. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  40743. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  40744. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  40745. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  40746. particleSystem.blendMode = parsedParticleSystem.blendMode;
  40747. if (!particleSystem.preventAutoStart) {
  40748. particleSystem.start();
  40749. }
  40750. return particleSystem;
  40751. };
  40752. // Statics
  40753. ParticleSystem.BLENDMODE_ONEONE = 0;
  40754. ParticleSystem.BLENDMODE_STANDARD = 1;
  40755. return ParticleSystem;
  40756. }());
  40757. BABYLON.ParticleSystem = ParticleSystem;
  40758. })(BABYLON || (BABYLON = {}));
  40759. //# sourceMappingURL=babylon.particleSystem.js.map
  40760. var BABYLON;
  40761. (function (BABYLON) {
  40762. var SolidParticle = (function () {
  40763. /**
  40764. * Creates a Solid Particle object.
  40765. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  40766. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  40767. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  40768. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  40769. * `shapeId` (integer) is the model shape identifier in the SPS.
  40770. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  40771. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  40772. */
  40773. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  40774. this.idx = 0; // particle global index
  40775. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  40776. this.position = BABYLON.Vector3.Zero(); // position
  40777. this.rotation = BABYLON.Vector3.Zero(); // rotation
  40778. this.scaling = BABYLON.Vector3.One(); // scaling
  40779. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  40780. this.velocity = BABYLON.Vector3.Zero(); // velocity
  40781. this.alive = true; // alive
  40782. this.isVisible = true; // visibility
  40783. this._pos = 0; // index of this particle in the global "positions" array
  40784. this.shapeId = 0; // model shape id
  40785. this.idxInShape = 0; // index of the particle in its shape id
  40786. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  40787. this.idx = particleIndex;
  40788. this._pos = positionIndex;
  40789. this._model = model;
  40790. this.shapeId = shapeId;
  40791. this.idxInShape = idxInShape;
  40792. this._sps = sps;
  40793. if (modelBoundingInfo) {
  40794. this._modelBoundingInfo = modelBoundingInfo;
  40795. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  40796. }
  40797. }
  40798. Object.defineProperty(SolidParticle.prototype, "scale", {
  40799. /**
  40800. * legacy support, changed scale to scaling
  40801. */
  40802. get: function () {
  40803. return this.scaling;
  40804. },
  40805. set: function (scale) {
  40806. this.scaling = scale;
  40807. },
  40808. enumerable: true,
  40809. configurable: true
  40810. });
  40811. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  40812. /**
  40813. * legacy support, changed quaternion to rotationQuaternion
  40814. */
  40815. get: function () {
  40816. return this.rotationQuaternion;
  40817. },
  40818. set: function (q) {
  40819. this.rotationQuaternion = q;
  40820. },
  40821. enumerable: true,
  40822. configurable: true
  40823. });
  40824. /**
  40825. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  40826. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  40827. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  40828. */
  40829. SolidParticle.prototype.intersectsMesh = function (target) {
  40830. if (!this._boundingInfo || !target._boundingInfo) {
  40831. return false;
  40832. }
  40833. if (this._sps._bSphereOnly) {
  40834. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  40835. }
  40836. return this._boundingInfo.intersects(target._boundingInfo, false);
  40837. };
  40838. return SolidParticle;
  40839. }());
  40840. BABYLON.SolidParticle = SolidParticle;
  40841. var ModelShape = (function () {
  40842. /**
  40843. * 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.
  40844. * SPS internal tool, don't use it manually.
  40845. */
  40846. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  40847. this.shapeID = id;
  40848. this._shape = shape;
  40849. this._shapeUV = shapeUV;
  40850. this._positionFunction = posFunction;
  40851. this._vertexFunction = vtxFunction;
  40852. }
  40853. return ModelShape;
  40854. }());
  40855. BABYLON.ModelShape = ModelShape;
  40856. })(BABYLON || (BABYLON = {}));
  40857. //# sourceMappingURL=babylon.solidParticle.js.map
  40858. var BABYLON;
  40859. (function (BABYLON) {
  40860. /**
  40861. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  40862. */
  40863. var SolidParticleSystem = (function () {
  40864. /**
  40865. * Creates a SPS (Solid Particle System) object.
  40866. * `name` (String) is the SPS name, this will be the underlying mesh name.
  40867. * `scene` (Scene) is the scene in which the SPS is added.
  40868. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  40869. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  40870. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  40871. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  40872. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  40873. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  40874. */
  40875. function SolidParticleSystem(name, scene, options) {
  40876. // public members
  40877. /**
  40878. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  40879. * Example : var p = SPS.particles[i];
  40880. */
  40881. this.particles = new Array();
  40882. /**
  40883. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  40884. */
  40885. this.nbParticles = 0;
  40886. /**
  40887. * If the particles must ever face the camera (default false). Useful for planar particles.
  40888. */
  40889. this.billboard = false;
  40890. /**
  40891. * Recompute normals when adding a shape
  40892. */
  40893. this.recomputeNormals = true;
  40894. /**
  40895. * This a counter ofr your own usage. It's not set by any SPS functions.
  40896. */
  40897. this.counter = 0;
  40898. /**
  40899. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  40900. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  40901. */
  40902. this.vars = {};
  40903. this._positions = new Array();
  40904. this._indices = new Array();
  40905. this._normals = new Array();
  40906. this._colors = new Array();
  40907. this._uvs = new Array();
  40908. this._index = 0; // indices index
  40909. this._updatable = true;
  40910. this._pickable = false;
  40911. this._isVisibilityBoxLocked = false;
  40912. this._alwaysVisible = false;
  40913. this._shapeCounter = 0;
  40914. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  40915. this._color = new BABYLON.Color4(0, 0, 0, 0);
  40916. this._computeParticleColor = true;
  40917. this._computeParticleTexture = true;
  40918. this._computeParticleRotation = true;
  40919. this._computeParticleVertex = false;
  40920. this._computeBoundingBox = false;
  40921. this._cam_axisZ = BABYLON.Vector3.Zero();
  40922. this._cam_axisY = BABYLON.Vector3.Zero();
  40923. this._cam_axisX = BABYLON.Vector3.Zero();
  40924. this._axisX = BABYLON.Axis.X;
  40925. this._axisY = BABYLON.Axis.Y;
  40926. this._axisZ = BABYLON.Axis.Z;
  40927. this._camDir = BABYLON.Vector3.Zero();
  40928. this._rotMatrix = new BABYLON.Matrix();
  40929. this._invertMatrix = new BABYLON.Matrix();
  40930. this._rotated = BABYLON.Vector3.Zero();
  40931. this._quaternion = new BABYLON.Quaternion();
  40932. this._vertex = BABYLON.Vector3.Zero();
  40933. this._normal = BABYLON.Vector3.Zero();
  40934. this._yaw = 0.0;
  40935. this._pitch = 0.0;
  40936. this._roll = 0.0;
  40937. this._halfroll = 0.0;
  40938. this._halfpitch = 0.0;
  40939. this._halfyaw = 0.0;
  40940. this._sinRoll = 0.0;
  40941. this._cosRoll = 0.0;
  40942. this._sinPitch = 0.0;
  40943. this._cosPitch = 0.0;
  40944. this._sinYaw = 0.0;
  40945. this._cosYaw = 0.0;
  40946. this._w = 0.0;
  40947. this._mustUnrotateFixedNormals = false;
  40948. this._minimum = BABYLON.Tmp.Vector3[0];
  40949. this._maximum = BABYLON.Tmp.Vector3[1];
  40950. this._scale = BABYLON.Tmp.Vector3[2];
  40951. this._translation = BABYLON.Tmp.Vector3[3];
  40952. this._minBbox = BABYLON.Tmp.Vector3[4];
  40953. this._maxBbox = BABYLON.Tmp.Vector3[5];
  40954. this._particlesIntersect = false;
  40955. this._bSphereOnly = false;
  40956. this._bSphereRadiusFactor = 1.0;
  40957. this.name = name;
  40958. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  40959. this._camera = scene.activeCamera;
  40960. this._pickable = options ? options.isPickable : false;
  40961. this._particlesIntersect = options ? options.particleIntersection : false;
  40962. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  40963. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  40964. if (options && options.updatable) {
  40965. this._updatable = options.updatable;
  40966. }
  40967. else {
  40968. this._updatable = true;
  40969. }
  40970. if (this._pickable) {
  40971. this.pickedParticles = [];
  40972. }
  40973. }
  40974. /**
  40975. * Builds the SPS underlying mesh. Returns a standard Mesh.
  40976. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  40977. */
  40978. SolidParticleSystem.prototype.buildMesh = function () {
  40979. if (this.nbParticles === 0) {
  40980. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  40981. this.addShape(triangle, 1);
  40982. triangle.dispose();
  40983. }
  40984. this._positions32 = new Float32Array(this._positions);
  40985. this._uvs32 = new Float32Array(this._uvs);
  40986. this._colors32 = new Float32Array(this._colors);
  40987. if (this.recomputeNormals) {
  40988. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  40989. }
  40990. this._normals32 = new Float32Array(this._normals);
  40991. this._fixedNormal32 = new Float32Array(this._normals);
  40992. if (this._mustUnrotateFixedNormals) {
  40993. this._unrotateFixedNormals();
  40994. }
  40995. var vertexData = new BABYLON.VertexData();
  40996. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  40997. vertexData.indices = this._indices;
  40998. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  40999. if (this._uvs32) {
  41000. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  41001. ;
  41002. }
  41003. if (this._colors32) {
  41004. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  41005. }
  41006. var mesh = new BABYLON.Mesh(this.name, this._scene);
  41007. vertexData.applyToMesh(mesh, this._updatable);
  41008. this.mesh = mesh;
  41009. this.mesh.isPickable = this._pickable;
  41010. // free memory
  41011. this._positions = null;
  41012. this._normals = null;
  41013. this._uvs = null;
  41014. this._colors = null;
  41015. if (!this._updatable) {
  41016. this.particles.length = 0;
  41017. }
  41018. return mesh;
  41019. };
  41020. /**
  41021. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  41022. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  41023. * Thus the particles generated from `digest()` have their property `position` set yet.
  41024. * `mesh` ( Mesh ) is the mesh to be digested
  41025. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  41026. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  41027. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  41028. */
  41029. SolidParticleSystem.prototype.digest = function (mesh, options) {
  41030. var size = (options && options.facetNb) || 1;
  41031. var number = (options && options.number);
  41032. var delta = (options && options.delta) || 0;
  41033. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41034. var meshInd = mesh.getIndices();
  41035. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41036. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  41037. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  41038. var f = 0; // facet counter
  41039. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  41040. // compute size from number
  41041. if (number) {
  41042. number = (number > totalFacets) ? totalFacets : number;
  41043. size = Math.round(totalFacets / number);
  41044. delta = 0;
  41045. }
  41046. else {
  41047. size = (size > totalFacets) ? totalFacets : size;
  41048. }
  41049. var facetPos = []; // submesh positions
  41050. var facetInd = []; // submesh indices
  41051. var facetUV = []; // submesh UV
  41052. var facetCol = []; // submesh colors
  41053. var barycenter = BABYLON.Tmp.Vector3[0];
  41054. var rand;
  41055. var sizeO = size;
  41056. while (f < totalFacets) {
  41057. size = sizeO + Math.floor((1 + delta) * Math.random());
  41058. if (f > totalFacets - size) {
  41059. size = totalFacets - f;
  41060. }
  41061. // reset temp arrays
  41062. facetPos.length = 0;
  41063. facetInd.length = 0;
  41064. facetUV.length = 0;
  41065. facetCol.length = 0;
  41066. // iterate over "size" facets
  41067. var fi = 0;
  41068. for (var j = f * 3; j < (f + size) * 3; j++) {
  41069. facetInd.push(fi);
  41070. var i = meshInd[j];
  41071. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  41072. if (meshUV) {
  41073. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  41074. }
  41075. if (meshCol) {
  41076. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  41077. }
  41078. fi++;
  41079. }
  41080. // create a model shape for each single particle
  41081. var idx = this.nbParticles;
  41082. var shape = this._posToShape(facetPos);
  41083. var shapeUV = this._uvsToShapeUV(facetUV);
  41084. // compute the barycenter of the shape
  41085. var v;
  41086. for (v = 0; v < shape.length; v++) {
  41087. barycenter.addInPlace(shape[v]);
  41088. }
  41089. barycenter.scaleInPlace(1 / shape.length);
  41090. // shift the shape from its barycenter to the origin
  41091. for (v = 0; v < shape.length; v++) {
  41092. shape[v].subtractInPlace(barycenter);
  41093. }
  41094. var bInfo;
  41095. if (this._particlesIntersect) {
  41096. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  41097. }
  41098. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  41099. // add the particle in the SPS
  41100. var currentPos = this._positions.length;
  41101. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  41102. this._addParticle(idx, currentPos, modelShape, this._shapeCounter, 0, bInfo);
  41103. // initialize the particle position
  41104. this.particles[this.nbParticles].position.addInPlace(barycenter);
  41105. this._index += shape.length;
  41106. idx++;
  41107. this.nbParticles++;
  41108. this._shapeCounter++;
  41109. f += size;
  41110. }
  41111. return this;
  41112. };
  41113. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  41114. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  41115. var index = 0;
  41116. var idx = 0;
  41117. for (var p = 0; p < this.particles.length; p++) {
  41118. this._particle = this.particles[p];
  41119. this._shape = this._particle._model._shape;
  41120. if (this._particle.rotationQuaternion) {
  41121. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  41122. }
  41123. else {
  41124. this._yaw = this._particle.rotation.y;
  41125. this._pitch = this._particle.rotation.x;
  41126. this._roll = this._particle.rotation.z;
  41127. this._quaternionRotationYPR();
  41128. }
  41129. this._quaternionToRotationMatrix();
  41130. this._rotMatrix.invertToRef(this._invertMatrix);
  41131. for (var pt = 0; pt < this._shape.length; pt++) {
  41132. idx = index + pt * 3;
  41133. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  41134. this._fixedNormal32[idx] = this._normal.x;
  41135. this._fixedNormal32[idx + 1] = this._normal.y;
  41136. this._fixedNormal32[idx + 2] = this._normal.z;
  41137. }
  41138. index = idx + 3;
  41139. }
  41140. };
  41141. //reset copy
  41142. SolidParticleSystem.prototype._resetCopy = function () {
  41143. this._copy.position.x = 0;
  41144. this._copy.position.y = 0;
  41145. this._copy.position.z = 0;
  41146. this._copy.rotation.x = 0;
  41147. this._copy.rotation.y = 0;
  41148. this._copy.rotation.z = 0;
  41149. this._copy.rotationQuaternion = null;
  41150. this._copy.scaling.x = 1;
  41151. this._copy.scaling.y = 1;
  41152. this._copy.scaling.z = 1;
  41153. this._copy.uvs.x = 0;
  41154. this._copy.uvs.y = 0;
  41155. this._copy.uvs.z = 1;
  41156. this._copy.uvs.w = 1;
  41157. this._copy.color = null;
  41158. };
  41159. // _meshBuilder : inserts the shape model in the global SPS mesh
  41160. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  41161. var i;
  41162. var u = 0;
  41163. var c = 0;
  41164. var n = 0;
  41165. this._resetCopy();
  41166. if (options && options.positionFunction) {
  41167. options.positionFunction(this._copy, idx, idxInShape);
  41168. this._mustUnrotateFixedNormals = true;
  41169. }
  41170. if (this._copy.rotationQuaternion) {
  41171. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  41172. }
  41173. else {
  41174. this._yaw = this._copy.rotation.y;
  41175. this._pitch = this._copy.rotation.x;
  41176. this._roll = this._copy.rotation.z;
  41177. this._quaternionRotationYPR();
  41178. }
  41179. this._quaternionToRotationMatrix();
  41180. for (i = 0; i < shape.length; i++) {
  41181. this._vertex.x = shape[i].x;
  41182. this._vertex.y = shape[i].y;
  41183. this._vertex.z = shape[i].z;
  41184. if (options && options.vertexFunction) {
  41185. options.vertexFunction(this._copy, this._vertex, i);
  41186. }
  41187. this._vertex.x *= this._copy.scaling.x;
  41188. this._vertex.y *= this._copy.scaling.y;
  41189. this._vertex.z *= this._copy.scaling.z;
  41190. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  41191. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  41192. if (meshUV) {
  41193. 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);
  41194. u += 2;
  41195. }
  41196. if (this._copy.color) {
  41197. this._color = this._copy.color;
  41198. }
  41199. else if (meshCol && meshCol[c] !== undefined) {
  41200. this._color.r = meshCol[c];
  41201. this._color.g = meshCol[c + 1];
  41202. this._color.b = meshCol[c + 2];
  41203. this._color.a = meshCol[c + 3];
  41204. }
  41205. else {
  41206. this._color.r = 1;
  41207. this._color.g = 1;
  41208. this._color.b = 1;
  41209. this._color.a = 1;
  41210. }
  41211. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  41212. c += 4;
  41213. if (!this.recomputeNormals && meshNor) {
  41214. this._normal.x = meshNor[n];
  41215. this._normal.y = meshNor[n + 1];
  41216. this._normal.z = meshNor[n + 2];
  41217. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  41218. normals.push(this._normal.x, this._normal.y, this._normal.z);
  41219. n += 3;
  41220. }
  41221. }
  41222. for (i = 0; i < meshInd.length; i++) {
  41223. indices.push(p + meshInd[i]);
  41224. }
  41225. if (this._pickable) {
  41226. var nbfaces = meshInd.length / 3;
  41227. for (i = 0; i < nbfaces; i++) {
  41228. this.pickedParticles.push({ idx: idx, faceId: i });
  41229. }
  41230. }
  41231. return this._copy;
  41232. };
  41233. // returns a shape array from positions array
  41234. SolidParticleSystem.prototype._posToShape = function (positions) {
  41235. var shape = [];
  41236. for (var i = 0; i < positions.length; i += 3) {
  41237. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  41238. }
  41239. return shape;
  41240. };
  41241. // returns a shapeUV array from a Vector4 uvs
  41242. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  41243. var shapeUV = [];
  41244. if (uvs) {
  41245. for (var i = 0; i < uvs.length; i++)
  41246. shapeUV.push(uvs[i]);
  41247. }
  41248. return shapeUV;
  41249. };
  41250. // adds a new particle object in the particles array
  41251. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  41252. var sp = new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo);
  41253. this.particles.push(sp);
  41254. return sp;
  41255. };
  41256. /**
  41257. * Adds some particles to the SPS from the model shape. Returns the shape id.
  41258. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  41259. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  41260. * `nb` (positive integer) the number of particles to be created from this model
  41261. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  41262. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  41263. */
  41264. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  41265. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41266. var meshInd = mesh.getIndices();
  41267. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41268. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  41269. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  41270. var bbInfo;
  41271. if (this._particlesIntersect) {
  41272. bbInfo = mesh.getBoundingInfo();
  41273. }
  41274. var shape = this._posToShape(meshPos);
  41275. var shapeUV = this._uvsToShapeUV(meshUV);
  41276. var posfunc = options ? options.positionFunction : null;
  41277. var vtxfunc = options ? options.vertexFunction : null;
  41278. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  41279. // particles
  41280. var sp;
  41281. var currentCopy;
  41282. var idx = this.nbParticles;
  41283. for (var i = 0; i < nb; i++) {
  41284. var currentPos = this._positions.length;
  41285. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  41286. if (this._updatable) {
  41287. sp = this._addParticle(idx, currentPos, modelShape, this._shapeCounter, i, bbInfo);
  41288. sp.position.copyFrom(currentCopy.position);
  41289. sp.rotation.copyFrom(currentCopy.rotation);
  41290. if (currentCopy.rotationQuaternion) {
  41291. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  41292. }
  41293. if (currentCopy.color) {
  41294. sp.color.copyFrom(currentCopy.color);
  41295. }
  41296. sp.scaling.copyFrom(currentCopy.scaling);
  41297. sp.uvs.copyFrom(currentCopy.uvs);
  41298. }
  41299. this._index += shape.length;
  41300. idx++;
  41301. }
  41302. this.nbParticles += nb;
  41303. this._shapeCounter++;
  41304. return this._shapeCounter - 1;
  41305. };
  41306. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  41307. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  41308. this._resetCopy();
  41309. if (particle._model._positionFunction) {
  41310. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  41311. }
  41312. if (this._copy.rotationQuaternion) {
  41313. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  41314. }
  41315. else {
  41316. this._yaw = this._copy.rotation.y;
  41317. this._pitch = this._copy.rotation.x;
  41318. this._roll = this._copy.rotation.z;
  41319. this._quaternionRotationYPR();
  41320. }
  41321. this._quaternionToRotationMatrix();
  41322. this._shape = particle._model._shape;
  41323. for (var pt = 0; pt < this._shape.length; pt++) {
  41324. this._vertex.x = this._shape[pt].x;
  41325. this._vertex.y = this._shape[pt].y;
  41326. this._vertex.z = this._shape[pt].z;
  41327. if (particle._model._vertexFunction) {
  41328. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  41329. }
  41330. this._vertex.x *= this._copy.scaling.x;
  41331. this._vertex.y *= this._copy.scaling.y;
  41332. this._vertex.z *= this._copy.scaling.z;
  41333. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  41334. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  41335. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  41336. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  41337. }
  41338. particle.position.x = 0.0;
  41339. particle.position.y = 0.0;
  41340. particle.position.z = 0.0;
  41341. particle.rotation.x = 0.0;
  41342. particle.rotation.y = 0.0;
  41343. particle.rotation.z = 0.0;
  41344. particle.rotationQuaternion = null;
  41345. particle.scaling.x = 1.0;
  41346. particle.scaling.y = 1.0;
  41347. particle.scaling.z = 1.0;
  41348. };
  41349. /**
  41350. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  41351. * Returns the SPS.
  41352. */
  41353. SolidParticleSystem.prototype.rebuildMesh = function () {
  41354. for (var p = 0; p < this.particles.length; p++) {
  41355. this._rebuildParticle(this.particles[p]);
  41356. }
  41357. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  41358. return this;
  41359. };
  41360. /**
  41361. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  41362. * This method calls `updateParticle()` for each particle of the SPS.
  41363. * For an animated SPS, it is usually called within the render loop.
  41364. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  41365. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  41366. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  41367. * Returns the SPS.
  41368. */
  41369. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  41370. if (start === void 0) { start = 0; }
  41371. if (end === void 0) { end = this.nbParticles - 1; }
  41372. if (update === void 0) { update = true; }
  41373. if (!this._updatable) {
  41374. return;
  41375. }
  41376. // custom beforeUpdate
  41377. this.beforeUpdateParticles(start, end, update);
  41378. this._cam_axisX.x = 1.0;
  41379. this._cam_axisX.y = 0.0;
  41380. this._cam_axisX.z = 0.0;
  41381. this._cam_axisY.x = 0.0;
  41382. this._cam_axisY.y = 1.0;
  41383. this._cam_axisY.z = 0.0;
  41384. this._cam_axisZ.x = 0.0;
  41385. this._cam_axisZ.y = 0.0;
  41386. this._cam_axisZ.z = 1.0;
  41387. // if the particles will always face the camera
  41388. if (this.billboard) {
  41389. this.mesh.computeWorldMatrix(true);
  41390. // compute the camera position and un-rotate it by the current mesh rotation
  41391. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  41392. this._quaternionToRotationMatrix();
  41393. this._rotMatrix.invertToRef(this._invertMatrix);
  41394. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  41395. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  41396. this._cam_axisZ.normalize();
  41397. // same for camera up vector extracted from the cam view matrix
  41398. var view = this._camera.getViewMatrix(true);
  41399. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  41400. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  41401. this._cam_axisY.normalize();
  41402. this._cam_axisX.normalize();
  41403. }
  41404. }
  41405. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  41406. var idx = 0; // current position index in the global array positions32
  41407. var index = 0; // position start index in the global array positions32 of the current particle
  41408. var colidx = 0; // current color index in the global array colors32
  41409. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  41410. var uvidx = 0; // current uv index in the global array uvs32
  41411. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  41412. var pt = 0; // current index in the particle model shape
  41413. if (this.mesh.isFacetDataEnabled) {
  41414. this._computeBoundingBox = true;
  41415. }
  41416. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  41417. if (this._computeBoundingBox) {
  41418. if (start == 0 && end == this.nbParticles - 1) {
  41419. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  41420. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  41421. }
  41422. else {
  41423. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  41424. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  41425. }
  41426. }
  41427. // particle loop
  41428. index = this.particles[start]._pos;
  41429. var vpos = (index / 3) | 0;
  41430. colorIndex = vpos * 4;
  41431. uvIndex = vpos * 2;
  41432. for (var p = start; p <= end; p++) {
  41433. this._particle = this.particles[p];
  41434. this._shape = this._particle._model._shape;
  41435. this._shapeUV = this._particle._model._shapeUV;
  41436. // call to custom user function to update the particle properties
  41437. this.updateParticle(this._particle);
  41438. // skip the computations for inactive or already invisible particles
  41439. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  41440. // increment indexes for the next particle
  41441. pt = this._shape.length;
  41442. index += pt * 3;
  41443. colorIndex += pt * 4;
  41444. uvIndex += pt * 2;
  41445. continue;
  41446. }
  41447. if (this._particle.isVisible) {
  41448. this._particle._stillInvisible = false; // un-mark permanent invisibility
  41449. // particle rotation matrix
  41450. if (this.billboard) {
  41451. this._particle.rotation.x = 0.0;
  41452. this._particle.rotation.y = 0.0;
  41453. }
  41454. if (this._computeParticleRotation || this.billboard) {
  41455. if (this._particle.rotationQuaternion) {
  41456. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  41457. }
  41458. else {
  41459. this._yaw = this._particle.rotation.y;
  41460. this._pitch = this._particle.rotation.x;
  41461. this._roll = this._particle.rotation.z;
  41462. this._quaternionRotationYPR();
  41463. }
  41464. this._quaternionToRotationMatrix();
  41465. }
  41466. // particle vertex loop
  41467. for (pt = 0; pt < this._shape.length; pt++) {
  41468. idx = index + pt * 3;
  41469. colidx = colorIndex + pt * 4;
  41470. uvidx = uvIndex + pt * 2;
  41471. this._vertex.x = this._shape[pt].x;
  41472. this._vertex.y = this._shape[pt].y;
  41473. this._vertex.z = this._shape[pt].z;
  41474. if (this._computeParticleVertex) {
  41475. this.updateParticleVertex(this._particle, this._vertex, pt);
  41476. }
  41477. // positions
  41478. this._vertex.x *= this._particle.scaling.x;
  41479. this._vertex.y *= this._particle.scaling.y;
  41480. this._vertex.z *= this._particle.scaling.z;
  41481. 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];
  41482. 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;
  41483. 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;
  41484. 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;
  41485. 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;
  41486. 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;
  41487. 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;
  41488. if (this._computeBoundingBox) {
  41489. if (this._positions32[idx] < this._minimum.x) {
  41490. this._minimum.x = this._positions32[idx];
  41491. }
  41492. if (this._positions32[idx] > this._maximum.x) {
  41493. this._maximum.x = this._positions32[idx];
  41494. }
  41495. if (this._positions32[idx + 1] < this._minimum.y) {
  41496. this._minimum.y = this._positions32[idx + 1];
  41497. }
  41498. if (this._positions32[idx + 1] > this._maximum.y) {
  41499. this._maximum.y = this._positions32[idx + 1];
  41500. }
  41501. if (this._positions32[idx + 2] < this._minimum.z) {
  41502. this._minimum.z = this._positions32[idx + 2];
  41503. }
  41504. if (this._positions32[idx + 2] > this._maximum.z) {
  41505. this._maximum.z = this._positions32[idx + 2];
  41506. }
  41507. }
  41508. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  41509. if (!this._computeParticleVertex) {
  41510. this._normal.x = this._fixedNormal32[idx];
  41511. this._normal.y = this._fixedNormal32[idx + 1];
  41512. this._normal.z = this._fixedNormal32[idx + 2];
  41513. 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]);
  41514. 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]);
  41515. 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]);
  41516. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  41517. 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;
  41518. 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;
  41519. }
  41520. if (this._computeParticleColor) {
  41521. this._colors32[colidx] = this._particle.color.r;
  41522. this._colors32[colidx + 1] = this._particle.color.g;
  41523. this._colors32[colidx + 2] = this._particle.color.b;
  41524. this._colors32[colidx + 3] = this._particle.color.a;
  41525. }
  41526. if (this._computeParticleTexture) {
  41527. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  41528. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  41529. }
  41530. }
  41531. }
  41532. else {
  41533. this._particle._stillInvisible = true; // mark the particle as invisible
  41534. for (pt = 0; pt < this._shape.length; pt++) {
  41535. idx = index + pt * 3;
  41536. colidx = colorIndex + pt * 4;
  41537. uvidx = uvIndex + pt * 2;
  41538. this._positions32[idx] = 0.0;
  41539. this._positions32[idx + 1] = 0.0;
  41540. this._positions32[idx + 2] = 0.0;
  41541. this._normals32[idx] = 0.0;
  41542. this._normals32[idx + 1] = 0.0;
  41543. this._normals32[idx + 2] = 0.0;
  41544. if (this._computeParticleColor) {
  41545. this._colors32[colidx] = this._particle.color.r;
  41546. this._colors32[colidx + 1] = this._particle.color.g;
  41547. this._colors32[colidx + 2] = this._particle.color.b;
  41548. this._colors32[colidx + 3] = this._particle.color.a;
  41549. }
  41550. if (this._computeParticleTexture) {
  41551. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  41552. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  41553. }
  41554. }
  41555. }
  41556. // if the particle intersections must be computed : update the bbInfo
  41557. if (this._particlesIntersect) {
  41558. var bInfo = this._particle._boundingInfo;
  41559. var bBox = bInfo.boundingBox;
  41560. var bSphere = bInfo.boundingSphere;
  41561. if (!this._bSphereOnly) {
  41562. // place, scale and rotate the particle bbox within the SPS local system, then update it
  41563. for (var b = 0; b < bBox.vectors.length; b++) {
  41564. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  41565. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  41566. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  41567. 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];
  41568. 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;
  41569. 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;
  41570. 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;
  41571. 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;
  41572. 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;
  41573. 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;
  41574. }
  41575. bBox._update(this.mesh._worldMatrix);
  41576. }
  41577. // place and scale the particle bouding sphere in the SPS local system, then update it
  41578. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  41579. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  41580. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  41581. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  41582. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  41583. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  41584. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  41585. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  41586. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  41587. 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));
  41588. bSphere._update(this.mesh._worldMatrix);
  41589. }
  41590. // increment indexes for the next particle
  41591. index = idx + 3;
  41592. colorIndex = colidx + 4;
  41593. uvIndex = uvidx + 2;
  41594. }
  41595. // if the VBO must be updated
  41596. if (update) {
  41597. if (this._computeParticleColor) {
  41598. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  41599. }
  41600. if (this._computeParticleTexture) {
  41601. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  41602. }
  41603. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  41604. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  41605. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  41606. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  41607. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  41608. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  41609. for (var i = 0; i < this._normals32.length; i++) {
  41610. this._fixedNormal32[i] = this._normals32[i];
  41611. }
  41612. }
  41613. if (!this.mesh.areNormalsFrozen) {
  41614. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  41615. }
  41616. }
  41617. }
  41618. if (this._computeBoundingBox) {
  41619. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  41620. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  41621. }
  41622. this.afterUpdateParticles(start, end, update);
  41623. return this;
  41624. };
  41625. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  41626. this._halfroll = this._roll * 0.5;
  41627. this._halfpitch = this._pitch * 0.5;
  41628. this._halfyaw = this._yaw * 0.5;
  41629. this._sinRoll = Math.sin(this._halfroll);
  41630. this._cosRoll = Math.cos(this._halfroll);
  41631. this._sinPitch = Math.sin(this._halfpitch);
  41632. this._cosPitch = Math.cos(this._halfpitch);
  41633. this._sinYaw = Math.sin(this._halfyaw);
  41634. this._cosYaw = Math.cos(this._halfyaw);
  41635. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  41636. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  41637. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  41638. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  41639. };
  41640. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  41641. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  41642. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  41643. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  41644. this._rotMatrix.m[3] = 0;
  41645. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  41646. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  41647. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  41648. this._rotMatrix.m[7] = 0;
  41649. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  41650. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  41651. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  41652. this._rotMatrix.m[11] = 0;
  41653. this._rotMatrix.m[12] = 0;
  41654. this._rotMatrix.m[13] = 0;
  41655. this._rotMatrix.m[14] = 0;
  41656. this._rotMatrix.m[15] = 1.0;
  41657. };
  41658. /**
  41659. * Disposes the SPS.
  41660. * Returns nothing.
  41661. */
  41662. SolidParticleSystem.prototype.dispose = function () {
  41663. this.mesh.dispose();
  41664. this.vars = null;
  41665. // drop references to internal big arrays for the GC
  41666. this._positions = null;
  41667. this._indices = null;
  41668. this._normals = null;
  41669. this._uvs = null;
  41670. this._colors = null;
  41671. this._positions32 = null;
  41672. this._normals32 = null;
  41673. this._fixedNormal32 = null;
  41674. this._uvs32 = null;
  41675. this._colors32 = null;
  41676. this.pickedParticles = null;
  41677. };
  41678. /**
  41679. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  41680. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  41681. * Returns the SPS.
  41682. */
  41683. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  41684. if (!this._isVisibilityBoxLocked) {
  41685. this.mesh.refreshBoundingInfo();
  41686. }
  41687. return this;
  41688. };
  41689. /**
  41690. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  41691. * @param size the size (float) of the visibility box
  41692. * note : this doesn't lock the SPS mesh bounding box.
  41693. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  41694. */
  41695. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  41696. var vis = size / 2;
  41697. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  41698. };
  41699. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  41700. // getter and setter
  41701. get: function () {
  41702. return this._alwaysVisible;
  41703. },
  41704. /**
  41705. * Sets the SPS as always visible or not
  41706. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  41707. */
  41708. set: function (val) {
  41709. this._alwaysVisible = val;
  41710. this.mesh.alwaysSelectAsActiveMesh = val;
  41711. },
  41712. enumerable: true,
  41713. configurable: true
  41714. });
  41715. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  41716. get: function () {
  41717. return this._isVisibilityBoxLocked;
  41718. },
  41719. /**
  41720. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  41721. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  41722. */
  41723. set: function (val) {
  41724. this._isVisibilityBoxLocked = val;
  41725. this.mesh.getBoundingInfo().isLocked = val;
  41726. },
  41727. enumerable: true,
  41728. configurable: true
  41729. });
  41730. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  41731. // getters
  41732. get: function () {
  41733. return this._computeParticleRotation;
  41734. },
  41735. // Optimizer setters
  41736. /**
  41737. * Tells to `setParticles()` to compute the particle rotations or not.
  41738. * Default value : true. The SPS is faster when it's set to false.
  41739. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  41740. */
  41741. set: function (val) {
  41742. this._computeParticleRotation = val;
  41743. },
  41744. enumerable: true,
  41745. configurable: true
  41746. });
  41747. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  41748. get: function () {
  41749. return this._computeParticleColor;
  41750. },
  41751. /**
  41752. * Tells to `setParticles()` to compute the particle colors or not.
  41753. * Default value : true. The SPS is faster when it's set to false.
  41754. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  41755. */
  41756. set: function (val) {
  41757. this._computeParticleColor = val;
  41758. },
  41759. enumerable: true,
  41760. configurable: true
  41761. });
  41762. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  41763. get: function () {
  41764. return this._computeParticleTexture;
  41765. },
  41766. /**
  41767. * Tells to `setParticles()` to compute the particle textures or not.
  41768. * Default value : true. The SPS is faster when it's set to false.
  41769. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  41770. */
  41771. set: function (val) {
  41772. this._computeParticleTexture = val;
  41773. },
  41774. enumerable: true,
  41775. configurable: true
  41776. });
  41777. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  41778. get: function () {
  41779. return this._computeParticleVertex;
  41780. },
  41781. /**
  41782. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  41783. * Default value : false. The SPS is faster when it's set to false.
  41784. * Note : the particle custom vertex positions aren't stored values.
  41785. */
  41786. set: function (val) {
  41787. this._computeParticleVertex = val;
  41788. },
  41789. enumerable: true,
  41790. configurable: true
  41791. });
  41792. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  41793. get: function () {
  41794. return this._computeBoundingBox;
  41795. },
  41796. /**
  41797. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  41798. */
  41799. set: function (val) {
  41800. this._computeBoundingBox = val;
  41801. },
  41802. enumerable: true,
  41803. configurable: true
  41804. });
  41805. // =======================================================================
  41806. // Particle behavior logic
  41807. // these following methods may be overwritten by the user to fit his needs
  41808. /**
  41809. * This function does nothing. It may be overwritten to set all the particle first values.
  41810. * The SPS doesn't call this function, you may have to call it by your own.
  41811. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  41812. */
  41813. SolidParticleSystem.prototype.initParticles = function () {
  41814. };
  41815. /**
  41816. * This function does nothing. It may be overwritten to recycle a particle.
  41817. * The SPS doesn't call this function, you may have to call it by your own.
  41818. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  41819. */
  41820. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  41821. return particle;
  41822. };
  41823. /**
  41824. * Updates a particle : this function should be overwritten by the user.
  41825. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  41826. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  41827. * ex : just set a particle position or velocity and recycle conditions
  41828. */
  41829. SolidParticleSystem.prototype.updateParticle = function (particle) {
  41830. return particle;
  41831. };
  41832. /**
  41833. * Updates a vertex of a particle : it can be overwritten by the user.
  41834. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  41835. * @param particle the current particle
  41836. * @param vertex the current index of the current particle
  41837. * @param pt the index of the current vertex in the particle shape
  41838. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  41839. * ex : just set a vertex particle position
  41840. */
  41841. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  41842. return vertex;
  41843. };
  41844. /**
  41845. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  41846. * This does nothing and may be overwritten by the user.
  41847. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  41848. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  41849. * @param update the boolean update value actually passed to setParticles()
  41850. */
  41851. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  41852. };
  41853. /**
  41854. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  41855. * This will be passed three parameters.
  41856. * This does nothing and may be overwritten by the user.
  41857. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  41858. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  41859. * @param update the boolean update value actually passed to setParticles()
  41860. */
  41861. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  41862. };
  41863. return SolidParticleSystem;
  41864. }());
  41865. BABYLON.SolidParticleSystem = SolidParticleSystem;
  41866. })(BABYLON || (BABYLON = {}));
  41867. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  41868. /// <reference path="babylon.mesh.ts" />
  41869. var BABYLON;
  41870. (function (BABYLON) {
  41871. var GroundMesh = (function (_super) {
  41872. __extends(GroundMesh, _super);
  41873. function GroundMesh(name, scene) {
  41874. var _this = _super.call(this, name, scene) || this;
  41875. _this.generateOctree = false;
  41876. _this._worldInverse = new BABYLON.Matrix();
  41877. return _this;
  41878. }
  41879. GroundMesh.prototype.getClassName = function () {
  41880. return "GroundMesh";
  41881. };
  41882. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  41883. get: function () {
  41884. return Math.min(this._subdivisionsX, this._subdivisionsY);
  41885. },
  41886. enumerable: true,
  41887. configurable: true
  41888. });
  41889. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  41890. get: function () {
  41891. return this._subdivisionsX;
  41892. },
  41893. enumerable: true,
  41894. configurable: true
  41895. });
  41896. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  41897. get: function () {
  41898. return this._subdivisionsY;
  41899. },
  41900. enumerable: true,
  41901. configurable: true
  41902. });
  41903. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  41904. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  41905. this._subdivisionsX = chunksCount;
  41906. this._subdivisionsY = chunksCount;
  41907. this.subdivide(chunksCount);
  41908. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  41909. };
  41910. /**
  41911. * Returns a height (y) value in the Worl system :
  41912. * the ground altitude at the coordinates (x, z) expressed in the World system.
  41913. * Returns the ground y position if (x, z) are outside the ground surface.
  41914. */
  41915. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  41916. var world = this.getWorldMatrix();
  41917. var invMat = BABYLON.Tmp.Matrix[5];
  41918. world.invertToRef(invMat);
  41919. var tmpVect = BABYLON.Tmp.Vector3[8];
  41920. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  41921. x = tmpVect.x;
  41922. z = tmpVect.z;
  41923. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  41924. return this.position.y;
  41925. }
  41926. if (!this._heightQuads || this._heightQuads.length == 0) {
  41927. this._initHeightQuads();
  41928. this._computeHeightQuads();
  41929. }
  41930. var facet = this._getFacetAt(x, z);
  41931. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  41932. // return y in the World system
  41933. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  41934. return tmpVect.y;
  41935. };
  41936. /**
  41937. * Returns a normalized vector (Vector3) orthogonal to the ground
  41938. * at the ground coordinates (x, z) expressed in the World system.
  41939. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  41940. */
  41941. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  41942. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  41943. this.getNormalAtCoordinatesToRef(x, z, normal);
  41944. return normal;
  41945. };
  41946. /**
  41947. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  41948. * at the ground coordinates (x, z) expressed in the World system.
  41949. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  41950. * Returns the GroundMesh.
  41951. */
  41952. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  41953. var world = this.getWorldMatrix();
  41954. var tmpMat = BABYLON.Tmp.Matrix[5];
  41955. world.invertToRef(tmpMat);
  41956. var tmpVect = BABYLON.Tmp.Vector3[8];
  41957. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  41958. x = tmpVect.x;
  41959. z = tmpVect.z;
  41960. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  41961. return this;
  41962. }
  41963. if (!this._heightQuads || this._heightQuads.length == 0) {
  41964. this._initHeightQuads();
  41965. this._computeHeightQuads();
  41966. }
  41967. var facet = this._getFacetAt(x, z);
  41968. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  41969. return this;
  41970. };
  41971. /**
  41972. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  41973. * if the ground has been updated.
  41974. * This can be used in the render loop.
  41975. * Returns the GroundMesh.
  41976. */
  41977. GroundMesh.prototype.updateCoordinateHeights = function () {
  41978. if (!this._heightQuads || this._heightQuads.length == 0) {
  41979. this._initHeightQuads();
  41980. }
  41981. this._computeHeightQuads();
  41982. return this;
  41983. };
  41984. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  41985. GroundMesh.prototype._getFacetAt = function (x, z) {
  41986. // retrieve col and row from x, z coordinates in the ground local system
  41987. var subdivisionsX = this._subdivisionsX;
  41988. var subdivisionsY = this._subdivisionsY;
  41989. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  41990. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  41991. var quad = this._heightQuads[row * this._subdivisionsX + col];
  41992. var facet;
  41993. if (z < quad.slope.x * x + quad.slope.y) {
  41994. facet = quad.facet1;
  41995. }
  41996. else {
  41997. facet = quad.facet2;
  41998. }
  41999. return facet;
  42000. };
  42001. // Creates and populates the heightMap array with "facet" elements :
  42002. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  42003. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  42004. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  42005. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  42006. // Returns the GroundMesh.
  42007. GroundMesh.prototype._initHeightQuads = function () {
  42008. var subdivisionsX = this._subdivisionsX;
  42009. var subdivisionsY = this._subdivisionsY;
  42010. this._heightQuads = new Array();
  42011. for (var row = 0; row < subdivisionsY; row++) {
  42012. for (var col = 0; col < subdivisionsX; col++) {
  42013. 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) };
  42014. this._heightQuads[row * subdivisionsX + col] = quad;
  42015. }
  42016. }
  42017. return this;
  42018. };
  42019. // Compute each quad element values and update the the heightMap array :
  42020. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  42021. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  42022. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  42023. // Returns the GroundMesh.
  42024. GroundMesh.prototype._computeHeightQuads = function () {
  42025. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42026. var v1 = BABYLON.Tmp.Vector3[3];
  42027. var v2 = BABYLON.Tmp.Vector3[2];
  42028. var v3 = BABYLON.Tmp.Vector3[1];
  42029. var v4 = BABYLON.Tmp.Vector3[0];
  42030. var v1v2 = BABYLON.Tmp.Vector3[4];
  42031. var v1v3 = BABYLON.Tmp.Vector3[5];
  42032. var v1v4 = BABYLON.Tmp.Vector3[6];
  42033. var norm1 = BABYLON.Tmp.Vector3[7];
  42034. var norm2 = BABYLON.Tmp.Vector3[8];
  42035. var i = 0;
  42036. var j = 0;
  42037. var k = 0;
  42038. var cd = 0; // 2D slope coefficient : z = cd * x + h
  42039. var h = 0;
  42040. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  42041. var d2 = 0;
  42042. var subdivisionsX = this._subdivisionsX;
  42043. var subdivisionsY = this._subdivisionsY;
  42044. for (var row = 0; row < subdivisionsY; row++) {
  42045. for (var col = 0; col < subdivisionsX; col++) {
  42046. i = col * 3;
  42047. j = row * (subdivisionsX + 1) * 3;
  42048. k = (row + 1) * (subdivisionsX + 1) * 3;
  42049. v1.x = positions[j + i];
  42050. v1.y = positions[j + i + 1];
  42051. v1.z = positions[j + i + 2];
  42052. v2.x = positions[j + i + 3];
  42053. v2.y = positions[j + i + 4];
  42054. v2.z = positions[j + i + 5];
  42055. v3.x = positions[k + i];
  42056. v3.y = positions[k + i + 1];
  42057. v3.z = positions[k + i + 2];
  42058. v4.x = positions[k + i + 3];
  42059. v4.y = positions[k + i + 4];
  42060. v4.z = positions[k + i + 5];
  42061. // 2D slope V1V4
  42062. cd = (v4.z - v1.z) / (v4.x - v1.x);
  42063. h = v1.z - cd * v1.x; // v1 belongs to the slope
  42064. // facet equations :
  42065. // we compute each facet normal vector
  42066. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  42067. // we compute the value d by applying the equation to v1 which belongs to the plane
  42068. // then we store the facet equation in a Vector4
  42069. v2.subtractToRef(v1, v1v2);
  42070. v3.subtractToRef(v1, v1v3);
  42071. v4.subtractToRef(v1, v1v4);
  42072. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  42073. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  42074. norm1.normalize();
  42075. norm2.normalize();
  42076. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  42077. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  42078. var quad = this._heightQuads[row * subdivisionsX + col];
  42079. quad.slope.copyFromFloats(cd, h);
  42080. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  42081. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  42082. }
  42083. }
  42084. return this;
  42085. };
  42086. GroundMesh.prototype.serialize = function (serializationObject) {
  42087. _super.prototype.serialize.call(this, serializationObject);
  42088. serializationObject.subdivisionsX = this._subdivisionsX;
  42089. serializationObject.subdivisionsY = this._subdivisionsY;
  42090. serializationObject.minX = this._minX;
  42091. serializationObject.maxX = this._maxX;
  42092. serializationObject.minZ = this._minZ;
  42093. serializationObject.maxZ = this._maxZ;
  42094. serializationObject.width = this._width;
  42095. serializationObject.height = this._height;
  42096. };
  42097. GroundMesh.Parse = function (parsedMesh, scene) {
  42098. var result = new GroundMesh(parsedMesh.name, scene);
  42099. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  42100. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  42101. result._minX = parsedMesh.minX;
  42102. result._maxX = parsedMesh.maxX;
  42103. result._minZ = parsedMesh.minZ;
  42104. result._maxZ = parsedMesh.maxZ;
  42105. result._width = parsedMesh.width;
  42106. result._height = parsedMesh.height;
  42107. return result;
  42108. };
  42109. return GroundMesh;
  42110. }(BABYLON.Mesh));
  42111. BABYLON.GroundMesh = GroundMesh;
  42112. })(BABYLON || (BABYLON = {}));
  42113. //# sourceMappingURL=babylon.groundMesh.js.map
  42114. var BABYLON;
  42115. (function (BABYLON) {
  42116. /**
  42117. * Creates an instance based on a source mesh.
  42118. */
  42119. var InstancedMesh = (function (_super) {
  42120. __extends(InstancedMesh, _super);
  42121. function InstancedMesh(name, source) {
  42122. var _this = _super.call(this, name, source.getScene()) || this;
  42123. source.instances.push(_this);
  42124. _this._sourceMesh = source;
  42125. _this.position.copyFrom(source.position);
  42126. _this.rotation.copyFrom(source.rotation);
  42127. _this.scaling.copyFrom(source.scaling);
  42128. if (source.rotationQuaternion) {
  42129. _this.rotationQuaternion = source.rotationQuaternion.clone();
  42130. }
  42131. _this.infiniteDistance = source.infiniteDistance;
  42132. _this.setPivotMatrix(source.getPivotMatrix());
  42133. _this.refreshBoundingInfo();
  42134. _this._syncSubMeshes();
  42135. return _this;
  42136. }
  42137. /**
  42138. * Returns the string "InstancedMesh".
  42139. */
  42140. InstancedMesh.prototype.getClassName = function () {
  42141. return "InstancedMesh";
  42142. };
  42143. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  42144. // Methods
  42145. get: function () {
  42146. return this._sourceMesh.receiveShadows;
  42147. },
  42148. enumerable: true,
  42149. configurable: true
  42150. });
  42151. Object.defineProperty(InstancedMesh.prototype, "material", {
  42152. get: function () {
  42153. return this._sourceMesh.material;
  42154. },
  42155. enumerable: true,
  42156. configurable: true
  42157. });
  42158. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  42159. get: function () {
  42160. return this._sourceMesh.visibility;
  42161. },
  42162. enumerable: true,
  42163. configurable: true
  42164. });
  42165. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  42166. get: function () {
  42167. return this._sourceMesh.skeleton;
  42168. },
  42169. enumerable: true,
  42170. configurable: true
  42171. });
  42172. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  42173. get: function () {
  42174. return this._sourceMesh.renderingGroupId;
  42175. },
  42176. enumerable: true,
  42177. configurable: true
  42178. });
  42179. /**
  42180. * Returns the total number of vertices (integer).
  42181. */
  42182. InstancedMesh.prototype.getTotalVertices = function () {
  42183. return this._sourceMesh.getTotalVertices();
  42184. };
  42185. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  42186. get: function () {
  42187. return this._sourceMesh;
  42188. },
  42189. enumerable: true,
  42190. configurable: true
  42191. });
  42192. /**
  42193. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  42194. */
  42195. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  42196. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  42197. };
  42198. /**
  42199. * Sets the vertex data of the mesh geometry for the requested `kind`.
  42200. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  42201. * The `data` are either a numeric array either a Float32Array.
  42202. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  42203. * 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).
  42204. * Note that a new underlying VertexBuffer object is created each call.
  42205. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  42206. *
  42207. * Possible `kind` values :
  42208. * - BABYLON.VertexBuffer.PositionKind
  42209. * - BABYLON.VertexBuffer.UVKind
  42210. * - BABYLON.VertexBuffer.UV2Kind
  42211. * - BABYLON.VertexBuffer.UV3Kind
  42212. * - BABYLON.VertexBuffer.UV4Kind
  42213. * - BABYLON.VertexBuffer.UV5Kind
  42214. * - BABYLON.VertexBuffer.UV6Kind
  42215. * - BABYLON.VertexBuffer.ColorKind
  42216. * - BABYLON.VertexBuffer.MatricesIndicesKind
  42217. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  42218. * - BABYLON.VertexBuffer.MatricesWeightsKind
  42219. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  42220. *
  42221. * Returns the Mesh.
  42222. */
  42223. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  42224. if (this.sourceMesh) {
  42225. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  42226. }
  42227. return this.sourceMesh;
  42228. };
  42229. /**
  42230. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  42231. * If the mesh has no geometry, it is simply returned as it is.
  42232. * The `data` are either a numeric array either a Float32Array.
  42233. * No new underlying VertexBuffer object is created.
  42234. * 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.
  42235. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  42236. *
  42237. * Possible `kind` values :
  42238. * - BABYLON.VertexBuffer.PositionKind
  42239. * - BABYLON.VertexBuffer.UVKind
  42240. * - BABYLON.VertexBuffer.UV2Kind
  42241. * - BABYLON.VertexBuffer.UV3Kind
  42242. * - BABYLON.VertexBuffer.UV4Kind
  42243. * - BABYLON.VertexBuffer.UV5Kind
  42244. * - BABYLON.VertexBuffer.UV6Kind
  42245. * - BABYLON.VertexBuffer.ColorKind
  42246. * - BABYLON.VertexBuffer.MatricesIndicesKind
  42247. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  42248. * - BABYLON.VertexBuffer.MatricesWeightsKind
  42249. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  42250. *
  42251. * Returns the Mesh.
  42252. */
  42253. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  42254. if (this.sourceMesh) {
  42255. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  42256. }
  42257. return this.sourceMesh;
  42258. };
  42259. /**
  42260. * Sets the mesh indices.
  42261. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  42262. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  42263. * This method creates a new index buffer each call.
  42264. * Returns the Mesh.
  42265. */
  42266. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  42267. if (this.sourceMesh) {
  42268. this.sourceMesh.setIndices(indices, totalVertices);
  42269. }
  42270. return this.sourceMesh;
  42271. };
  42272. /**
  42273. * Boolean : True if the mesh owns the requested kind of data.
  42274. */
  42275. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  42276. return this._sourceMesh.isVerticesDataPresent(kind);
  42277. };
  42278. /**
  42279. * Returns an array of indices (IndicesArray).
  42280. */
  42281. InstancedMesh.prototype.getIndices = function () {
  42282. return this._sourceMesh.getIndices();
  42283. };
  42284. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  42285. get: function () {
  42286. return this._sourceMesh._positions;
  42287. },
  42288. enumerable: true,
  42289. configurable: true
  42290. });
  42291. /**
  42292. * Sets a new updated BoundingInfo to the mesh.
  42293. * Returns the mesh.
  42294. */
  42295. InstancedMesh.prototype.refreshBoundingInfo = function () {
  42296. var meshBB = this._sourceMesh.getBoundingInfo();
  42297. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  42298. this._updateBoundingInfo();
  42299. return this;
  42300. };
  42301. InstancedMesh.prototype._preActivate = function () {
  42302. if (this._currentLOD) {
  42303. this._currentLOD._preActivate();
  42304. }
  42305. return this;
  42306. };
  42307. InstancedMesh.prototype._activate = function (renderId) {
  42308. if (this._currentLOD) {
  42309. this._currentLOD._registerInstanceForRenderId(this, renderId);
  42310. }
  42311. return this;
  42312. };
  42313. /**
  42314. * Returns the current associated LOD AbstractMesh.
  42315. */
  42316. InstancedMesh.prototype.getLOD = function (camera) {
  42317. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  42318. if (this._currentLOD === this.sourceMesh) {
  42319. return this;
  42320. }
  42321. return this._currentLOD;
  42322. };
  42323. InstancedMesh.prototype._syncSubMeshes = function () {
  42324. this.releaseSubMeshes();
  42325. if (this._sourceMesh.subMeshes) {
  42326. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  42327. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  42328. }
  42329. }
  42330. return this;
  42331. };
  42332. InstancedMesh.prototype._generatePointsArray = function () {
  42333. return this._sourceMesh._generatePointsArray();
  42334. };
  42335. /**
  42336. * Creates a new InstancedMesh from the current mesh.
  42337. * - name (string) : the cloned mesh name
  42338. * - newParent (optional Node) : the optional Node to parent the clone to.
  42339. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  42340. *
  42341. * Returns the clone.
  42342. */
  42343. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  42344. var result = this._sourceMesh.createInstance(name);
  42345. // Deep copy
  42346. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  42347. // Bounding info
  42348. this.refreshBoundingInfo();
  42349. // Parent
  42350. if (newParent) {
  42351. result.parent = newParent;
  42352. }
  42353. if (!doNotCloneChildren) {
  42354. // Children
  42355. for (var index = 0; index < this.getScene().meshes.length; index++) {
  42356. var mesh = this.getScene().meshes[index];
  42357. if (mesh.parent === this) {
  42358. mesh.clone(mesh.name, result);
  42359. }
  42360. }
  42361. }
  42362. result.computeWorldMatrix(true);
  42363. return result;
  42364. };
  42365. /**
  42366. * Disposes the InstancedMesh.
  42367. * Returns nothing.
  42368. */
  42369. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  42370. // Remove from mesh
  42371. var index = this._sourceMesh.instances.indexOf(this);
  42372. this._sourceMesh.instances.splice(index, 1);
  42373. _super.prototype.dispose.call(this, doNotRecurse);
  42374. };
  42375. return InstancedMesh;
  42376. }(BABYLON.AbstractMesh));
  42377. BABYLON.InstancedMesh = InstancedMesh;
  42378. })(BABYLON || (BABYLON = {}));
  42379. //# sourceMappingURL=babylon.instancedMesh.js.map
  42380. /// <reference path="babylon.mesh.ts" />
  42381. var BABYLON;
  42382. (function (BABYLON) {
  42383. var LinesMesh = (function (_super) {
  42384. __extends(LinesMesh, _super);
  42385. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  42386. if (parent === void 0) { parent = null; }
  42387. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  42388. _this.useVertexColor = useVertexColor;
  42389. _this.color = new BABYLON.Color3(1, 1, 1);
  42390. _this.alpha = 1;
  42391. if (source) {
  42392. _this.color = source.color.clone();
  42393. _this.alpha = source.alpha;
  42394. _this.useVertexColor = source.useVertexColor;
  42395. }
  42396. _this._intersectionThreshold = 0.1;
  42397. var options = {
  42398. attributes: [BABYLON.VertexBuffer.PositionKind],
  42399. uniforms: ["world", "viewProjection"],
  42400. needAlphaBlending: false,
  42401. };
  42402. if (!useVertexColor) {
  42403. options.uniforms.push("color");
  42404. options.needAlphaBlending = true;
  42405. }
  42406. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  42407. return _this;
  42408. }
  42409. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  42410. /**
  42411. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  42412. * This margin is expressed in world space coordinates, so its value may vary.
  42413. * Default value is 0.1
  42414. * @returns the intersection Threshold value.
  42415. */
  42416. get: function () {
  42417. return this._intersectionThreshold;
  42418. },
  42419. /**
  42420. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  42421. * This margin is expressed in world space coordinates, so its value may vary.
  42422. * @param value the new threshold to apply
  42423. */
  42424. set: function (value) {
  42425. if (this._intersectionThreshold === value) {
  42426. return;
  42427. }
  42428. this._intersectionThreshold = value;
  42429. if (this.geometry) {
  42430. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  42431. }
  42432. },
  42433. enumerable: true,
  42434. configurable: true
  42435. });
  42436. /**
  42437. * Returns the string "LineMesh"
  42438. */
  42439. LinesMesh.prototype.getClassName = function () {
  42440. return "LinesMesh";
  42441. };
  42442. Object.defineProperty(LinesMesh.prototype, "material", {
  42443. get: function () {
  42444. return this._colorShader;
  42445. },
  42446. enumerable: true,
  42447. configurable: true
  42448. });
  42449. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  42450. get: function () {
  42451. return false;
  42452. },
  42453. enumerable: true,
  42454. configurable: true
  42455. });
  42456. LinesMesh.prototype.createInstance = function (name) {
  42457. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  42458. return null;
  42459. };
  42460. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  42461. // VBOs
  42462. this._geometry._bind(this._colorShader.getEffect());
  42463. // Color
  42464. if (!this.useVertexColor) {
  42465. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  42466. }
  42467. return this;
  42468. };
  42469. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  42470. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  42471. return this;
  42472. }
  42473. var engine = this.getScene().getEngine();
  42474. // Draw order
  42475. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  42476. return this;
  42477. };
  42478. LinesMesh.prototype.dispose = function (doNotRecurse) {
  42479. this._colorShader.dispose();
  42480. _super.prototype.dispose.call(this, doNotRecurse);
  42481. };
  42482. /**
  42483. * Returns a new LineMesh object cloned from the current one.
  42484. */
  42485. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  42486. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  42487. };
  42488. return LinesMesh;
  42489. }(BABYLON.Mesh));
  42490. BABYLON.LinesMesh = LinesMesh;
  42491. })(BABYLON || (BABYLON = {}));
  42492. //# sourceMappingURL=babylon.linesMesh.js.map
  42493. var BABYLON;
  42494. (function (BABYLON) {
  42495. var ShaderMaterial = (function (_super) {
  42496. __extends(ShaderMaterial, _super);
  42497. function ShaderMaterial(name, scene, shaderPath, options) {
  42498. var _this = _super.call(this, name, scene) || this;
  42499. _this._textures = {};
  42500. _this._textureArrays = {};
  42501. _this._floats = {};
  42502. _this._floatsArrays = {};
  42503. _this._colors3 = {};
  42504. _this._colors3Arrays = {};
  42505. _this._colors4 = {};
  42506. _this._vectors2 = {};
  42507. _this._vectors3 = {};
  42508. _this._vectors4 = {};
  42509. _this._matrices = {};
  42510. _this._matrices3x3 = {};
  42511. _this._matrices2x2 = {};
  42512. _this._vectors3Arrays = {};
  42513. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  42514. _this._shaderPath = shaderPath;
  42515. options.needAlphaBlending = options.needAlphaBlending || false;
  42516. options.needAlphaTesting = options.needAlphaTesting || false;
  42517. options.attributes = options.attributes || ["position", "normal", "uv"];
  42518. options.uniforms = options.uniforms || ["worldViewProjection"];
  42519. options.uniformBuffers = options.uniformBuffers || [];
  42520. options.samplers = options.samplers || [];
  42521. options.defines = options.defines || [];
  42522. _this._options = options;
  42523. return _this;
  42524. }
  42525. ShaderMaterial.prototype.getClassName = function () {
  42526. return "ShaderMaterial";
  42527. };
  42528. ShaderMaterial.prototype.needAlphaBlending = function () {
  42529. return this._options.needAlphaBlending;
  42530. };
  42531. ShaderMaterial.prototype.needAlphaTesting = function () {
  42532. return this._options.needAlphaTesting;
  42533. };
  42534. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  42535. if (this._options.uniforms.indexOf(uniformName) === -1) {
  42536. this._options.uniforms.push(uniformName);
  42537. }
  42538. };
  42539. ShaderMaterial.prototype.setTexture = function (name, texture) {
  42540. if (this._options.samplers.indexOf(name) === -1) {
  42541. this._options.samplers.push(name);
  42542. }
  42543. this._textures[name] = texture;
  42544. return this;
  42545. };
  42546. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  42547. if (this._options.samplers.indexOf(name) === -1) {
  42548. this._options.samplers.push(name);
  42549. }
  42550. this._checkUniform(name);
  42551. this._textureArrays[name] = textures;
  42552. return this;
  42553. };
  42554. ShaderMaterial.prototype.setFloat = function (name, value) {
  42555. this._checkUniform(name);
  42556. this._floats[name] = value;
  42557. return this;
  42558. };
  42559. ShaderMaterial.prototype.setFloats = function (name, value) {
  42560. this._checkUniform(name);
  42561. this._floatsArrays[name] = value;
  42562. return this;
  42563. };
  42564. ShaderMaterial.prototype.setColor3 = function (name, value) {
  42565. this._checkUniform(name);
  42566. this._colors3[name] = value;
  42567. return this;
  42568. };
  42569. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  42570. this._checkUniform(name);
  42571. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  42572. color.toArray(arr, arr.length);
  42573. return arr;
  42574. }, []);
  42575. return this;
  42576. };
  42577. ShaderMaterial.prototype.setColor4 = function (name, value) {
  42578. this._checkUniform(name);
  42579. this._colors4[name] = value;
  42580. return this;
  42581. };
  42582. ShaderMaterial.prototype.setVector2 = function (name, value) {
  42583. this._checkUniform(name);
  42584. this._vectors2[name] = value;
  42585. return this;
  42586. };
  42587. ShaderMaterial.prototype.setVector3 = function (name, value) {
  42588. this._checkUniform(name);
  42589. this._vectors3[name] = value;
  42590. return this;
  42591. };
  42592. ShaderMaterial.prototype.setVector4 = function (name, value) {
  42593. this._checkUniform(name);
  42594. this._vectors4[name] = value;
  42595. return this;
  42596. };
  42597. ShaderMaterial.prototype.setMatrix = function (name, value) {
  42598. this._checkUniform(name);
  42599. this._matrices[name] = value;
  42600. return this;
  42601. };
  42602. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  42603. this._checkUniform(name);
  42604. this._matrices3x3[name] = value;
  42605. return this;
  42606. };
  42607. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  42608. this._checkUniform(name);
  42609. this._matrices2x2[name] = value;
  42610. return this;
  42611. };
  42612. ShaderMaterial.prototype.setArray3 = function (name, value) {
  42613. this._checkUniform(name);
  42614. this._vectors3Arrays[name] = value;
  42615. return this;
  42616. };
  42617. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  42618. if (!mesh) {
  42619. return true;
  42620. }
  42621. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  42622. return false;
  42623. }
  42624. return false;
  42625. };
  42626. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  42627. var scene = this.getScene();
  42628. var engine = scene.getEngine();
  42629. if (!this.checkReadyOnEveryCall) {
  42630. if (this._renderId === scene.getRenderId()) {
  42631. if (this._checkCache(scene, mesh, useInstances)) {
  42632. return true;
  42633. }
  42634. }
  42635. }
  42636. // Instances
  42637. var defines = [];
  42638. var attribs = [];
  42639. var fallbacks = new BABYLON.EffectFallbacks();
  42640. if (useInstances) {
  42641. defines.push("#define INSTANCES");
  42642. }
  42643. for (var index = 0; index < this._options.defines.length; index++) {
  42644. defines.push(this._options.defines[index]);
  42645. }
  42646. for (var index = 0; index < this._options.attributes.length; index++) {
  42647. attribs.push(this._options.attributes[index]);
  42648. }
  42649. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  42650. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42651. defines.push("#define VERTEXCOLOR");
  42652. }
  42653. // Bones
  42654. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  42655. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42656. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42657. if (mesh.numBoneInfluencers > 4) {
  42658. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42659. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42660. }
  42661. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  42662. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  42663. fallbacks.addCPUSkinningFallback(0, mesh);
  42664. if (this._options.uniforms.indexOf("mBones") === -1) {
  42665. this._options.uniforms.push("mBones");
  42666. }
  42667. }
  42668. else {
  42669. defines.push("#define NUM_BONE_INFLUENCERS 0");
  42670. }
  42671. // Textures
  42672. for (var name in this._textures) {
  42673. if (!this._textures[name].isReady()) {
  42674. return false;
  42675. }
  42676. }
  42677. // Alpha test
  42678. if (engine.getAlphaTesting()) {
  42679. defines.push("#define ALPHATEST");
  42680. }
  42681. var previousEffect = this._effect;
  42682. var join = defines.join("\n");
  42683. this._effect = engine.createEffect(this._shaderPath, {
  42684. attributes: attribs,
  42685. uniformsNames: this._options.uniforms,
  42686. uniformBuffersNames: this._options.uniformBuffers,
  42687. samplers: this._options.samplers,
  42688. defines: join,
  42689. fallbacks: fallbacks,
  42690. onCompiled: this.onCompiled,
  42691. onError: this.onError
  42692. }, engine);
  42693. if (!this._effect.isReady()) {
  42694. return false;
  42695. }
  42696. if (previousEffect !== this._effect) {
  42697. scene.resetCachedMaterial();
  42698. }
  42699. this._renderId = scene.getRenderId();
  42700. return true;
  42701. };
  42702. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42703. var scene = this.getScene();
  42704. if (this._options.uniforms.indexOf("world") !== -1) {
  42705. this._effect.setMatrix("world", world);
  42706. }
  42707. if (this._options.uniforms.indexOf("worldView") !== -1) {
  42708. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  42709. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  42710. }
  42711. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  42712. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  42713. }
  42714. };
  42715. ShaderMaterial.prototype.bind = function (world, mesh) {
  42716. // Std values
  42717. this.bindOnlyWorldMatrix(world);
  42718. if (this.getScene().getCachedMaterial() !== this) {
  42719. if (this._options.uniforms.indexOf("view") !== -1) {
  42720. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  42721. }
  42722. if (this._options.uniforms.indexOf("projection") !== -1) {
  42723. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  42724. }
  42725. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  42726. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  42727. }
  42728. // Bones
  42729. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  42730. var name;
  42731. // Texture
  42732. for (name in this._textures) {
  42733. this._effect.setTexture(name, this._textures[name]);
  42734. }
  42735. // Texture arrays
  42736. for (name in this._textureArrays) {
  42737. this._effect.setTextureArray(name, this._textureArrays[name]);
  42738. }
  42739. // Float
  42740. for (name in this._floats) {
  42741. this._effect.setFloat(name, this._floats[name]);
  42742. }
  42743. // Float s
  42744. for (name in this._floatsArrays) {
  42745. this._effect.setArray(name, this._floatsArrays[name]);
  42746. }
  42747. // Color3
  42748. for (name in this._colors3) {
  42749. this._effect.setColor3(name, this._colors3[name]);
  42750. }
  42751. for (name in this._colors3Arrays) {
  42752. this._effect.setArray3(name, this._colors3Arrays[name]);
  42753. }
  42754. // Color4
  42755. for (name in this._colors4) {
  42756. var color = this._colors4[name];
  42757. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  42758. }
  42759. // Vector2
  42760. for (name in this._vectors2) {
  42761. this._effect.setVector2(name, this._vectors2[name]);
  42762. }
  42763. // Vector3
  42764. for (name in this._vectors3) {
  42765. this._effect.setVector3(name, this._vectors3[name]);
  42766. }
  42767. // Vector4
  42768. for (name in this._vectors4) {
  42769. this._effect.setVector4(name, this._vectors4[name]);
  42770. }
  42771. // Matrix
  42772. for (name in this._matrices) {
  42773. this._effect.setMatrix(name, this._matrices[name]);
  42774. }
  42775. // Matrix 3x3
  42776. for (name in this._matrices3x3) {
  42777. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  42778. }
  42779. // Matrix 2x2
  42780. for (name in this._matrices2x2) {
  42781. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  42782. }
  42783. // Vector3Array
  42784. for (name in this._vectors3Arrays) {
  42785. this._effect.setArray3(name, this._vectors3Arrays[name]);
  42786. }
  42787. }
  42788. this._afterBind(mesh);
  42789. };
  42790. ShaderMaterial.prototype.getActiveTextures = function () {
  42791. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42792. for (var name in this._textures) {
  42793. activeTextures.push(this._textures[name]);
  42794. }
  42795. for (var name in this._textureArrays) {
  42796. var array = this._textureArrays[name];
  42797. for (var index = 0; index < array.length; index++) {
  42798. activeTextures.push(array[index]);
  42799. }
  42800. }
  42801. return activeTextures;
  42802. };
  42803. ShaderMaterial.prototype.hasTexture = function (texture) {
  42804. if (_super.prototype.hasTexture.call(this, texture)) {
  42805. return true;
  42806. }
  42807. for (var name in this._textures) {
  42808. if (this._textures[name] === texture) {
  42809. return true;
  42810. }
  42811. }
  42812. for (var name in this._textureArrays) {
  42813. var array = this._textureArrays[name];
  42814. for (var index = 0; index < array.length; index++) {
  42815. if (array[index] === texture) {
  42816. return true;
  42817. }
  42818. }
  42819. }
  42820. return false;
  42821. };
  42822. ShaderMaterial.prototype.clone = function (name) {
  42823. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  42824. return newShaderMaterial;
  42825. };
  42826. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42827. if (forceDisposeTextures) {
  42828. var name;
  42829. for (name in this._textures) {
  42830. this._textures[name].dispose();
  42831. }
  42832. for (name in this._textureArrays) {
  42833. var array = this._textureArrays[name];
  42834. for (var index = 0; index < array.length; index++) {
  42835. array[index].dispose();
  42836. }
  42837. }
  42838. }
  42839. this._textures = {};
  42840. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42841. };
  42842. ShaderMaterial.prototype.serialize = function () {
  42843. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42844. serializationObject.customType = "BABYLON.ShaderMaterial";
  42845. serializationObject.options = this._options;
  42846. serializationObject.shaderPath = this._shaderPath;
  42847. var name;
  42848. // Texture
  42849. serializationObject.textures = {};
  42850. for (name in this._textures) {
  42851. serializationObject.textures[name] = this._textures[name].serialize();
  42852. }
  42853. // Texture arrays
  42854. serializationObject.textureArrays = {};
  42855. for (name in this._textureArrays) {
  42856. serializationObject.textureArrays[name] = [];
  42857. var array = this._textureArrays[name];
  42858. for (var index = 0; index < array.length; index++) {
  42859. serializationObject.textureArrays[name].push(array[index].serialize());
  42860. }
  42861. }
  42862. // Float
  42863. serializationObject.floats = {};
  42864. for (name in this._floats) {
  42865. serializationObject.floats[name] = this._floats[name];
  42866. }
  42867. // Float s
  42868. serializationObject.floatArrays = {};
  42869. for (name in this._floatsArrays) {
  42870. serializationObject.floatArrays[name] = this._floatsArrays[name];
  42871. }
  42872. // Color3
  42873. serializationObject.colors3 = {};
  42874. for (name in this._colors3) {
  42875. serializationObject.colors3[name] = this._colors3[name].asArray();
  42876. }
  42877. // Color3 array
  42878. serializationObject.colors3Arrays = {};
  42879. for (name in this._colors3Arrays) {
  42880. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  42881. }
  42882. // Color4
  42883. serializationObject.colors4 = {};
  42884. for (name in this._colors4) {
  42885. serializationObject.colors4[name] = this._colors4[name].asArray();
  42886. }
  42887. // Vector2
  42888. serializationObject.vectors2 = {};
  42889. for (name in this._vectors2) {
  42890. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  42891. }
  42892. // Vector3
  42893. serializationObject.vectors3 = {};
  42894. for (name in this._vectors3) {
  42895. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  42896. }
  42897. // Vector4
  42898. serializationObject.vectors4 = {};
  42899. for (name in this._vectors4) {
  42900. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  42901. }
  42902. // Matrix
  42903. serializationObject.matrices = {};
  42904. for (name in this._matrices) {
  42905. serializationObject.matrices[name] = this._matrices[name].asArray();
  42906. }
  42907. // Matrix 3x3
  42908. serializationObject.matrices3x3 = {};
  42909. for (name in this._matrices3x3) {
  42910. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  42911. }
  42912. // Matrix 2x2
  42913. serializationObject.matrices2x2 = {};
  42914. for (name in this._matrices2x2) {
  42915. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  42916. }
  42917. // Vector3Array
  42918. serializationObject.vectors3Arrays = {};
  42919. for (name in this._vectors3Arrays) {
  42920. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  42921. }
  42922. return serializationObject;
  42923. };
  42924. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  42925. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  42926. var name;
  42927. // Texture
  42928. for (name in source.textures) {
  42929. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  42930. }
  42931. // Texture arrays
  42932. for (name in source.textureArrays) {
  42933. var array = source.textureArrays[name];
  42934. var textureArray = new Array();
  42935. for (var index = 0; index < array.length; index++) {
  42936. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  42937. }
  42938. material.setTextureArray(name, textureArray);
  42939. }
  42940. // Float
  42941. for (name in source.floats) {
  42942. material.setFloat(name, source.floats[name]);
  42943. }
  42944. // Float s
  42945. for (name in source.floatsArrays) {
  42946. material.setFloats(name, source.floatsArrays[name]);
  42947. }
  42948. // Color3
  42949. for (name in source.colors3) {
  42950. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  42951. }
  42952. // Color3 arrays
  42953. for (name in source.colors3Arrays) {
  42954. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  42955. if (i % 3 === 0) {
  42956. arr.push([num]);
  42957. }
  42958. else {
  42959. arr[arr.length - 1].push(num);
  42960. }
  42961. return arr;
  42962. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  42963. material.setColor3Array(name, colors);
  42964. }
  42965. // Color4
  42966. for (name in source.colors4) {
  42967. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  42968. }
  42969. // Vector2
  42970. for (name in source.vectors2) {
  42971. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  42972. }
  42973. // Vector3
  42974. for (name in source.vectors3) {
  42975. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  42976. }
  42977. // Vector4
  42978. for (name in source.vectors4) {
  42979. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  42980. }
  42981. // Matrix
  42982. for (name in source.matrices) {
  42983. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  42984. }
  42985. // Matrix 3x3
  42986. for (name in source.matrices3x3) {
  42987. material.setMatrix3x3(name, source.matrices3x3[name]);
  42988. }
  42989. // Matrix 2x2
  42990. for (name in source.matrices2x2) {
  42991. material.setMatrix2x2(name, source.matrices2x2[name]);
  42992. }
  42993. // Vector3Array
  42994. for (name in source.vectors3Arrays) {
  42995. material.setArray3(name, source.vectors3Arrays[name]);
  42996. }
  42997. return material;
  42998. };
  42999. return ShaderMaterial;
  43000. }(BABYLON.Material));
  43001. BABYLON.ShaderMaterial = ShaderMaterial;
  43002. })(BABYLON || (BABYLON = {}));
  43003. //# sourceMappingURL=babylon.shaderMaterial.js.map
  43004. var BABYLON;
  43005. (function (BABYLON) {
  43006. var MeshBuilder = (function () {
  43007. function MeshBuilder() {
  43008. }
  43009. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  43010. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  43011. return BABYLON.Mesh.DOUBLESIDE;
  43012. }
  43013. if (orientation === undefined || orientation === null) {
  43014. return BABYLON.Mesh.FRONTSIDE;
  43015. }
  43016. return orientation;
  43017. };
  43018. /**
  43019. * Creates a box mesh.
  43020. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  43021. * The parameter `size` sets the size (float) of each box side (default 1).
  43022. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  43023. * 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).
  43024. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  43025. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43026. * 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).
  43027. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43028. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43029. */
  43030. MeshBuilder.CreateBox = function (name, options, scene) {
  43031. var box = new BABYLON.Mesh(name, scene);
  43032. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43033. box.sideOrientation = options.sideOrientation;
  43034. var vertexData = BABYLON.VertexData.CreateBox(options);
  43035. vertexData.applyToMesh(box, options.updatable);
  43036. return box;
  43037. };
  43038. /**
  43039. * Creates a sphere mesh.
  43040. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  43041. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  43042. * 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`).
  43043. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  43044. * 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
  43045. * 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).
  43046. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43047. * 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).
  43048. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43049. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43050. */
  43051. MeshBuilder.CreateSphere = function (name, options, scene) {
  43052. var sphere = new BABYLON.Mesh(name, scene);
  43053. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43054. sphere.sideOrientation = options.sideOrientation;
  43055. var vertexData = BABYLON.VertexData.CreateSphere(options);
  43056. vertexData.applyToMesh(sphere, options.updatable);
  43057. return sphere;
  43058. };
  43059. /**
  43060. * Creates a plane polygonal mesh. By default, this is a disc.
  43061. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  43062. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  43063. * 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.
  43064. * 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
  43065. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43066. * 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).
  43067. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43068. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43069. */
  43070. MeshBuilder.CreateDisc = function (name, options, scene) {
  43071. var disc = new BABYLON.Mesh(name, scene);
  43072. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43073. disc.sideOrientation = options.sideOrientation;
  43074. var vertexData = BABYLON.VertexData.CreateDisc(options);
  43075. vertexData.applyToMesh(disc, options.updatable);
  43076. return disc;
  43077. };
  43078. /**
  43079. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  43080. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  43081. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  43082. * 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`).
  43083. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  43084. * 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.
  43085. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43086. * 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).
  43087. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43088. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43089. */
  43090. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  43091. var sphere = new BABYLON.Mesh(name, scene);
  43092. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43093. sphere.sideOrientation = options.sideOrientation;
  43094. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  43095. vertexData.applyToMesh(sphere, options.updatable);
  43096. return sphere;
  43097. };
  43098. ;
  43099. /**
  43100. * Creates a ribbon mesh.
  43101. * 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.
  43102. *
  43103. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  43104. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  43105. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  43106. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  43107. * 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.
  43108. * 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.
  43109. * 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
  43110. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43111. * 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).
  43112. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43113. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  43114. * 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.
  43115. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  43116. * 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
  43117. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  43118. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  43119. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43120. */
  43121. MeshBuilder.CreateRibbon = function (name, options, scene) {
  43122. var pathArray = options.pathArray;
  43123. var closeArray = options.closeArray;
  43124. var closePath = options.closePath;
  43125. var offset = options.offset;
  43126. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43127. var instance = options.instance;
  43128. var updatable = options.updatable;
  43129. if (instance) {
  43130. // positionFunction : ribbon case
  43131. // only pathArray and sideOrientation parameters are taken into account for positions update
  43132. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  43133. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  43134. var positionFunction = function (positions) {
  43135. var minlg = pathArray[0].length;
  43136. var i = 0;
  43137. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  43138. for (var si = 1; si <= ns; si++) {
  43139. for (var p = 0; p < pathArray.length; p++) {
  43140. var path = pathArray[p];
  43141. var l = path.length;
  43142. minlg = (minlg < l) ? minlg : l;
  43143. var j = 0;
  43144. while (j < minlg) {
  43145. positions[i] = path[j].x;
  43146. positions[i + 1] = path[j].y;
  43147. positions[i + 2] = path[j].z;
  43148. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  43149. BABYLON.Tmp.Vector3[0].x = path[j].x;
  43150. }
  43151. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  43152. BABYLON.Tmp.Vector3[1].x = path[j].x;
  43153. }
  43154. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  43155. BABYLON.Tmp.Vector3[0].y = path[j].y;
  43156. }
  43157. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  43158. BABYLON.Tmp.Vector3[1].y = path[j].y;
  43159. }
  43160. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  43161. BABYLON.Tmp.Vector3[0].z = path[j].z;
  43162. }
  43163. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  43164. BABYLON.Tmp.Vector3[1].z = path[j].z;
  43165. }
  43166. j++;
  43167. i += 3;
  43168. }
  43169. if (instance._closePath) {
  43170. positions[i] = path[0].x;
  43171. positions[i + 1] = path[0].y;
  43172. positions[i + 2] = path[0].z;
  43173. i += 3;
  43174. }
  43175. }
  43176. }
  43177. };
  43178. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  43179. positionFunction(positions);
  43180. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  43181. instance._boundingInfo.update(instance._worldMatrix);
  43182. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  43183. if (options.colors) {
  43184. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  43185. for (var c = 0; c < options.colors.length; c++) {
  43186. colors[c * 4] = options.colors[c].r;
  43187. colors[c * 4 + 1] = options.colors[c].g;
  43188. colors[c * 4 + 2] = options.colors[c].b;
  43189. colors[c * 4 + 3] = options.colors[c].a;
  43190. }
  43191. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  43192. }
  43193. if (options.uvs) {
  43194. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  43195. for (var i = 0; i < options.uvs.length; i++) {
  43196. uvs[i * 2] = options.uvs[i].x;
  43197. uvs[i * 2 + 1] = options.uvs[i].y;
  43198. }
  43199. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  43200. }
  43201. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  43202. var indices = instance.getIndices();
  43203. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  43204. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  43205. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  43206. if (instance._closePath) {
  43207. var indexFirst = 0;
  43208. var indexLast = 0;
  43209. for (var p = 0; p < pathArray.length; p++) {
  43210. indexFirst = instance._idx[p] * 3;
  43211. if (p + 1 < pathArray.length) {
  43212. indexLast = (instance._idx[p + 1] - 1) * 3;
  43213. }
  43214. else {
  43215. indexLast = normals.length - 3;
  43216. }
  43217. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  43218. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  43219. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  43220. normals[indexLast] = normals[indexFirst];
  43221. normals[indexLast + 1] = normals[indexFirst + 1];
  43222. normals[indexLast + 2] = normals[indexFirst + 2];
  43223. }
  43224. }
  43225. if (!(instance.areNormalsFrozen)) {
  43226. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  43227. }
  43228. }
  43229. return instance;
  43230. }
  43231. else {
  43232. var ribbon = new BABYLON.Mesh(name, scene);
  43233. ribbon.sideOrientation = sideOrientation;
  43234. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  43235. if (closePath) {
  43236. ribbon._idx = vertexData._idx;
  43237. }
  43238. ribbon._closePath = closePath;
  43239. ribbon._closeArray = closeArray;
  43240. vertexData.applyToMesh(ribbon, updatable);
  43241. return ribbon;
  43242. }
  43243. };
  43244. /**
  43245. * Creates a cylinder or a cone mesh.
  43246. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  43247. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  43248. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  43249. * 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.
  43250. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  43251. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  43252. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  43253. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  43254. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  43255. * 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).
  43256. * 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
  43257. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  43258. * 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
  43259. * 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.
  43260. * If `enclose` is false, a ring surface is one element.
  43261. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  43262. * 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
  43263. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43264. * 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).
  43265. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43266. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43267. */
  43268. MeshBuilder.CreateCylinder = function (name, options, scene) {
  43269. var cylinder = new BABYLON.Mesh(name, scene);
  43270. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43271. cylinder.sideOrientation = options.sideOrientation;
  43272. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  43273. vertexData.applyToMesh(cylinder, options.updatable);
  43274. return cylinder;
  43275. };
  43276. /**
  43277. * Creates a torus mesh.
  43278. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  43279. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  43280. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  43281. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  43282. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43283. * 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).
  43284. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43285. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43286. */
  43287. MeshBuilder.CreateTorus = function (name, options, scene) {
  43288. var torus = new BABYLON.Mesh(name, scene);
  43289. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43290. torus.sideOrientation = options.sideOrientation;
  43291. var vertexData = BABYLON.VertexData.CreateTorus(options);
  43292. vertexData.applyToMesh(torus, options.updatable);
  43293. return torus;
  43294. };
  43295. /**
  43296. * Creates a torus knot mesh.
  43297. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  43298. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  43299. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  43300. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  43301. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  43302. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43303. * 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).
  43304. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43305. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43306. */
  43307. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  43308. var torusKnot = new BABYLON.Mesh(name, scene);
  43309. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43310. torusKnot.sideOrientation = options.sideOrientation;
  43311. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  43312. vertexData.applyToMesh(torusKnot, options.updatable);
  43313. return torusKnot;
  43314. };
  43315. /**
  43316. * Creates a line system mesh.
  43317. * A line system is a pool of many lines gathered in a single mesh.
  43318. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  43319. * 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.
  43320. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  43321. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  43322. * 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
  43323. * 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
  43324. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  43325. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43326. */
  43327. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  43328. var instance = options.instance;
  43329. var lines = options.lines;
  43330. if (instance) {
  43331. var positionFunction = function (positions) {
  43332. var i = 0;
  43333. for (var l = 0; l < lines.length; l++) {
  43334. var points = lines[l];
  43335. for (var p = 0; p < points.length; p++) {
  43336. positions[i] = points[p].x;
  43337. positions[i + 1] = points[p].y;
  43338. positions[i + 2] = points[p].z;
  43339. i += 3;
  43340. }
  43341. }
  43342. };
  43343. instance.updateMeshPositions(positionFunction, false);
  43344. return instance;
  43345. }
  43346. // line system creation
  43347. var lineSystem = new BABYLON.LinesMesh(name, scene);
  43348. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  43349. vertexData.applyToMesh(lineSystem, options.updatable);
  43350. return lineSystem;
  43351. };
  43352. /**
  43353. * Creates a line mesh.
  43354. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  43355. * 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.
  43356. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  43357. * The parameter `points` is an array successive Vector3.
  43358. * 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
  43359. * When updating an instance, remember that only point positions can change, not the number of points.
  43360. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43361. */
  43362. MeshBuilder.CreateLines = function (name, options, scene) {
  43363. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  43364. return lines;
  43365. };
  43366. /**
  43367. * Creates a dashed line mesh.
  43368. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  43369. * 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.
  43370. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  43371. * The parameter `points` is an array successive Vector3.
  43372. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  43373. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  43374. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  43375. * 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
  43376. * When updating an instance, remember that only point positions can change, not the number of points.
  43377. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43378. */
  43379. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  43380. var points = options.points;
  43381. var instance = options.instance;
  43382. var gapSize = options.gapSize;
  43383. var dashNb = options.dashNb;
  43384. var dashSize = options.dashSize;
  43385. if (instance) {
  43386. var positionFunction = function (positions) {
  43387. var curvect = BABYLON.Vector3.Zero();
  43388. var nbSeg = positions.length / 6;
  43389. var lg = 0;
  43390. var nb = 0;
  43391. var shft = 0;
  43392. var dashshft = 0;
  43393. var curshft = 0;
  43394. var p = 0;
  43395. var i = 0;
  43396. var j = 0;
  43397. for (i = 0; i < points.length - 1; i++) {
  43398. points[i + 1].subtractToRef(points[i], curvect);
  43399. lg += curvect.length();
  43400. }
  43401. shft = lg / nbSeg;
  43402. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  43403. for (i = 0; i < points.length - 1; i++) {
  43404. points[i + 1].subtractToRef(points[i], curvect);
  43405. nb = Math.floor(curvect.length() / shft);
  43406. curvect.normalize();
  43407. j = 0;
  43408. while (j < nb && p < positions.length) {
  43409. curshft = shft * j;
  43410. positions[p] = points[i].x + curshft * curvect.x;
  43411. positions[p + 1] = points[i].y + curshft * curvect.y;
  43412. positions[p + 2] = points[i].z + curshft * curvect.z;
  43413. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  43414. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  43415. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  43416. p += 6;
  43417. j++;
  43418. }
  43419. }
  43420. while (p < positions.length) {
  43421. positions[p] = points[i].x;
  43422. positions[p + 1] = points[i].y;
  43423. positions[p + 2] = points[i].z;
  43424. p += 3;
  43425. }
  43426. };
  43427. instance.updateMeshPositions(positionFunction, false);
  43428. return instance;
  43429. }
  43430. // dashed lines creation
  43431. var dashedLines = new BABYLON.LinesMesh(name, scene);
  43432. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  43433. vertexData.applyToMesh(dashedLines, options.updatable);
  43434. dashedLines.dashSize = dashSize;
  43435. dashedLines.gapSize = gapSize;
  43436. return dashedLines;
  43437. };
  43438. /**
  43439. * Creates an extruded shape mesh.
  43440. * 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.
  43441. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  43442. *
  43443. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  43444. * 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
  43445. * extruded along the Z axis.
  43446. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  43447. * 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.
  43448. * The parameter `scale` (float, default 1) is the value to scale the shape.
  43449. * 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
  43450. * 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
  43451. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  43452. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43453. * 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).
  43454. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43455. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  43456. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43457. */
  43458. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  43459. var path = options.path;
  43460. var shape = options.shape;
  43461. var scale = options.scale || 1;
  43462. var rotation = options.rotation || 0;
  43463. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  43464. var updatable = options.updatable;
  43465. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43466. var instance = options.instance;
  43467. var invertUV = options.invertUV || false;
  43468. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  43469. };
  43470. /**
  43471. * Creates an custom extruded shape mesh.
  43472. * 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.
  43473. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  43474. *
  43475. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  43476. * 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
  43477. * extruded along the Z axis.
  43478. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  43479. * 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
  43480. * and the distance of this point from the begining of the path :
  43481. * ```javascript
  43482. * var rotationFunction = function(i, distance) {
  43483. * // do things
  43484. * return rotationValue; }
  43485. * ```
  43486. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  43487. * 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
  43488. * and the distance of this point from the begining of the path :
  43489. * ```javascript
  43490. * var scaleFunction = function(i, distance) {
  43491. * // do things
  43492. * return scaleValue;}
  43493. * ```
  43494. * It must returns a float value that will be the scale value applied to the shape on each path point.
  43495. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  43496. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  43497. * 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
  43498. * 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
  43499. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  43500. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43501. * 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).
  43502. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43503. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  43504. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43505. */
  43506. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  43507. var path = options.path;
  43508. var shape = options.shape;
  43509. var scaleFunction = options.scaleFunction || (function () { return 1; });
  43510. var rotationFunction = options.rotationFunction || (function () { return 0; });
  43511. var ribbonCloseArray = options.ribbonCloseArray || false;
  43512. var ribbonClosePath = options.ribbonClosePath || false;
  43513. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  43514. var updatable = options.updatable;
  43515. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43516. var instance = options.instance;
  43517. var invertUV = options.invertUV || false;
  43518. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  43519. };
  43520. /**
  43521. * Creates lathe mesh.
  43522. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  43523. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  43524. *
  43525. * 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
  43526. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  43527. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  43528. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  43529. * 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.
  43530. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  43531. * 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
  43532. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43533. * 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).
  43534. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43535. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  43536. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43537. */
  43538. MeshBuilder.CreateLathe = function (name, options, scene) {
  43539. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  43540. var closed = (options.closed === undefined) ? true : options.closed;
  43541. var shape = options.shape;
  43542. var radius = options.radius || 1;
  43543. var tessellation = options.tessellation || 64;
  43544. var updatable = options.updatable;
  43545. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43546. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  43547. var pi2 = Math.PI * 2;
  43548. var paths = new Array();
  43549. var invertUV = options.invertUV || false;
  43550. var i = 0;
  43551. var p = 0;
  43552. var step = pi2 / tessellation * arc;
  43553. var rotated;
  43554. var path = new Array();
  43555. ;
  43556. for (i = 0; i <= tessellation; i++) {
  43557. var path = [];
  43558. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  43559. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  43560. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  43561. }
  43562. for (p = 0; p < shape.length; p++) {
  43563. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  43564. path.push(rotated);
  43565. }
  43566. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  43567. 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));
  43568. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  43569. }
  43570. paths.push(path);
  43571. }
  43572. // lathe ribbon
  43573. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  43574. return lathe;
  43575. };
  43576. /**
  43577. * Creates a plane mesh.
  43578. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  43579. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  43580. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  43581. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  43582. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43583. * 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).
  43584. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43585. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43586. */
  43587. MeshBuilder.CreatePlane = function (name, options, scene) {
  43588. var plane = new BABYLON.Mesh(name, scene);
  43589. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43590. plane.sideOrientation = options.sideOrientation;
  43591. var vertexData = BABYLON.VertexData.CreatePlane(options);
  43592. vertexData.applyToMesh(plane, options.updatable);
  43593. if (options.sourcePlane) {
  43594. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  43595. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  43596. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  43597. plane.rotate(vectorProduct, product);
  43598. }
  43599. return plane;
  43600. };
  43601. /**
  43602. * Creates a ground mesh.
  43603. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  43604. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  43605. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  43606. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43607. */
  43608. MeshBuilder.CreateGround = function (name, options, scene) {
  43609. var ground = new BABYLON.GroundMesh(name, scene);
  43610. ground._setReady(false);
  43611. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  43612. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  43613. ground._width = options.width || 1;
  43614. ground._height = options.height || 1;
  43615. ground._maxX = ground._width / 2;
  43616. ground._maxZ = ground._height / 2;
  43617. ground._minX = -ground._maxX;
  43618. ground._minZ = -ground._maxZ;
  43619. var vertexData = BABYLON.VertexData.CreateGround(options);
  43620. vertexData.applyToMesh(ground, options.updatable);
  43621. ground._setReady(true);
  43622. return ground;
  43623. };
  43624. /**
  43625. * Creates a tiled ground mesh.
  43626. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  43627. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  43628. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  43629. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  43630. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  43631. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  43632. * numbers of subdivisions on the ground width and height of each tile.
  43633. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43634. */
  43635. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  43636. var tiledGround = new BABYLON.Mesh(name, scene);
  43637. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  43638. vertexData.applyToMesh(tiledGround, options.updatable);
  43639. return tiledGround;
  43640. };
  43641. /**
  43642. * Creates a ground mesh from a height map.
  43643. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  43644. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  43645. * The parameter `url` sets the URL of the height map image resource.
  43646. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  43647. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  43648. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  43649. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  43650. * 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.
  43651. * 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).
  43652. * This function is passed the newly built mesh :
  43653. * ```javascript
  43654. * function(mesh) { // do things
  43655. * return; }
  43656. * ```
  43657. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43658. */
  43659. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  43660. var width = options.width || 10.0;
  43661. var height = options.height || 10.0;
  43662. var subdivisions = options.subdivisions || 1 | 0;
  43663. var minHeight = options.minHeight || 0.0;
  43664. var maxHeight = options.maxHeight || 10.0;
  43665. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  43666. var updatable = options.updatable;
  43667. var onReady = options.onReady;
  43668. var ground = new BABYLON.GroundMesh(name, scene);
  43669. ground._subdivisionsX = subdivisions;
  43670. ground._subdivisionsY = subdivisions;
  43671. ground._width = width;
  43672. ground._height = height;
  43673. ground._maxX = ground._width / 2.0;
  43674. ground._maxZ = ground._height / 2.0;
  43675. ground._minX = -ground._maxX;
  43676. ground._minZ = -ground._maxZ;
  43677. ground._setReady(false);
  43678. var onload = function (img) {
  43679. // Getting height map data
  43680. var canvas = document.createElement("canvas");
  43681. var context = canvas.getContext("2d");
  43682. var bufferWidth = img.width;
  43683. var bufferHeight = img.height;
  43684. canvas.width = bufferWidth;
  43685. canvas.height = bufferHeight;
  43686. context.drawImage(img, 0, 0);
  43687. // Create VertexData from map data
  43688. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  43689. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  43690. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  43691. width: width, height: height,
  43692. subdivisions: subdivisions,
  43693. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  43694. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  43695. });
  43696. vertexData.applyToMesh(ground, updatable);
  43697. ground._setReady(true);
  43698. //execute ready callback, if set
  43699. if (onReady) {
  43700. onReady(ground);
  43701. }
  43702. };
  43703. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  43704. return ground;
  43705. };
  43706. /**
  43707. * Creates a polygon mesh.
  43708. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  43709. * 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.
  43710. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43711. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43712. * 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).
  43713. * Remember you can only change the shape positions, not their number when updating a polygon.
  43714. */
  43715. MeshBuilder.CreatePolygon = function (name, options, scene) {
  43716. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43717. var shape = options.shape;
  43718. var holes = options.holes || [];
  43719. var depth = options.depth || 0;
  43720. var contours = [];
  43721. var hole = [];
  43722. for (var i = 0; i < shape.length; i++) {
  43723. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  43724. }
  43725. var epsilon = 0.00000001;
  43726. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  43727. contours.pop();
  43728. }
  43729. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  43730. for (var hNb = 0; hNb < holes.length; hNb++) {
  43731. hole = [];
  43732. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  43733. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  43734. }
  43735. polygonTriangulation.addHole(hole);
  43736. }
  43737. var polygon = polygonTriangulation.build(options.updatable, depth);
  43738. polygon.sideOrientation = options.sideOrientation;
  43739. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  43740. vertexData.applyToMesh(polygon, options.updatable);
  43741. return polygon;
  43742. };
  43743. ;
  43744. /**
  43745. * Creates an extruded polygon mesh, with depth in the Y direction.
  43746. * 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).
  43747. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  43748. */
  43749. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  43750. return MeshBuilder.CreatePolygon(name, options, scene);
  43751. };
  43752. ;
  43753. /**
  43754. * Creates a tube mesh.
  43755. * 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.
  43756. *
  43757. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  43758. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  43759. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  43760. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  43761. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  43762. * 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.
  43763. * It must return a radius value (positive float) :
  43764. * ```javascript
  43765. * var radiusFunction = function(i, distance) {
  43766. * // do things
  43767. * return radius; }
  43768. * ```
  43769. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  43770. * 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
  43771. * 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
  43772. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43773. * 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).
  43774. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43775. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  43776. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43777. */
  43778. MeshBuilder.CreateTube = function (name, options, scene) {
  43779. var path = options.path;
  43780. var radius = options.radius || 1.0;
  43781. var tessellation = options.tessellation || 64 | 0;
  43782. var radiusFunction = options.radiusFunction;
  43783. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  43784. var invertUV = options.invertUV || false;
  43785. var updatable = options.updatable;
  43786. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43787. var instance = options.instance;
  43788. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  43789. // tube geometry
  43790. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  43791. var tangents = path3D.getTangents();
  43792. var normals = path3D.getNormals();
  43793. var distances = path3D.getDistances();
  43794. var pi2 = Math.PI * 2;
  43795. var step = pi2 / tessellation * arc;
  43796. var returnRadius = function () { return radius; };
  43797. var radiusFunctionFinal = radiusFunction || returnRadius;
  43798. var circlePath;
  43799. var rad;
  43800. var normal;
  43801. var rotated;
  43802. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  43803. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  43804. for (var i = 0; i < path.length; i++) {
  43805. rad = radiusFunctionFinal(i, distances[i]); // current radius
  43806. circlePath = Array(); // current circle array
  43807. normal = normals[i]; // current normal
  43808. for (var t = 0; t < tessellation; t++) {
  43809. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  43810. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  43811. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  43812. rotated.scaleInPlace(rad).addInPlace(path[i]);
  43813. circlePath[t] = rotated;
  43814. }
  43815. circlePaths[index] = circlePath;
  43816. index++;
  43817. }
  43818. // cap
  43819. var capPath = function (nbPoints, pathIndex) {
  43820. var pointCap = Array();
  43821. for (var i = 0; i < nbPoints; i++) {
  43822. pointCap.push(path[pathIndex]);
  43823. }
  43824. return pointCap;
  43825. };
  43826. switch (cap) {
  43827. case BABYLON.Mesh.NO_CAP:
  43828. break;
  43829. case BABYLON.Mesh.CAP_START:
  43830. circlePaths[0] = capPath(tessellation, 0);
  43831. circlePaths[1] = circlePaths[2].slice(0);
  43832. break;
  43833. case BABYLON.Mesh.CAP_END:
  43834. circlePaths[index] = circlePaths[index - 1].slice(0);
  43835. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  43836. break;
  43837. case BABYLON.Mesh.CAP_ALL:
  43838. circlePaths[0] = capPath(tessellation, 0);
  43839. circlePaths[1] = circlePaths[2].slice(0);
  43840. circlePaths[index] = circlePaths[index - 1].slice(0);
  43841. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  43842. break;
  43843. default:
  43844. break;
  43845. }
  43846. return circlePaths;
  43847. };
  43848. var path3D;
  43849. var pathArray;
  43850. if (instance) {
  43851. var arc = options.arc || instance.arc;
  43852. path3D = (instance.path3D).update(path);
  43853. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  43854. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  43855. instance.path3D = path3D;
  43856. instance.pathArray = pathArray;
  43857. instance.arc = arc;
  43858. return instance;
  43859. }
  43860. // tube creation
  43861. path3D = new BABYLON.Path3D(path);
  43862. var newPathArray = new Array();
  43863. cap = (cap < 0 || cap > 3) ? 0 : cap;
  43864. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  43865. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  43866. tube.pathArray = pathArray;
  43867. tube.path3D = path3D;
  43868. tube.tessellation = tessellation;
  43869. tube.cap = cap;
  43870. tube.arc = options.arc;
  43871. return tube;
  43872. };
  43873. /**
  43874. * Creates a polyhedron mesh.
  43875. *
  43876. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  43877. * 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
  43878. * to choose the wanted type.
  43879. * The parameter `size` (positive float, default 1) sets the polygon size.
  43880. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  43881. * 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`.
  43882. * 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
  43883. * 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)`).
  43884. * 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
  43885. * 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.
  43886. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43887. * 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).
  43888. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43889. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43890. */
  43891. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  43892. var polyhedron = new BABYLON.Mesh(name, scene);
  43893. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43894. polyhedron.sideOrientation = options.sideOrientation;
  43895. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  43896. vertexData.applyToMesh(polyhedron, options.updatable);
  43897. return polyhedron;
  43898. };
  43899. /**
  43900. * Creates a decal mesh.
  43901. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  43902. * 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.
  43903. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  43904. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  43905. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  43906. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  43907. */
  43908. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  43909. var indices = sourceMesh.getIndices();
  43910. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  43911. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  43912. var position = options.position || BABYLON.Vector3.Zero();
  43913. var normal = options.normal || BABYLON.Vector3.Up();
  43914. var size = options.size || BABYLON.Vector3.One();
  43915. var angle = options.angle || 0;
  43916. // Getting correct rotation
  43917. if (!normal) {
  43918. var target = new BABYLON.Vector3(0, 0, 1);
  43919. var camera = sourceMesh.getScene().activeCamera;
  43920. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  43921. normal = camera.globalPosition.subtract(cameraWorldTarget);
  43922. }
  43923. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  43924. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  43925. var pitch = Math.atan2(normal.y, len);
  43926. // Matrix
  43927. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  43928. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  43929. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  43930. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  43931. var vertexData = new BABYLON.VertexData();
  43932. vertexData.indices = [];
  43933. vertexData.positions = [];
  43934. vertexData.normals = [];
  43935. vertexData.uvs = [];
  43936. var currentVertexDataIndex = 0;
  43937. var extractDecalVector3 = function (indexId) {
  43938. var vertexId = indices[indexId];
  43939. var result = new BABYLON.PositionNormalVertex();
  43940. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  43941. // Send vector to decal local world
  43942. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  43943. // Get normal
  43944. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  43945. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  43946. return result;
  43947. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  43948. var clip = function (vertices, axis) {
  43949. if (vertices.length === 0) {
  43950. return vertices;
  43951. }
  43952. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  43953. var clipVertices = function (v0, v1) {
  43954. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  43955. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  43956. };
  43957. var result = new Array();
  43958. for (var index = 0; index < vertices.length; index += 3) {
  43959. var v1Out;
  43960. var v2Out;
  43961. var v3Out;
  43962. var total = 0;
  43963. var nV1, nV2, nV3, nV4;
  43964. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  43965. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  43966. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  43967. v1Out = d1 > 0;
  43968. v2Out = d2 > 0;
  43969. v3Out = d3 > 0;
  43970. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  43971. switch (total) {
  43972. case 0:
  43973. result.push(vertices[index]);
  43974. result.push(vertices[index + 1]);
  43975. result.push(vertices[index + 2]);
  43976. break;
  43977. case 1:
  43978. if (v1Out) {
  43979. nV1 = vertices[index + 1];
  43980. nV2 = vertices[index + 2];
  43981. nV3 = clipVertices(vertices[index], nV1);
  43982. nV4 = clipVertices(vertices[index], nV2);
  43983. }
  43984. if (v2Out) {
  43985. nV1 = vertices[index];
  43986. nV2 = vertices[index + 2];
  43987. nV3 = clipVertices(vertices[index + 1], nV1);
  43988. nV4 = clipVertices(vertices[index + 1], nV2);
  43989. result.push(nV3);
  43990. result.push(nV2.clone());
  43991. result.push(nV1.clone());
  43992. result.push(nV2.clone());
  43993. result.push(nV3.clone());
  43994. result.push(nV4);
  43995. break;
  43996. }
  43997. if (v3Out) {
  43998. nV1 = vertices[index];
  43999. nV2 = vertices[index + 1];
  44000. nV3 = clipVertices(vertices[index + 2], nV1);
  44001. nV4 = clipVertices(vertices[index + 2], nV2);
  44002. }
  44003. result.push(nV1.clone());
  44004. result.push(nV2.clone());
  44005. result.push(nV3);
  44006. result.push(nV4);
  44007. result.push(nV3.clone());
  44008. result.push(nV2.clone());
  44009. break;
  44010. case 2:
  44011. if (!v1Out) {
  44012. nV1 = vertices[index].clone();
  44013. nV2 = clipVertices(nV1, vertices[index + 1]);
  44014. nV3 = clipVertices(nV1, vertices[index + 2]);
  44015. result.push(nV1);
  44016. result.push(nV2);
  44017. result.push(nV3);
  44018. }
  44019. if (!v2Out) {
  44020. nV1 = vertices[index + 1].clone();
  44021. nV2 = clipVertices(nV1, vertices[index + 2]);
  44022. nV3 = clipVertices(nV1, vertices[index]);
  44023. result.push(nV1);
  44024. result.push(nV2);
  44025. result.push(nV3);
  44026. }
  44027. if (!v3Out) {
  44028. nV1 = vertices[index + 2].clone();
  44029. nV2 = clipVertices(nV1, vertices[index]);
  44030. nV3 = clipVertices(nV1, vertices[index + 1]);
  44031. result.push(nV1);
  44032. result.push(nV2);
  44033. result.push(nV3);
  44034. }
  44035. break;
  44036. case 3:
  44037. break;
  44038. }
  44039. }
  44040. return result;
  44041. };
  44042. for (var index = 0; index < indices.length; index += 3) {
  44043. var faceVertices = new Array();
  44044. faceVertices.push(extractDecalVector3(index));
  44045. faceVertices.push(extractDecalVector3(index + 1));
  44046. faceVertices.push(extractDecalVector3(index + 2));
  44047. // Clip
  44048. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  44049. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  44050. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  44051. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  44052. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  44053. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  44054. if (faceVertices.length === 0) {
  44055. continue;
  44056. }
  44057. // Add UVs and get back to world
  44058. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  44059. var vertex = faceVertices[vIndex];
  44060. //TODO check for Int32Array | Uint32Array | Uint16Array
  44061. vertexData.indices.push(currentVertexDataIndex);
  44062. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  44063. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  44064. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  44065. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  44066. currentVertexDataIndex++;
  44067. }
  44068. }
  44069. // Return mesh
  44070. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  44071. vertexData.applyToMesh(decal);
  44072. decal.position = position.clone();
  44073. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  44074. return decal;
  44075. };
  44076. // Privates
  44077. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  44078. // extrusion geometry
  44079. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  44080. var tangents = path3D.getTangents();
  44081. var normals = path3D.getNormals();
  44082. var binormals = path3D.getBinormals();
  44083. var distances = path3D.getDistances();
  44084. var angle = 0;
  44085. var returnScale = function () { return scale; };
  44086. var returnRotation = function () { return rotation; };
  44087. var rotate = custom ? rotateFunction : returnRotation;
  44088. var scl = custom ? scaleFunction : returnScale;
  44089. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  44090. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  44091. for (var i = 0; i < curve.length; i++) {
  44092. var shapePath = new Array();
  44093. var angleStep = rotate(i, distances[i]);
  44094. var scaleRatio = scl(i, distances[i]);
  44095. for (var p = 0; p < shape.length; p++) {
  44096. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  44097. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  44098. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  44099. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  44100. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  44101. shapePath[p] = rotated;
  44102. }
  44103. shapePaths[index] = shapePath;
  44104. angle += angleStep;
  44105. index++;
  44106. }
  44107. // cap
  44108. var capPath = function (shapePath) {
  44109. var pointCap = Array();
  44110. var barycenter = BABYLON.Vector3.Zero();
  44111. var i;
  44112. for (i = 0; i < shapePath.length; i++) {
  44113. barycenter.addInPlace(shapePath[i]);
  44114. }
  44115. barycenter.scaleInPlace(1.0 / shapePath.length);
  44116. for (i = 0; i < shapePath.length; i++) {
  44117. pointCap.push(barycenter);
  44118. }
  44119. return pointCap;
  44120. };
  44121. switch (cap) {
  44122. case BABYLON.Mesh.NO_CAP:
  44123. break;
  44124. case BABYLON.Mesh.CAP_START:
  44125. shapePaths[0] = capPath(shapePaths[2]);
  44126. shapePaths[1] = shapePaths[2];
  44127. break;
  44128. case BABYLON.Mesh.CAP_END:
  44129. shapePaths[index] = shapePaths[index - 1];
  44130. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  44131. break;
  44132. case BABYLON.Mesh.CAP_ALL:
  44133. shapePaths[0] = capPath(shapePaths[2]);
  44134. shapePaths[1] = shapePaths[2];
  44135. shapePaths[index] = shapePaths[index - 1];
  44136. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  44137. break;
  44138. default:
  44139. break;
  44140. }
  44141. return shapePaths;
  44142. };
  44143. var path3D;
  44144. var pathArray;
  44145. if (instance) {
  44146. path3D = (instance.path3D).update(curve);
  44147. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  44148. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  44149. return instance;
  44150. }
  44151. // extruded shape creation
  44152. path3D = new BABYLON.Path3D(curve);
  44153. var newShapePaths = new Array();
  44154. cap = (cap < 0 || cap > 3) ? 0 : cap;
  44155. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  44156. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs, backUVs: backUVs }, scene);
  44157. extrudedGeneric.pathArray = pathArray;
  44158. extrudedGeneric.path3D = path3D;
  44159. extrudedGeneric.cap = cap;
  44160. return extrudedGeneric;
  44161. };
  44162. return MeshBuilder;
  44163. }());
  44164. BABYLON.MeshBuilder = MeshBuilder;
  44165. })(BABYLON || (BABYLON = {}));
  44166. //# sourceMappingURL=babylon.meshBuilder.js.map
  44167. var BABYLON;
  44168. (function (BABYLON) {
  44169. var AudioEngine = (function () {
  44170. function AudioEngine() {
  44171. this._audioContext = null;
  44172. this._audioContextInitialized = false;
  44173. this.canUseWebAudio = false;
  44174. this.WarnedWebAudioUnsupported = false;
  44175. this.unlocked = false;
  44176. this.isMP3supported = false;
  44177. this.isOGGsupported = false;
  44178. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  44179. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  44180. this.canUseWebAudio = true;
  44181. }
  44182. var audioElem = document.createElement('audio');
  44183. try {
  44184. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  44185. this.isMP3supported = true;
  44186. }
  44187. }
  44188. catch (e) {
  44189. // protect error during capability check.
  44190. }
  44191. try {
  44192. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  44193. this.isOGGsupported = true;
  44194. }
  44195. }
  44196. catch (e) {
  44197. // protect error during capability check.
  44198. }
  44199. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  44200. this._unlockiOSaudio();
  44201. }
  44202. else {
  44203. this.unlocked = true;
  44204. }
  44205. }
  44206. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  44207. get: function () {
  44208. if (!this._audioContextInitialized) {
  44209. this._initializeAudioContext();
  44210. }
  44211. return this._audioContext;
  44212. },
  44213. enumerable: true,
  44214. configurable: true
  44215. });
  44216. AudioEngine.prototype._unlockiOSaudio = function () {
  44217. var _this = this;
  44218. var unlockaudio = function () {
  44219. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  44220. var source = _this.audioContext.createBufferSource();
  44221. source.buffer = buffer;
  44222. source.connect(_this.audioContext.destination);
  44223. source.start(0);
  44224. setTimeout(function () {
  44225. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  44226. _this.unlocked = true;
  44227. window.removeEventListener('touchend', unlockaudio, false);
  44228. if (_this.onAudioUnlocked) {
  44229. _this.onAudioUnlocked();
  44230. }
  44231. }
  44232. }, 0);
  44233. };
  44234. window.addEventListener('touchend', unlockaudio, false);
  44235. };
  44236. AudioEngine.prototype._initializeAudioContext = function () {
  44237. try {
  44238. if (this.canUseWebAudio) {
  44239. this._audioContext = new AudioContext();
  44240. // create a global volume gain node
  44241. this.masterGain = this._audioContext.createGain();
  44242. this.masterGain.gain.value = 1;
  44243. this.masterGain.connect(this._audioContext.destination);
  44244. this._audioContextInitialized = true;
  44245. }
  44246. }
  44247. catch (e) {
  44248. this.canUseWebAudio = false;
  44249. BABYLON.Tools.Error("Web Audio: " + e.message);
  44250. }
  44251. };
  44252. AudioEngine.prototype.dispose = function () {
  44253. if (this.canUseWebAudio && this._audioContextInitialized) {
  44254. if (this._connectedAnalyser) {
  44255. this._connectedAnalyser.stopDebugCanvas();
  44256. this._connectedAnalyser.dispose();
  44257. this.masterGain.disconnect();
  44258. this.masterGain.connect(this._audioContext.destination);
  44259. this._connectedAnalyser = null;
  44260. }
  44261. this.masterGain.gain.value = 1;
  44262. }
  44263. this.WarnedWebAudioUnsupported = false;
  44264. };
  44265. AudioEngine.prototype.getGlobalVolume = function () {
  44266. if (this.canUseWebAudio && this._audioContextInitialized) {
  44267. return this.masterGain.gain.value;
  44268. }
  44269. else {
  44270. return -1;
  44271. }
  44272. };
  44273. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  44274. if (this.canUseWebAudio && this._audioContextInitialized) {
  44275. this.masterGain.gain.value = newVolume;
  44276. }
  44277. };
  44278. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  44279. if (this._connectedAnalyser) {
  44280. this._connectedAnalyser.stopDebugCanvas();
  44281. }
  44282. if (this.canUseWebAudio && this._audioContextInitialized) {
  44283. this._connectedAnalyser = analyser;
  44284. this.masterGain.disconnect();
  44285. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  44286. }
  44287. };
  44288. return AudioEngine;
  44289. }());
  44290. BABYLON.AudioEngine = AudioEngine;
  44291. })(BABYLON || (BABYLON = {}));
  44292. //# sourceMappingURL=babylon.audioEngine.js.map
  44293. var BABYLON;
  44294. (function (BABYLON) {
  44295. var Sound = (function () {
  44296. /**
  44297. * Create a sound and attach it to a scene
  44298. * @param name Name of your sound
  44299. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  44300. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  44301. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  44302. */
  44303. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  44304. var _this = this;
  44305. this.autoplay = false;
  44306. this.loop = false;
  44307. this.useCustomAttenuation = false;
  44308. this.spatialSound = false;
  44309. this.refDistance = 1;
  44310. this.rolloffFactor = 1;
  44311. this.maxDistance = 100;
  44312. this.distanceModel = "linear";
  44313. this._panningModel = "equalpower";
  44314. this._playbackRate = 1;
  44315. this._streaming = false;
  44316. this._startTime = 0;
  44317. this._startOffset = 0;
  44318. this._position = BABYLON.Vector3.Zero();
  44319. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  44320. this._volume = 1;
  44321. this._isLoaded = false;
  44322. this._isReadyToPlay = false;
  44323. this.isPlaying = false;
  44324. this.isPaused = false;
  44325. this._isDirectional = false;
  44326. // Used if you'd like to create a directional sound.
  44327. // If not set, the sound will be omnidirectional
  44328. this._coneInnerAngle = 360;
  44329. this._coneOuterAngle = 360;
  44330. this._coneOuterGain = 0;
  44331. this._isOutputConnected = false;
  44332. this._urlType = "Unknown";
  44333. this.name = name;
  44334. this._scene = scene;
  44335. this._readyToPlayCallback = readyToPlayCallback;
  44336. // Default custom attenuation function is a linear attenuation
  44337. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  44338. if (currentDistance < maxDistance) {
  44339. return currentVolume * (1 - currentDistance / maxDistance);
  44340. }
  44341. else {
  44342. return 0;
  44343. }
  44344. };
  44345. if (options) {
  44346. this.autoplay = options.autoplay || false;
  44347. this.loop = options.loop || false;
  44348. // if volume === 0, we need another way to check this option
  44349. if (options.volume !== undefined) {
  44350. this._volume = options.volume;
  44351. }
  44352. this.spatialSound = options.spatialSound || false;
  44353. this.maxDistance = options.maxDistance || 100;
  44354. this.useCustomAttenuation = options.useCustomAttenuation || false;
  44355. this.rolloffFactor = options.rolloffFactor || 1;
  44356. this.refDistance = options.refDistance || 1;
  44357. this.distanceModel = options.distanceModel || "linear";
  44358. this._playbackRate = options.playbackRate || 1;
  44359. this._streaming = options.streaming || false;
  44360. }
  44361. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44362. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  44363. this._soundGain.gain.value = this._volume;
  44364. this._inputAudioNode = this._soundGain;
  44365. this._ouputAudioNode = this._soundGain;
  44366. if (this.spatialSound) {
  44367. this._createSpatialParameters();
  44368. }
  44369. this._scene.mainSoundTrack.AddSound(this);
  44370. var validParameter = true;
  44371. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  44372. if (urlOrArrayBuffer) {
  44373. if (typeof (urlOrArrayBuffer) === "string")
  44374. this._urlType = "String";
  44375. if (Array.isArray(urlOrArrayBuffer))
  44376. this._urlType = "Array";
  44377. if (urlOrArrayBuffer instanceof ArrayBuffer)
  44378. this._urlType = "ArrayBuffer";
  44379. var urls = [];
  44380. var codecSupportedFound = false;
  44381. switch (this._urlType) {
  44382. case "ArrayBuffer":
  44383. if (urlOrArrayBuffer.byteLength > 0) {
  44384. codecSupportedFound = true;
  44385. this._soundLoaded(urlOrArrayBuffer);
  44386. }
  44387. break;
  44388. case "String":
  44389. urls.push(urlOrArrayBuffer);
  44390. case "Array":
  44391. if (urls.length === 0)
  44392. urls = urlOrArrayBuffer;
  44393. // If we found a supported format, we load it immediately and stop the loop
  44394. for (var i = 0; i < urls.length; i++) {
  44395. var url = urls[i];
  44396. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  44397. codecSupportedFound = true;
  44398. }
  44399. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  44400. codecSupportedFound = true;
  44401. }
  44402. if (url.indexOf(".wav", url.length - 4) !== -1) {
  44403. codecSupportedFound = true;
  44404. }
  44405. if (url.indexOf("blob:") !== -1) {
  44406. codecSupportedFound = true;
  44407. }
  44408. if (codecSupportedFound) {
  44409. // Loading sound using XHR2
  44410. if (!this._streaming) {
  44411. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  44412. }
  44413. else {
  44414. this._htmlAudioElement = new Audio(url);
  44415. this._htmlAudioElement.controls = false;
  44416. this._htmlAudioElement.loop = this.loop;
  44417. this._htmlAudioElement.crossOrigin = "anonymous";
  44418. this._htmlAudioElement.preload = "auto";
  44419. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  44420. _this._isReadyToPlay = true;
  44421. if (_this.autoplay) {
  44422. _this.play();
  44423. }
  44424. if (_this._readyToPlayCallback) {
  44425. _this._readyToPlayCallback();
  44426. }
  44427. });
  44428. document.body.appendChild(this._htmlAudioElement);
  44429. }
  44430. break;
  44431. }
  44432. }
  44433. break;
  44434. default:
  44435. validParameter = false;
  44436. break;
  44437. }
  44438. if (!validParameter) {
  44439. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  44440. }
  44441. else {
  44442. if (!codecSupportedFound) {
  44443. this._isReadyToPlay = true;
  44444. // Simulating a ready to play event to avoid breaking code path
  44445. if (this._readyToPlayCallback) {
  44446. window.setTimeout(function () {
  44447. _this._readyToPlayCallback();
  44448. }, 1000);
  44449. }
  44450. }
  44451. }
  44452. }
  44453. }
  44454. else {
  44455. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  44456. this._scene.mainSoundTrack.AddSound(this);
  44457. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  44458. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  44459. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  44460. }
  44461. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  44462. if (this._readyToPlayCallback) {
  44463. window.setTimeout(function () {
  44464. _this._readyToPlayCallback();
  44465. }, 1000);
  44466. }
  44467. }
  44468. }
  44469. Sound.prototype.dispose = function () {
  44470. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  44471. if (this.isPlaying) {
  44472. this.stop();
  44473. }
  44474. this._isReadyToPlay = false;
  44475. if (this.soundTrackId === -1) {
  44476. this._scene.mainSoundTrack.RemoveSound(this);
  44477. }
  44478. else {
  44479. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  44480. }
  44481. if (this._soundGain) {
  44482. this._soundGain.disconnect();
  44483. this._soundGain = null;
  44484. }
  44485. if (this._soundPanner) {
  44486. this._soundPanner.disconnect();
  44487. this._soundPanner = null;
  44488. }
  44489. if (this._soundSource) {
  44490. this._soundSource.disconnect();
  44491. this._soundSource = null;
  44492. }
  44493. this._audioBuffer = null;
  44494. if (this._htmlAudioElement) {
  44495. this._htmlAudioElement.pause();
  44496. this._htmlAudioElement.src = "";
  44497. document.body.removeChild(this._htmlAudioElement);
  44498. }
  44499. if (this._connectedMesh) {
  44500. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  44501. this._connectedMesh = null;
  44502. }
  44503. }
  44504. };
  44505. Sound.prototype.isReady = function () {
  44506. return this._isReadyToPlay;
  44507. };
  44508. Sound.prototype._soundLoaded = function (audioData) {
  44509. var _this = this;
  44510. this._isLoaded = true;
  44511. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  44512. _this._audioBuffer = buffer;
  44513. _this._isReadyToPlay = true;
  44514. if (_this.autoplay) {
  44515. _this.play();
  44516. }
  44517. if (_this._readyToPlayCallback) {
  44518. _this._readyToPlayCallback();
  44519. }
  44520. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  44521. };
  44522. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  44523. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44524. this._audioBuffer = audioBuffer;
  44525. this._isReadyToPlay = true;
  44526. }
  44527. };
  44528. Sound.prototype.updateOptions = function (options) {
  44529. if (options) {
  44530. this.loop = options.loop || this.loop;
  44531. this.maxDistance = options.maxDistance || this.maxDistance;
  44532. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  44533. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  44534. this.refDistance = options.refDistance || this.refDistance;
  44535. this.distanceModel = options.distanceModel || this.distanceModel;
  44536. this._playbackRate = options.playbackRate || this._playbackRate;
  44537. this._updateSpatialParameters();
  44538. if (this.isPlaying) {
  44539. if (this._streaming) {
  44540. this._htmlAudioElement.playbackRate = this._playbackRate;
  44541. }
  44542. else {
  44543. this._soundSource.playbackRate.value = this._playbackRate;
  44544. }
  44545. }
  44546. }
  44547. };
  44548. Sound.prototype._createSpatialParameters = function () {
  44549. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44550. if (this._scene.headphone) {
  44551. this._panningModel = "HRTF";
  44552. }
  44553. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  44554. this._updateSpatialParameters();
  44555. this._soundPanner.connect(this._ouputAudioNode);
  44556. this._inputAudioNode = this._soundPanner;
  44557. }
  44558. };
  44559. Sound.prototype._updateSpatialParameters = function () {
  44560. if (this.spatialSound) {
  44561. if (this.useCustomAttenuation) {
  44562. // Tricks to disable in a way embedded Web Audio attenuation
  44563. this._soundPanner.distanceModel = "linear";
  44564. this._soundPanner.maxDistance = Number.MAX_VALUE;
  44565. this._soundPanner.refDistance = 1;
  44566. this._soundPanner.rolloffFactor = 1;
  44567. this._soundPanner.panningModel = this._panningModel;
  44568. }
  44569. else {
  44570. this._soundPanner.distanceModel = this.distanceModel;
  44571. this._soundPanner.maxDistance = this.maxDistance;
  44572. this._soundPanner.refDistance = this.refDistance;
  44573. this._soundPanner.rolloffFactor = this.rolloffFactor;
  44574. this._soundPanner.panningModel = this._panningModel;
  44575. }
  44576. }
  44577. };
  44578. Sound.prototype.switchPanningModelToHRTF = function () {
  44579. this._panningModel = "HRTF";
  44580. this._switchPanningModel();
  44581. };
  44582. Sound.prototype.switchPanningModelToEqualPower = function () {
  44583. this._panningModel = "equalpower";
  44584. this._switchPanningModel();
  44585. };
  44586. Sound.prototype._switchPanningModel = function () {
  44587. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  44588. this._soundPanner.panningModel = this._panningModel;
  44589. }
  44590. };
  44591. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  44592. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44593. if (this._isOutputConnected) {
  44594. this._ouputAudioNode.disconnect();
  44595. }
  44596. this._ouputAudioNode.connect(soundTrackAudioNode);
  44597. this._isOutputConnected = true;
  44598. }
  44599. };
  44600. /**
  44601. * Transform this sound into a directional source
  44602. * @param coneInnerAngle Size of the inner cone in degree
  44603. * @param coneOuterAngle Size of the outer cone in degree
  44604. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  44605. */
  44606. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  44607. if (coneOuterAngle < coneInnerAngle) {
  44608. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  44609. return;
  44610. }
  44611. this._coneInnerAngle = coneInnerAngle;
  44612. this._coneOuterAngle = coneOuterAngle;
  44613. this._coneOuterGain = coneOuterGain;
  44614. this._isDirectional = true;
  44615. if (this.isPlaying && this.loop) {
  44616. this.stop();
  44617. this.play();
  44618. }
  44619. };
  44620. Sound.prototype.setPosition = function (newPosition) {
  44621. this._position = newPosition;
  44622. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  44623. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  44624. }
  44625. };
  44626. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  44627. this._localDirection = newLocalDirection;
  44628. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  44629. this._updateDirection();
  44630. }
  44631. };
  44632. Sound.prototype._updateDirection = function () {
  44633. var mat = this._connectedMesh.getWorldMatrix();
  44634. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  44635. direction.normalize();
  44636. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  44637. };
  44638. Sound.prototype.updateDistanceFromListener = function () {
  44639. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  44640. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  44641. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  44642. }
  44643. };
  44644. Sound.prototype.setAttenuationFunction = function (callback) {
  44645. this._customAttenuationFunction = callback;
  44646. };
  44647. /**
  44648. * Play the sound
  44649. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  44650. * @param offset (optional) Start the sound setting it at a specific time
  44651. */
  44652. Sound.prototype.play = function (time, offset) {
  44653. var _this = this;
  44654. if (this._isReadyToPlay && this._scene.audioEnabled) {
  44655. try {
  44656. if (this._startOffset < 0) {
  44657. time = -this._startOffset;
  44658. this._startOffset = 0;
  44659. }
  44660. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  44661. if (!this._soundSource || !this._streamingSource) {
  44662. if (this.spatialSound) {
  44663. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  44664. if (this._isDirectional) {
  44665. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  44666. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  44667. this._soundPanner.coneOuterGain = this._coneOuterGain;
  44668. if (this._connectedMesh) {
  44669. this._updateDirection();
  44670. }
  44671. else {
  44672. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  44673. }
  44674. }
  44675. }
  44676. }
  44677. if (this._streaming) {
  44678. if (!this._streamingSource) {
  44679. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  44680. this._htmlAudioElement.onended = function () { _this._onended(); };
  44681. this._htmlAudioElement.playbackRate = this._playbackRate;
  44682. }
  44683. this._streamingSource.disconnect();
  44684. this._streamingSource.connect(this._inputAudioNode);
  44685. this._htmlAudioElement.play();
  44686. }
  44687. else {
  44688. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  44689. this._soundSource.buffer = this._audioBuffer;
  44690. this._soundSource.connect(this._inputAudioNode);
  44691. this._soundSource.loop = this.loop;
  44692. this._soundSource.playbackRate.value = this._playbackRate;
  44693. this._soundSource.onended = function () { _this._onended(); };
  44694. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  44695. }
  44696. this._startTime = startTime;
  44697. this.isPlaying = true;
  44698. this.isPaused = false;
  44699. }
  44700. catch (ex) {
  44701. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  44702. }
  44703. }
  44704. };
  44705. Sound.prototype._onended = function () {
  44706. this.isPlaying = false;
  44707. if (this.onended) {
  44708. this.onended();
  44709. }
  44710. };
  44711. /**
  44712. * Stop the sound
  44713. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  44714. */
  44715. Sound.prototype.stop = function (time) {
  44716. if (this.isPlaying) {
  44717. if (this._streaming) {
  44718. this._htmlAudioElement.pause();
  44719. // Test needed for Firefox or it will generate an Invalid State Error
  44720. if (this._htmlAudioElement.currentTime > 0) {
  44721. this._htmlAudioElement.currentTime = 0;
  44722. }
  44723. }
  44724. else {
  44725. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  44726. this._soundSource.stop(stopTime);
  44727. this._soundSource.onended = null;
  44728. if (!this.isPaused) {
  44729. this._startOffset = 0;
  44730. }
  44731. }
  44732. this.isPlaying = false;
  44733. }
  44734. };
  44735. Sound.prototype.pause = function () {
  44736. if (this.isPlaying) {
  44737. this.isPaused = true;
  44738. if (this._streaming) {
  44739. this._htmlAudioElement.pause();
  44740. }
  44741. else {
  44742. this.stop(0);
  44743. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  44744. }
  44745. }
  44746. };
  44747. Sound.prototype.setVolume = function (newVolume, time) {
  44748. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44749. if (time) {
  44750. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  44751. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  44752. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  44753. }
  44754. else {
  44755. this._soundGain.gain.value = newVolume;
  44756. }
  44757. }
  44758. this._volume = newVolume;
  44759. };
  44760. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  44761. this._playbackRate = newPlaybackRate;
  44762. if (this.isPlaying) {
  44763. if (this._streaming) {
  44764. this._htmlAudioElement.playbackRate = this._playbackRate;
  44765. }
  44766. else {
  44767. this._soundSource.playbackRate.value = this._playbackRate;
  44768. }
  44769. }
  44770. };
  44771. Sound.prototype.getVolume = function () {
  44772. return this._volume;
  44773. };
  44774. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  44775. var _this = this;
  44776. if (this._connectedMesh) {
  44777. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  44778. this._registerFunc = null;
  44779. }
  44780. this._connectedMesh = meshToConnectTo;
  44781. if (!this.spatialSound) {
  44782. this.spatialSound = true;
  44783. this._createSpatialParameters();
  44784. if (this.isPlaying && this.loop) {
  44785. this.stop();
  44786. this.play();
  44787. }
  44788. }
  44789. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  44790. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  44791. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  44792. };
  44793. Sound.prototype.detachFromMesh = function () {
  44794. if (this._connectedMesh) {
  44795. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  44796. this._registerFunc = null;
  44797. this._connectedMesh = null;
  44798. }
  44799. };
  44800. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  44801. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  44802. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  44803. this._updateDirection();
  44804. }
  44805. };
  44806. Sound.prototype.clone = function () {
  44807. var _this = this;
  44808. if (!this._streaming) {
  44809. var setBufferAndRun = function () {
  44810. if (_this._isReadyToPlay) {
  44811. clonedSound._audioBuffer = _this.getAudioBuffer();
  44812. clonedSound._isReadyToPlay = true;
  44813. if (clonedSound.autoplay) {
  44814. clonedSound.play();
  44815. }
  44816. }
  44817. else {
  44818. window.setTimeout(setBufferAndRun, 300);
  44819. }
  44820. };
  44821. var currentOptions = {
  44822. autoplay: this.autoplay, loop: this.loop,
  44823. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  44824. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  44825. refDistance: this.refDistance, distanceModel: this.distanceModel
  44826. };
  44827. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  44828. if (this.useCustomAttenuation) {
  44829. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  44830. }
  44831. clonedSound.setPosition(this._position);
  44832. clonedSound.setPlaybackRate(this._playbackRate);
  44833. setBufferAndRun();
  44834. return clonedSound;
  44835. }
  44836. else {
  44837. return null;
  44838. }
  44839. };
  44840. Sound.prototype.getAudioBuffer = function () {
  44841. return this._audioBuffer;
  44842. };
  44843. Sound.prototype.serialize = function () {
  44844. var serializationObject = {
  44845. name: this.name,
  44846. url: this.name,
  44847. autoplay: this.autoplay,
  44848. loop: this.loop,
  44849. volume: this._volume,
  44850. spatialSound: this.spatialSound,
  44851. maxDistance: this.maxDistance,
  44852. rolloffFactor: this.rolloffFactor,
  44853. refDistance: this.refDistance,
  44854. distanceModel: this.distanceModel,
  44855. playbackRate: this._playbackRate,
  44856. panningModel: this._panningModel,
  44857. soundTrackId: this.soundTrackId
  44858. };
  44859. if (this.spatialSound) {
  44860. if (this._connectedMesh)
  44861. serializationObject.connectedMeshId = this._connectedMesh.id;
  44862. serializationObject.position = this._position.asArray();
  44863. serializationObject.refDistance = this.refDistance;
  44864. serializationObject.distanceModel = this.distanceModel;
  44865. serializationObject.isDirectional = this._isDirectional;
  44866. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  44867. serializationObject.coneInnerAngle = this._coneInnerAngle;
  44868. serializationObject.coneOuterAngle = this._coneOuterAngle;
  44869. serializationObject.coneOuterGain = this._coneOuterGain;
  44870. }
  44871. return serializationObject;
  44872. };
  44873. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  44874. var soundName = parsedSound.name;
  44875. var soundUrl;
  44876. if (parsedSound.url) {
  44877. soundUrl = rootUrl + parsedSound.url;
  44878. }
  44879. else {
  44880. soundUrl = rootUrl + soundName;
  44881. }
  44882. var options = {
  44883. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  44884. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  44885. rolloffFactor: parsedSound.rolloffFactor,
  44886. refDistance: parsedSound.refDistance,
  44887. distanceModel: parsedSound.distanceModel,
  44888. playbackRate: parsedSound.playbackRate
  44889. };
  44890. var newSound;
  44891. if (!sourceSound) {
  44892. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  44893. scene._addPendingData(newSound);
  44894. }
  44895. else {
  44896. var setBufferAndRun = function () {
  44897. if (sourceSound._isReadyToPlay) {
  44898. newSound._audioBuffer = sourceSound.getAudioBuffer();
  44899. newSound._isReadyToPlay = true;
  44900. if (newSound.autoplay) {
  44901. newSound.play();
  44902. }
  44903. }
  44904. else {
  44905. window.setTimeout(setBufferAndRun, 300);
  44906. }
  44907. };
  44908. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  44909. setBufferAndRun();
  44910. }
  44911. if (parsedSound.position) {
  44912. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  44913. newSound.setPosition(soundPosition);
  44914. }
  44915. if (parsedSound.isDirectional) {
  44916. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  44917. if (parsedSound.localDirectionToMesh) {
  44918. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  44919. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  44920. }
  44921. }
  44922. if (parsedSound.connectedMeshId) {
  44923. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  44924. if (connectedMesh) {
  44925. newSound.attachToMesh(connectedMesh);
  44926. }
  44927. }
  44928. return newSound;
  44929. };
  44930. return Sound;
  44931. }());
  44932. BABYLON.Sound = Sound;
  44933. })(BABYLON || (BABYLON = {}));
  44934. //# sourceMappingURL=babylon.sound.js.map
  44935. var BABYLON;
  44936. (function (BABYLON) {
  44937. var SoundTrack = (function () {
  44938. function SoundTrack(scene, options) {
  44939. this.id = -1;
  44940. this._isMainTrack = false;
  44941. this._isInitialized = false;
  44942. this._scene = scene;
  44943. this.soundCollection = new Array();
  44944. this._options = options;
  44945. if (!this._isMainTrack) {
  44946. this._scene.soundTracks.push(this);
  44947. this.id = this._scene.soundTracks.length - 1;
  44948. }
  44949. }
  44950. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  44951. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44952. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  44953. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  44954. if (this._options) {
  44955. if (this._options.volume) {
  44956. this._outputAudioNode.gain.value = this._options.volume;
  44957. }
  44958. if (this._options.mainTrack) {
  44959. this._isMainTrack = this._options.mainTrack;
  44960. }
  44961. }
  44962. this._isInitialized = true;
  44963. }
  44964. };
  44965. SoundTrack.prototype.dispose = function () {
  44966. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44967. if (this._connectedAnalyser) {
  44968. this._connectedAnalyser.stopDebugCanvas();
  44969. }
  44970. while (this.soundCollection.length) {
  44971. this.soundCollection[0].dispose();
  44972. }
  44973. if (this._outputAudioNode) {
  44974. this._outputAudioNode.disconnect();
  44975. }
  44976. this._outputAudioNode = null;
  44977. }
  44978. };
  44979. SoundTrack.prototype.AddSound = function (sound) {
  44980. if (!this._isInitialized) {
  44981. this._initializeSoundTrackAudioGraph();
  44982. }
  44983. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44984. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  44985. }
  44986. if (sound.soundTrackId) {
  44987. if (sound.soundTrackId === -1) {
  44988. this._scene.mainSoundTrack.RemoveSound(sound);
  44989. }
  44990. else {
  44991. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  44992. }
  44993. }
  44994. this.soundCollection.push(sound);
  44995. sound.soundTrackId = this.id;
  44996. };
  44997. SoundTrack.prototype.RemoveSound = function (sound) {
  44998. var index = this.soundCollection.indexOf(sound);
  44999. if (index !== -1) {
  45000. this.soundCollection.splice(index, 1);
  45001. }
  45002. };
  45003. SoundTrack.prototype.setVolume = function (newVolume) {
  45004. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45005. this._outputAudioNode.gain.value = newVolume;
  45006. }
  45007. };
  45008. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  45009. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45010. for (var i = 0; i < this.soundCollection.length; i++) {
  45011. this.soundCollection[i].switchPanningModelToHRTF();
  45012. }
  45013. }
  45014. };
  45015. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  45016. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45017. for (var i = 0; i < this.soundCollection.length; i++) {
  45018. this.soundCollection[i].switchPanningModelToEqualPower();
  45019. }
  45020. }
  45021. };
  45022. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  45023. if (this._connectedAnalyser) {
  45024. this._connectedAnalyser.stopDebugCanvas();
  45025. }
  45026. this._connectedAnalyser = analyser;
  45027. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45028. this._outputAudioNode.disconnect();
  45029. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  45030. }
  45031. };
  45032. return SoundTrack;
  45033. }());
  45034. BABYLON.SoundTrack = SoundTrack;
  45035. })(BABYLON || (BABYLON = {}));
  45036. //# sourceMappingURL=babylon.soundtrack.js.map
  45037. var BABYLON;
  45038. (function (BABYLON) {
  45039. var Analyser = (function () {
  45040. function Analyser(scene) {
  45041. this.SMOOTHING = 0.75;
  45042. this.FFT_SIZE = 512;
  45043. this.BARGRAPHAMPLITUDE = 256;
  45044. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  45045. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  45046. this._scene = scene;
  45047. this._audioEngine = BABYLON.Engine.audioEngine;
  45048. if (this._audioEngine.canUseWebAudio) {
  45049. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  45050. this._webAudioAnalyser.minDecibels = -140;
  45051. this._webAudioAnalyser.maxDecibels = 0;
  45052. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  45053. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  45054. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  45055. }
  45056. }
  45057. Analyser.prototype.getFrequencyBinCount = function () {
  45058. if (this._audioEngine.canUseWebAudio) {
  45059. return this._webAudioAnalyser.frequencyBinCount;
  45060. }
  45061. else {
  45062. return 0;
  45063. }
  45064. };
  45065. Analyser.prototype.getByteFrequencyData = function () {
  45066. if (this._audioEngine.canUseWebAudio) {
  45067. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  45068. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  45069. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  45070. }
  45071. return this._byteFreqs;
  45072. };
  45073. Analyser.prototype.getByteTimeDomainData = function () {
  45074. if (this._audioEngine.canUseWebAudio) {
  45075. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  45076. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  45077. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  45078. }
  45079. return this._byteTime;
  45080. };
  45081. Analyser.prototype.getFloatFrequencyData = function () {
  45082. if (this._audioEngine.canUseWebAudio) {
  45083. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  45084. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  45085. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  45086. }
  45087. return this._floatFreqs;
  45088. };
  45089. Analyser.prototype.drawDebugCanvas = function () {
  45090. var _this = this;
  45091. if (this._audioEngine.canUseWebAudio) {
  45092. if (!this._debugCanvas) {
  45093. this._debugCanvas = document.createElement("canvas");
  45094. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  45095. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  45096. this._debugCanvas.style.position = "absolute";
  45097. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  45098. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  45099. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  45100. document.body.appendChild(this._debugCanvas);
  45101. this._registerFunc = function () {
  45102. _this.drawDebugCanvas();
  45103. };
  45104. this._scene.registerBeforeRender(this._registerFunc);
  45105. }
  45106. if (this._registerFunc) {
  45107. var workingArray = this.getByteFrequencyData();
  45108. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  45109. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  45110. // Draw the frequency domain chart.
  45111. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  45112. var value = workingArray[i];
  45113. var percent = value / this.BARGRAPHAMPLITUDE;
  45114. var height = this.DEBUGCANVASSIZE.height * percent;
  45115. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  45116. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  45117. var hue = i / this.getFrequencyBinCount() * 360;
  45118. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  45119. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  45120. }
  45121. }
  45122. }
  45123. };
  45124. Analyser.prototype.stopDebugCanvas = function () {
  45125. if (this._debugCanvas) {
  45126. this._scene.unregisterBeforeRender(this._registerFunc);
  45127. this._registerFunc = null;
  45128. document.body.removeChild(this._debugCanvas);
  45129. this._debugCanvas = null;
  45130. this._debugCanvasContext = null;
  45131. }
  45132. };
  45133. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  45134. if (this._audioEngine.canUseWebAudio) {
  45135. inputAudioNode.connect(this._webAudioAnalyser);
  45136. this._webAudioAnalyser.connect(outputAudioNode);
  45137. }
  45138. };
  45139. Analyser.prototype.dispose = function () {
  45140. if (this._audioEngine.canUseWebAudio) {
  45141. this._webAudioAnalyser.disconnect();
  45142. }
  45143. };
  45144. return Analyser;
  45145. }());
  45146. BABYLON.Analyser = Analyser;
  45147. })(BABYLON || (BABYLON = {}));
  45148. //# sourceMappingURL=babylon.analyser.js.map
  45149. var BABYLON;
  45150. (function (BABYLON) {
  45151. var CubeTexture = (function (_super) {
  45152. __extends(CubeTexture, _super);
  45153. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  45154. if (onLoad === void 0) { onLoad = null; }
  45155. if (onError === void 0) { onError = null; }
  45156. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  45157. if (prefiltered === void 0) { prefiltered = false; }
  45158. if (forcedExtension === void 0) { forcedExtension = null; }
  45159. var _this = _super.call(this, scene) || this;
  45160. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  45161. _this.name = rootUrl;
  45162. _this.url = rootUrl;
  45163. _this._noMipmap = noMipmap;
  45164. _this.hasAlpha = false;
  45165. _this._format = format;
  45166. _this._prefiltered = prefiltered;
  45167. _this.isCube = true;
  45168. _this._textureMatrix = BABYLON.Matrix.Identity();
  45169. if (prefiltered) {
  45170. _this.gammaSpace = false;
  45171. }
  45172. if (!rootUrl && !files) {
  45173. return _this;
  45174. }
  45175. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  45176. if (!files) {
  45177. if (!extensions) {
  45178. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  45179. }
  45180. files = [];
  45181. for (var index = 0; index < extensions.length; index++) {
  45182. files.push(rootUrl + extensions[index]);
  45183. }
  45184. _this._extensions = extensions;
  45185. }
  45186. _this._files = files;
  45187. if (!_this._texture) {
  45188. if (!scene.useDelayedTextureLoading) {
  45189. if (prefiltered) {
  45190. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  45191. }
  45192. else {
  45193. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  45194. }
  45195. }
  45196. else {
  45197. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  45198. }
  45199. }
  45200. else if (onLoad) {
  45201. if (_this._texture.isReady) {
  45202. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  45203. }
  45204. else {
  45205. _this._texture.onLoadedObservable.add(onLoad);
  45206. }
  45207. }
  45208. return _this;
  45209. }
  45210. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  45211. return new CubeTexture("", scene, null, noMipmap, files);
  45212. };
  45213. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  45214. if (forcedExtension === void 0) { forcedExtension = null; }
  45215. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  45216. };
  45217. // Methods
  45218. CubeTexture.prototype.delayLoad = function () {
  45219. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  45220. return;
  45221. }
  45222. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  45223. this._texture = this._getFromCache(this.url, this._noMipmap);
  45224. if (!this._texture) {
  45225. if (this._prefiltered) {
  45226. this._texture = this.getScene().getEngine().createPrefilteredCubeTexture(this.url, this.getScene(), this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  45227. }
  45228. else {
  45229. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  45230. }
  45231. }
  45232. };
  45233. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  45234. return this._textureMatrix;
  45235. };
  45236. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  45237. this._textureMatrix = value;
  45238. };
  45239. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  45240. var texture = BABYLON.SerializationHelper.Parse(function () {
  45241. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  45242. }, parsedTexture, scene);
  45243. // Animations
  45244. if (parsedTexture.animations) {
  45245. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  45246. var parsedAnimation = parsedTexture.animations[animationIndex];
  45247. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  45248. }
  45249. }
  45250. return texture;
  45251. };
  45252. CubeTexture.prototype.clone = function () {
  45253. var _this = this;
  45254. return BABYLON.SerializationHelper.Clone(function () {
  45255. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  45256. }, this);
  45257. };
  45258. return CubeTexture;
  45259. }(BABYLON.BaseTexture));
  45260. BABYLON.CubeTexture = CubeTexture;
  45261. })(BABYLON || (BABYLON = {}));
  45262. //# sourceMappingURL=babylon.cubeTexture.js.map
  45263. var BABYLON;
  45264. (function (BABYLON) {
  45265. var RenderTargetTexture = (function (_super) {
  45266. __extends(RenderTargetTexture, _super);
  45267. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  45268. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  45269. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  45270. if (isCube === void 0) { isCube = false; }
  45271. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45272. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  45273. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  45274. if (isMulti === void 0) { isMulti = false; }
  45275. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  45276. _this.isCube = isCube;
  45277. /**
  45278. * Use this list to define the list of mesh you want to render.
  45279. */
  45280. _this.renderList = new Array();
  45281. _this.renderParticles = true;
  45282. _this.renderSprites = false;
  45283. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  45284. _this.ignoreCameraViewport = false;
  45285. // Events
  45286. /**
  45287. * An event triggered when the texture is unbind.
  45288. * @type {BABYLON.Observable}
  45289. */
  45290. _this.onBeforeBindObservable = new BABYLON.Observable();
  45291. /**
  45292. * An event triggered when the texture is unbind.
  45293. * @type {BABYLON.Observable}
  45294. */
  45295. _this.onAfterUnbindObservable = new BABYLON.Observable();
  45296. /**
  45297. * An event triggered before rendering the texture
  45298. * @type {BABYLON.Observable}
  45299. */
  45300. _this.onBeforeRenderObservable = new BABYLON.Observable();
  45301. /**
  45302. * An event triggered after rendering the texture
  45303. * @type {BABYLON.Observable}
  45304. */
  45305. _this.onAfterRenderObservable = new BABYLON.Observable();
  45306. /**
  45307. * An event triggered after the texture clear
  45308. * @type {BABYLON.Observable}
  45309. */
  45310. _this.onClearObservable = new BABYLON.Observable();
  45311. _this._currentRefreshId = -1;
  45312. _this._refreshRate = 1;
  45313. _this._samples = 1;
  45314. scene = _this.getScene();
  45315. _this.name = name;
  45316. _this.isRenderTarget = true;
  45317. _this._size = size;
  45318. _this._generateMipMaps = generateMipMaps;
  45319. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  45320. // Rendering groups
  45321. _this._renderingManager = new BABYLON.RenderingManager(scene);
  45322. if (isMulti) {
  45323. return _this;
  45324. }
  45325. _this._renderTargetOptions = {
  45326. generateMipMaps: generateMipMaps,
  45327. type: type,
  45328. samplingMode: samplingMode,
  45329. generateDepthBuffer: generateDepthBuffer,
  45330. generateStencilBuffer: generateStencilBuffer
  45331. };
  45332. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  45333. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45334. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45335. }
  45336. if (isCube) {
  45337. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  45338. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  45339. _this._textureMatrix = BABYLON.Matrix.Identity();
  45340. }
  45341. else {
  45342. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  45343. }
  45344. return _this;
  45345. }
  45346. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  45347. get: function () {
  45348. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  45349. },
  45350. enumerable: true,
  45351. configurable: true
  45352. });
  45353. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  45354. get: function () {
  45355. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  45356. },
  45357. enumerable: true,
  45358. configurable: true
  45359. });
  45360. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  45361. get: function () {
  45362. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  45363. },
  45364. enumerable: true,
  45365. configurable: true
  45366. });
  45367. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  45368. set: function (callback) {
  45369. if (this._onAfterUnbindObserver) {
  45370. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  45371. }
  45372. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  45373. },
  45374. enumerable: true,
  45375. configurable: true
  45376. });
  45377. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  45378. set: function (callback) {
  45379. if (this._onBeforeRenderObserver) {
  45380. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  45381. }
  45382. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  45383. },
  45384. enumerable: true,
  45385. configurable: true
  45386. });
  45387. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  45388. set: function (callback) {
  45389. if (this._onAfterRenderObserver) {
  45390. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  45391. }
  45392. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  45393. },
  45394. enumerable: true,
  45395. configurable: true
  45396. });
  45397. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  45398. set: function (callback) {
  45399. if (this._onClearObserver) {
  45400. this.onClearObservable.remove(this._onClearObserver);
  45401. }
  45402. this._onClearObserver = this.onClearObservable.add(callback);
  45403. },
  45404. enumerable: true,
  45405. configurable: true
  45406. });
  45407. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  45408. get: function () {
  45409. return this._renderTargetOptions;
  45410. },
  45411. enumerable: true,
  45412. configurable: true
  45413. });
  45414. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  45415. get: function () {
  45416. return this._samples;
  45417. },
  45418. set: function (value) {
  45419. if (this._samples === value) {
  45420. return;
  45421. }
  45422. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  45423. },
  45424. enumerable: true,
  45425. configurable: true
  45426. });
  45427. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  45428. this._currentRefreshId = -1;
  45429. };
  45430. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  45431. get: function () {
  45432. return this._refreshRate;
  45433. },
  45434. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  45435. set: function (value) {
  45436. this._refreshRate = value;
  45437. this.resetRefreshCounter();
  45438. },
  45439. enumerable: true,
  45440. configurable: true
  45441. });
  45442. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  45443. if (!this._postProcessManager) {
  45444. this._postProcessManager = new BABYLON.PostProcessManager(this.getScene());
  45445. this._postProcesses = new Array();
  45446. }
  45447. this._postProcesses.push(postProcess);
  45448. this._postProcesses[0].autoClear = false;
  45449. };
  45450. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  45451. if (!this._postProcesses) {
  45452. return;
  45453. }
  45454. if (dispose) {
  45455. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  45456. var postProcess = _a[_i];
  45457. postProcess.dispose();
  45458. postProcess = null;
  45459. }
  45460. }
  45461. this._postProcesses = [];
  45462. };
  45463. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  45464. if (!this._postProcesses) {
  45465. return;
  45466. }
  45467. var index = this._postProcesses.indexOf(postProcess);
  45468. if (index === -1) {
  45469. return;
  45470. }
  45471. this._postProcesses.splice(index, 1);
  45472. if (this._postProcesses.length > 0) {
  45473. this._postProcesses[0].autoClear = false;
  45474. }
  45475. };
  45476. RenderTargetTexture.prototype._shouldRender = function () {
  45477. if (this._currentRefreshId === -1) {
  45478. this._currentRefreshId = 1;
  45479. return true;
  45480. }
  45481. if (this.refreshRate === this._currentRefreshId) {
  45482. this._currentRefreshId = 1;
  45483. return true;
  45484. }
  45485. this._currentRefreshId++;
  45486. return false;
  45487. };
  45488. RenderTargetTexture.prototype.getRenderSize = function () {
  45489. return this._size;
  45490. };
  45491. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  45492. get: function () {
  45493. return true;
  45494. },
  45495. enumerable: true,
  45496. configurable: true
  45497. });
  45498. RenderTargetTexture.prototype.scale = function (ratio) {
  45499. var newSize = this._size * ratio;
  45500. this.resize(newSize);
  45501. };
  45502. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  45503. if (this.isCube) {
  45504. return this._textureMatrix;
  45505. }
  45506. return _super.prototype.getReflectionTextureMatrix.call(this);
  45507. };
  45508. RenderTargetTexture.prototype.resize = function (size) {
  45509. this.releaseInternalTexture();
  45510. if (this.isCube) {
  45511. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  45512. }
  45513. else {
  45514. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  45515. }
  45516. };
  45517. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  45518. var scene = this.getScene();
  45519. var engine = scene.getEngine();
  45520. if (this.useCameraPostProcesses !== undefined) {
  45521. useCameraPostProcess = this.useCameraPostProcesses;
  45522. }
  45523. if (this._waitingRenderList) {
  45524. this.renderList = [];
  45525. for (var index = 0; index < this._waitingRenderList.length; index++) {
  45526. var id = this._waitingRenderList[index];
  45527. this.renderList.push(scene.getMeshByID(id));
  45528. }
  45529. delete this._waitingRenderList;
  45530. }
  45531. // Is predicate defined?
  45532. if (this.renderListPredicate) {
  45533. this.renderList.splice(0); // Clear previous renderList
  45534. var sceneMeshes = this.getScene().meshes;
  45535. for (var index = 0; index < sceneMeshes.length; index++) {
  45536. var mesh = sceneMeshes[index];
  45537. if (this.renderListPredicate(mesh)) {
  45538. this.renderList.push(mesh);
  45539. }
  45540. }
  45541. }
  45542. if (this.renderList && this.renderList.length === 0) {
  45543. return;
  45544. }
  45545. this.onBeforeBindObservable.notifyObservers(this);
  45546. // Set custom projection.
  45547. // Needs to be before binding to prevent changing the aspect ratio.
  45548. var camera;
  45549. if (this.activeCamera) {
  45550. camera = this.activeCamera;
  45551. engine.setViewport(this.activeCamera.viewport, this._size, this._size);
  45552. if (this.activeCamera !== scene.activeCamera) {
  45553. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  45554. }
  45555. }
  45556. else {
  45557. camera = scene.activeCamera;
  45558. engine.setViewport(scene.activeCamera.viewport, this._size, this._size);
  45559. }
  45560. // Prepare renderingManager
  45561. this._renderingManager.reset();
  45562. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  45563. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  45564. var sceneRenderId = scene.getRenderId();
  45565. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  45566. var mesh = currentRenderList[meshIndex];
  45567. if (mesh) {
  45568. if (!mesh.isReady()) {
  45569. // Reset _currentRefreshId
  45570. this.resetRefreshCounter();
  45571. continue;
  45572. }
  45573. mesh._preActivateForIntermediateRendering(sceneRenderId);
  45574. var isMasked = void 0;
  45575. if (!this.renderList) {
  45576. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  45577. }
  45578. else {
  45579. isMasked = false;
  45580. }
  45581. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  45582. mesh._activate(sceneRenderId);
  45583. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  45584. var subMesh = mesh.subMeshes[subIndex];
  45585. scene._activeIndices.addCount(subMesh.indexCount, false);
  45586. this._renderingManager.dispatch(subMesh);
  45587. }
  45588. }
  45589. }
  45590. }
  45591. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  45592. var particleSystem = scene.particleSystems[particleIndex];
  45593. var emitter = particleSystem.emitter;
  45594. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  45595. continue;
  45596. }
  45597. if (currentRenderList.indexOf(emitter) >= 0) {
  45598. this._renderingManager.dispatchParticles(particleSystem);
  45599. }
  45600. }
  45601. if (this.isCube) {
  45602. for (var face = 0; face < 6; face++) {
  45603. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  45604. scene.incrementRenderId();
  45605. scene.resetCachedMaterial();
  45606. }
  45607. }
  45608. else {
  45609. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  45610. }
  45611. this.onAfterUnbindObservable.notifyObservers(this);
  45612. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  45613. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  45614. }
  45615. engine.setViewport(scene.activeCamera.viewport);
  45616. scene.resetCachedMaterial();
  45617. };
  45618. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  45619. var _this = this;
  45620. var scene = this.getScene();
  45621. var engine = scene.getEngine();
  45622. // Bind
  45623. if (this._postProcessManager) {
  45624. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  45625. }
  45626. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  45627. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  45628. }
  45629. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  45630. // Clear
  45631. if (this.onClearObservable.hasObservers()) {
  45632. this.onClearObservable.notifyObservers(engine);
  45633. }
  45634. else {
  45635. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  45636. }
  45637. if (!this._doNotChangeAspectRatio) {
  45638. scene.updateTransformMatrix(true);
  45639. }
  45640. // Render
  45641. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  45642. if (this._postProcessManager) {
  45643. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses);
  45644. }
  45645. else if (useCameraPostProcess) {
  45646. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  45647. }
  45648. if (!this._doNotChangeAspectRatio) {
  45649. scene.updateTransformMatrix(true);
  45650. }
  45651. // Dump ?
  45652. if (dumpForDebug) {
  45653. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  45654. }
  45655. // Unbind
  45656. if (!this.isCube || faceIndex === 5) {
  45657. if (this.isCube) {
  45658. if (faceIndex === 5) {
  45659. engine.generateMipMapsForCubemap(this._texture);
  45660. }
  45661. }
  45662. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  45663. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  45664. });
  45665. }
  45666. else {
  45667. this.onAfterRenderObservable.notifyObservers(faceIndex);
  45668. }
  45669. };
  45670. /**
  45671. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  45672. * This allowed control for front to back rendering or reversly depending of the special needs.
  45673. *
  45674. * @param renderingGroupId The rendering group id corresponding to its index
  45675. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  45676. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  45677. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  45678. */
  45679. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  45680. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  45681. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  45682. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  45683. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  45684. };
  45685. /**
  45686. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  45687. *
  45688. * @param renderingGroupId The rendering group id corresponding to its index
  45689. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  45690. */
  45691. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  45692. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  45693. };
  45694. RenderTargetTexture.prototype.clone = function () {
  45695. var textureSize = this.getSize();
  45696. 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);
  45697. // Base texture
  45698. newTexture.hasAlpha = this.hasAlpha;
  45699. newTexture.level = this.level;
  45700. // RenderTarget Texture
  45701. newTexture.coordinatesMode = this.coordinatesMode;
  45702. newTexture.renderList = this.renderList.slice(0);
  45703. return newTexture;
  45704. };
  45705. RenderTargetTexture.prototype.serialize = function () {
  45706. if (!this.name) {
  45707. return null;
  45708. }
  45709. var serializationObject = _super.prototype.serialize.call(this);
  45710. serializationObject.renderTargetSize = this.getRenderSize();
  45711. serializationObject.renderList = [];
  45712. for (var index = 0; index < this.renderList.length; index++) {
  45713. serializationObject.renderList.push(this.renderList[index].id);
  45714. }
  45715. return serializationObject;
  45716. };
  45717. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  45718. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  45719. this.getScene().getEngine()._releaseFramebufferObjects(this.getInternalTexture());
  45720. };
  45721. RenderTargetTexture.prototype.dispose = function () {
  45722. if (this._postProcessManager) {
  45723. this._postProcessManager.dispose();
  45724. this._postProcessManager = null;
  45725. }
  45726. this.clearPostProcesses(true);
  45727. this.renderList = null;
  45728. // Remove from custom render targets
  45729. var scene = this.getScene();
  45730. var index = scene.customRenderTargets.indexOf(this);
  45731. if (index >= 0) {
  45732. scene.customRenderTargets.splice(index, 1);
  45733. }
  45734. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  45735. var camera = _a[_i];
  45736. index = camera.customRenderTargets.indexOf(this);
  45737. if (index >= 0) {
  45738. camera.customRenderTargets.splice(index, 1);
  45739. }
  45740. }
  45741. _super.prototype.dispose.call(this);
  45742. };
  45743. RenderTargetTexture.prototype._rebuild = function () {
  45744. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  45745. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  45746. }
  45747. if (this._postProcessManager) {
  45748. this._postProcessManager._rebuild();
  45749. }
  45750. };
  45751. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  45752. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  45753. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  45754. return RenderTargetTexture;
  45755. }(BABYLON.Texture));
  45756. BABYLON.RenderTargetTexture = RenderTargetTexture;
  45757. })(BABYLON || (BABYLON = {}));
  45758. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  45759. var BABYLON;
  45760. (function (BABYLON) {
  45761. ;
  45762. var MultiRenderTarget = (function (_super) {
  45763. __extends(MultiRenderTarget, _super);
  45764. function MultiRenderTarget(name, size, count, scene, options) {
  45765. var _this = this;
  45766. options = options || {};
  45767. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  45768. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  45769. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  45770. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  45771. if (!_this.isSupported) {
  45772. _this.dispose();
  45773. return;
  45774. }
  45775. var types = [];
  45776. var samplingModes = [];
  45777. for (var i = 0; i < count; i++) {
  45778. if (options.types && options.types[i]) {
  45779. types.push(options.types[i]);
  45780. }
  45781. else {
  45782. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  45783. }
  45784. if (options.samplingModes && options.samplingModes[i]) {
  45785. samplingModes.push(options.samplingModes[i]);
  45786. }
  45787. else {
  45788. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  45789. }
  45790. }
  45791. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  45792. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  45793. _this._count = count;
  45794. _this._size = size;
  45795. _this._multiRenderTargetOptions = {
  45796. samplingModes: samplingModes,
  45797. generateMipMaps: generateMipMaps,
  45798. generateDepthBuffer: generateDepthBuffer,
  45799. generateStencilBuffer: generateStencilBuffer,
  45800. generateDepthTexture: generateDepthTexture,
  45801. types: types,
  45802. textureCount: count
  45803. };
  45804. _this._createInternalTextures();
  45805. _this._createTextures();
  45806. return _this;
  45807. }
  45808. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  45809. get: function () {
  45810. var engine = this.getScene().getEngine();
  45811. return engine.webGLVersion > 1 || engine.getCaps().drawBuffersExtension;
  45812. },
  45813. enumerable: true,
  45814. configurable: true
  45815. });
  45816. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  45817. get: function () {
  45818. return this._textures;
  45819. },
  45820. enumerable: true,
  45821. configurable: true
  45822. });
  45823. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  45824. get: function () {
  45825. return this._textures[this._textures.length - 1];
  45826. },
  45827. enumerable: true,
  45828. configurable: true
  45829. });
  45830. MultiRenderTarget.prototype._rebuild = function () {
  45831. this.releaseInternalTextures();
  45832. this._createInternalTextures();
  45833. for (var i = 0; i < this._internalTextures.length; i++) {
  45834. var texture = this._textures[i];
  45835. texture._texture = this._internalTextures[i];
  45836. }
  45837. // Keeps references to frame buffer and stencil/depth buffer
  45838. this._texture = this._internalTextures[0];
  45839. };
  45840. MultiRenderTarget.prototype._createInternalTextures = function () {
  45841. this._internalTextures = this.getScene().getEngine().createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  45842. };
  45843. MultiRenderTarget.prototype._createTextures = function () {
  45844. this._textures = [];
  45845. for (var i = 0; i < this._internalTextures.length; i++) {
  45846. var texture = new BABYLON.Texture(null, this.getScene());
  45847. texture._texture = this._internalTextures[i];
  45848. this._textures.push(texture);
  45849. }
  45850. // Keeps references to frame buffer and stencil/depth buffer
  45851. this._texture = this._internalTextures[0];
  45852. };
  45853. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  45854. get: function () {
  45855. return this._samples;
  45856. },
  45857. set: function (value) {
  45858. if (this._samples === value) {
  45859. return;
  45860. }
  45861. for (var i = 0; i < this._internalTextures.length; i++) {
  45862. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._internalTextures[i], value);
  45863. }
  45864. },
  45865. enumerable: true,
  45866. configurable: true
  45867. });
  45868. MultiRenderTarget.prototype.resize = function (size) {
  45869. this.releaseInternalTextures();
  45870. this._internalTextures = this.getScene().getEngine().createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  45871. this._createInternalTextures();
  45872. };
  45873. MultiRenderTarget.prototype.dispose = function () {
  45874. this.releaseInternalTextures();
  45875. _super.prototype.dispose.call(this);
  45876. };
  45877. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  45878. if (!this._internalTextures) {
  45879. return;
  45880. }
  45881. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  45882. if (this._internalTextures[i] !== undefined) {
  45883. this._internalTextures[i].dispose();
  45884. this._internalTextures.splice(i, 1);
  45885. }
  45886. }
  45887. };
  45888. return MultiRenderTarget;
  45889. }(BABYLON.RenderTargetTexture));
  45890. BABYLON.MultiRenderTarget = MultiRenderTarget;
  45891. })(BABYLON || (BABYLON = {}));
  45892. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  45893. /// <reference path="babylon.renderTargetTexture.ts" />
  45894. var BABYLON;
  45895. (function (BABYLON) {
  45896. var MirrorTexture = (function (_super) {
  45897. __extends(MirrorTexture, _super);
  45898. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  45899. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  45900. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  45901. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  45902. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  45903. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  45904. _this._transformMatrix = BABYLON.Matrix.Zero();
  45905. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  45906. _this._blurKernelX = 0;
  45907. _this._blurKernelY = 0;
  45908. _this._blurRatio = 1.0;
  45909. _this.onBeforeRenderObservable.add(function () {
  45910. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  45911. _this._savedViewMatrix = scene.getViewMatrix();
  45912. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  45913. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  45914. scene.clipPlane = _this.mirrorPlane;
  45915. scene.getEngine().cullBackFaces = false;
  45916. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  45917. });
  45918. _this.onAfterRenderObservable.add(function () {
  45919. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  45920. scene.getEngine().cullBackFaces = true;
  45921. scene._mirroredCameraPosition = null;
  45922. delete scene.clipPlane;
  45923. });
  45924. return _this;
  45925. }
  45926. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  45927. get: function () {
  45928. return this._blurRatio;
  45929. },
  45930. set: function (value) {
  45931. if (this._blurRatio === value) {
  45932. return;
  45933. }
  45934. this._blurRatio = value;
  45935. this._preparePostProcesses();
  45936. },
  45937. enumerable: true,
  45938. configurable: true
  45939. });
  45940. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  45941. set: function (value) {
  45942. this.blurKernelX = value;
  45943. this.blurKernelY = value;
  45944. },
  45945. enumerable: true,
  45946. configurable: true
  45947. });
  45948. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  45949. get: function () {
  45950. return this._blurKernelX;
  45951. },
  45952. set: function (value) {
  45953. if (this._blurKernelX === value) {
  45954. return;
  45955. }
  45956. this._blurKernelX = value;
  45957. this._preparePostProcesses();
  45958. },
  45959. enumerable: true,
  45960. configurable: true
  45961. });
  45962. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  45963. get: function () {
  45964. return this._blurKernelY;
  45965. },
  45966. set: function (value) {
  45967. if (this._blurKernelY === value) {
  45968. return;
  45969. }
  45970. this._blurKernelY = value;
  45971. this._preparePostProcesses();
  45972. },
  45973. enumerable: true,
  45974. configurable: true
  45975. });
  45976. MirrorTexture.prototype._preparePostProcesses = function () {
  45977. this.clearPostProcesses(true);
  45978. if (this._blurKernelX && this._blurKernelY) {
  45979. var engine = this.getScene().getEngine();
  45980. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  45981. 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);
  45982. this._blurX.autoClear = false;
  45983. if (this._blurRatio === 1 && this.samples < 2) {
  45984. this._blurX.outputTexture = this._texture;
  45985. }
  45986. else {
  45987. this._blurX.alwaysForcePOT = true;
  45988. }
  45989. 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);
  45990. this._blurY.autoClear = false;
  45991. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  45992. this.addPostProcess(this._blurX);
  45993. this.addPostProcess(this._blurY);
  45994. }
  45995. };
  45996. MirrorTexture.prototype.clone = function () {
  45997. var textureSize = this.getSize();
  45998. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  45999. // Base texture
  46000. newTexture.hasAlpha = this.hasAlpha;
  46001. newTexture.level = this.level;
  46002. // Mirror Texture
  46003. newTexture.mirrorPlane = this.mirrorPlane.clone();
  46004. newTexture.renderList = this.renderList.slice(0);
  46005. return newTexture;
  46006. };
  46007. MirrorTexture.prototype.serialize = function () {
  46008. if (!this.name) {
  46009. return null;
  46010. }
  46011. var serializationObject = _super.prototype.serialize.call(this);
  46012. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  46013. return serializationObject;
  46014. };
  46015. return MirrorTexture;
  46016. }(BABYLON.RenderTargetTexture));
  46017. BABYLON.MirrorTexture = MirrorTexture;
  46018. })(BABYLON || (BABYLON = {}));
  46019. //# sourceMappingURL=babylon.mirrorTexture.js.map
  46020. /// <reference path="babylon.renderTargetTexture.ts" />
  46021. var BABYLON;
  46022. (function (BABYLON) {
  46023. /**
  46024. * Creates a refraction texture used by refraction channel of the standard material.
  46025. * @param name the texture name
  46026. * @param size size of the underlying texture
  46027. * @param scene root scene
  46028. */
  46029. var RefractionTexture = (function (_super) {
  46030. __extends(RefractionTexture, _super);
  46031. function RefractionTexture(name, size, scene, generateMipMaps) {
  46032. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  46033. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  46034. _this.depth = 2.0;
  46035. _this.onBeforeRenderObservable.add(function () {
  46036. scene.clipPlane = _this.refractionPlane;
  46037. });
  46038. _this.onAfterRenderObservable.add(function () {
  46039. delete scene.clipPlane;
  46040. });
  46041. return _this;
  46042. }
  46043. RefractionTexture.prototype.clone = function () {
  46044. var textureSize = this.getSize();
  46045. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  46046. // Base texture
  46047. newTexture.hasAlpha = this.hasAlpha;
  46048. newTexture.level = this.level;
  46049. // Refraction Texture
  46050. newTexture.refractionPlane = this.refractionPlane.clone();
  46051. newTexture.renderList = this.renderList.slice(0);
  46052. newTexture.depth = this.depth;
  46053. return newTexture;
  46054. };
  46055. RefractionTexture.prototype.serialize = function () {
  46056. if (!this.name) {
  46057. return null;
  46058. }
  46059. var serializationObject = _super.prototype.serialize.call(this);
  46060. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  46061. serializationObject.depth = this.depth;
  46062. return serializationObject;
  46063. };
  46064. return RefractionTexture;
  46065. }(BABYLON.RenderTargetTexture));
  46066. BABYLON.RefractionTexture = RefractionTexture;
  46067. })(BABYLON || (BABYLON = {}));
  46068. //# sourceMappingURL=babylon.refractionTexture.js.map
  46069. /// <reference path="babylon.texture.ts" />
  46070. var BABYLON;
  46071. (function (BABYLON) {
  46072. var DynamicTexture = (function (_super) {
  46073. __extends(DynamicTexture, _super);
  46074. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  46075. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46076. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  46077. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  46078. _this.name = name;
  46079. var engine = _this.getScene().getEngine();
  46080. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46081. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46082. _this._generateMipMaps = generateMipMaps;
  46083. if (options.getContext) {
  46084. _this._canvas = options;
  46085. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  46086. }
  46087. else {
  46088. _this._canvas = document.createElement("canvas");
  46089. if (options.width) {
  46090. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  46091. }
  46092. else {
  46093. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  46094. }
  46095. }
  46096. var textureSize = _this.getSize();
  46097. _this._canvas.width = textureSize.width;
  46098. _this._canvas.height = textureSize.height;
  46099. _this._context = _this._canvas.getContext("2d");
  46100. return _this;
  46101. }
  46102. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  46103. get: function () {
  46104. return true;
  46105. },
  46106. enumerable: true,
  46107. configurable: true
  46108. });
  46109. DynamicTexture.prototype._recreate = function (textureSize) {
  46110. this._canvas.width = textureSize.width;
  46111. this._canvas.height = textureSize.height;
  46112. this.releaseInternalTexture();
  46113. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  46114. };
  46115. DynamicTexture.prototype.scale = function (ratio) {
  46116. var textureSize = this.getSize();
  46117. textureSize.width *= ratio;
  46118. textureSize.height *= ratio;
  46119. this._recreate(textureSize);
  46120. };
  46121. DynamicTexture.prototype.scaleTo = function (width, height) {
  46122. var textureSize = this.getSize();
  46123. textureSize.width = width;
  46124. textureSize.height = height;
  46125. this._recreate(textureSize);
  46126. };
  46127. DynamicTexture.prototype.getContext = function () {
  46128. return this._context;
  46129. };
  46130. DynamicTexture.prototype.clear = function () {
  46131. var size = this.getSize();
  46132. this._context.fillRect(0, 0, size.width, size.height);
  46133. };
  46134. DynamicTexture.prototype.update = function (invertY) {
  46135. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  46136. };
  46137. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  46138. if (update === void 0) { update = true; }
  46139. var size = this.getSize();
  46140. if (clearColor) {
  46141. this._context.fillStyle = clearColor;
  46142. this._context.fillRect(0, 0, size.width, size.height);
  46143. }
  46144. this._context.font = font;
  46145. if (x === null || x === undefined) {
  46146. var textSize = this._context.measureText(text);
  46147. x = (size.width - textSize.width) / 2;
  46148. }
  46149. if (y === null || y === undefined) {
  46150. var fontSize = parseInt((font.replace(/\D/g, '')));
  46151. ;
  46152. y = (size.height / 2) + (fontSize / 3.65);
  46153. }
  46154. this._context.fillStyle = color;
  46155. this._context.fillText(text, x, y);
  46156. if (update) {
  46157. this.update(invertY);
  46158. }
  46159. };
  46160. DynamicTexture.prototype.clone = function () {
  46161. var textureSize = this.getSize();
  46162. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  46163. // Base texture
  46164. newTexture.hasAlpha = this.hasAlpha;
  46165. newTexture.level = this.level;
  46166. // Dynamic Texture
  46167. newTexture.wrapU = this.wrapU;
  46168. newTexture.wrapV = this.wrapV;
  46169. return newTexture;
  46170. };
  46171. DynamicTexture.prototype._rebuild = function () {
  46172. this.update();
  46173. };
  46174. return DynamicTexture;
  46175. }(BABYLON.Texture));
  46176. BABYLON.DynamicTexture = DynamicTexture;
  46177. })(BABYLON || (BABYLON = {}));
  46178. //# sourceMappingURL=babylon.dynamicTexture.js.map
  46179. var BABYLON;
  46180. (function (BABYLON) {
  46181. var VideoTexture = (function (_super) {
  46182. __extends(VideoTexture, _super);
  46183. /**
  46184. * Creates a video texture.
  46185. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  46186. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  46187. * @param {BABYLON.Scene} scene is obviously the current scene.
  46188. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  46189. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  46190. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  46191. */
  46192. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  46193. if (generateMipMaps === void 0) { generateMipMaps = false; }
  46194. if (invertY === void 0) { invertY = false; }
  46195. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46196. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  46197. _this._autoLaunch = true;
  46198. var urls;
  46199. _this.name = name;
  46200. if (urlsOrVideo instanceof HTMLVideoElement) {
  46201. _this.video = urlsOrVideo;
  46202. }
  46203. else {
  46204. urls = urlsOrVideo;
  46205. _this.video = document.createElement("video");
  46206. _this.video.autoplay = false;
  46207. _this.video.loop = true;
  46208. }
  46209. _this._generateMipMaps = generateMipMaps;
  46210. _this._samplingMode = samplingMode;
  46211. if (!_this.getScene().getEngine().needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  46212. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  46213. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  46214. }
  46215. else {
  46216. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46217. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46218. _this._generateMipMaps = false;
  46219. }
  46220. if (urls) {
  46221. _this.video.addEventListener("canplay", function () {
  46222. _this._createTexture();
  46223. });
  46224. urls.forEach(function (url) {
  46225. var source = document.createElement("source");
  46226. source.src = url;
  46227. _this.video.appendChild(source);
  46228. });
  46229. }
  46230. else {
  46231. _this._createTexture();
  46232. }
  46233. _this._lastUpdate = BABYLON.Tools.Now;
  46234. return _this;
  46235. }
  46236. VideoTexture.prototype.__setTextureReady = function () {
  46237. this._texture.isReady = true;
  46238. };
  46239. VideoTexture.prototype._createTexture = function () {
  46240. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  46241. if (this._autoLaunch) {
  46242. this._autoLaunch = false;
  46243. this.video.play();
  46244. }
  46245. this._setTextureReady = this.__setTextureReady.bind(this);
  46246. this.video.addEventListener("playing", this._setTextureReady);
  46247. };
  46248. VideoTexture.prototype.update = function () {
  46249. var now = BABYLON.Tools.Now;
  46250. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  46251. return false;
  46252. }
  46253. this._lastUpdate = now;
  46254. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  46255. return true;
  46256. };
  46257. VideoTexture.prototype.dispose = function () {
  46258. _super.prototype.dispose.call(this);
  46259. this.video.removeEventListener("playing", this._setTextureReady);
  46260. };
  46261. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  46262. var video = document.createElement("video");
  46263. var constraintsDeviceId;
  46264. if (constraints && constraints.deviceId) {
  46265. constraintsDeviceId = {
  46266. exact: constraints.deviceId
  46267. };
  46268. }
  46269. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  46270. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  46271. if (navigator.getUserMedia) {
  46272. navigator.getUserMedia({
  46273. video: {
  46274. deviceId: constraintsDeviceId,
  46275. width: {
  46276. min: (constraints && constraints.minWidth) || 256,
  46277. max: (constraints && constraints.maxWidth) || 640
  46278. },
  46279. height: {
  46280. min: (constraints && constraints.minHeight) || 256,
  46281. max: (constraints && constraints.maxHeight) || 480
  46282. }
  46283. }
  46284. }, function (stream) {
  46285. if (video.mozSrcObject !== undefined) {
  46286. video.mozSrcObject = stream;
  46287. }
  46288. else {
  46289. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  46290. }
  46291. video.play();
  46292. if (onReady) {
  46293. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  46294. }
  46295. }, function (e) {
  46296. BABYLON.Tools.Error(e.name);
  46297. });
  46298. }
  46299. };
  46300. return VideoTexture;
  46301. }(BABYLON.Texture));
  46302. BABYLON.VideoTexture = VideoTexture;
  46303. })(BABYLON || (BABYLON = {}));
  46304. //# sourceMappingURL=babylon.videoTexture.js.map
  46305. var BABYLON;
  46306. (function (BABYLON) {
  46307. var RawTexture = (function (_super) {
  46308. __extends(RawTexture, _super);
  46309. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  46310. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46311. if (invertY === void 0) { invertY = false; }
  46312. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46313. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  46314. _this.format = format;
  46315. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  46316. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46317. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46318. return _this;
  46319. }
  46320. RawTexture.prototype.update = function (data) {
  46321. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  46322. };
  46323. // Statics
  46324. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  46325. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46326. if (invertY === void 0) { invertY = false; }
  46327. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46328. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  46329. };
  46330. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  46331. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46332. if (invertY === void 0) { invertY = false; }
  46333. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46334. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  46335. };
  46336. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  46337. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46338. if (invertY === void 0) { invertY = false; }
  46339. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46340. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  46341. };
  46342. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  46343. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46344. if (invertY === void 0) { invertY = false; }
  46345. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46346. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  46347. };
  46348. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  46349. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46350. if (invertY === void 0) { invertY = false; }
  46351. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46352. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  46353. };
  46354. return RawTexture;
  46355. }(BABYLON.Texture));
  46356. BABYLON.RawTexture = RawTexture;
  46357. })(BABYLON || (BABYLON = {}));
  46358. //# sourceMappingURL=babylon.rawTexture.js.map
  46359. var BABYLON;
  46360. (function (BABYLON) {
  46361. var PostProcess = (function () {
  46362. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  46363. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  46364. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  46365. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  46366. if (blockCompilation === void 0) { blockCompilation = false; }
  46367. this.name = name;
  46368. this.width = -1;
  46369. this.height = -1;
  46370. this.autoClear = true;
  46371. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  46372. /*
  46373. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  46374. Can only be used on a single postprocess or on the last one of a chain.
  46375. */
  46376. this.enablePixelPerfectMode = false;
  46377. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  46378. this.alwaysForcePOT = false;
  46379. this.samples = 1;
  46380. this._reusable = false;
  46381. this._textures = new BABYLON.SmartArray(2);
  46382. this._currentRenderTextureInd = 0;
  46383. this._scaleRatio = new BABYLON.Vector2(1, 1);
  46384. this._texelSize = BABYLON.Vector2.Zero();
  46385. // Events
  46386. /**
  46387. * An event triggered when the postprocess is activated.
  46388. * @type {BABYLON.Observable}
  46389. */
  46390. this.onActivateObservable = new BABYLON.Observable();
  46391. /**
  46392. * An event triggered when the postprocess changes its size.
  46393. * @type {BABYLON.Observable}
  46394. */
  46395. this.onSizeChangedObservable = new BABYLON.Observable();
  46396. /**
  46397. * An event triggered when the postprocess applies its effect.
  46398. * @type {BABYLON.Observable}
  46399. */
  46400. this.onApplyObservable = new BABYLON.Observable();
  46401. /**
  46402. * An event triggered before rendering the postprocess
  46403. * @type {BABYLON.Observable}
  46404. */
  46405. this.onBeforeRenderObservable = new BABYLON.Observable();
  46406. /**
  46407. * An event triggered after rendering the postprocess
  46408. * @type {BABYLON.Observable}
  46409. */
  46410. this.onAfterRenderObservable = new BABYLON.Observable();
  46411. if (camera != null) {
  46412. this._camera = camera;
  46413. this._scene = camera.getScene();
  46414. camera.attachPostProcess(this);
  46415. this._engine = this._scene.getEngine();
  46416. this._scene.postProcesses.push(this);
  46417. }
  46418. else {
  46419. this._engine = engine;
  46420. this._engine.postProcesses.push(this);
  46421. }
  46422. this._options = options;
  46423. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  46424. this._reusable = reusable || false;
  46425. this._textureType = textureType;
  46426. this._samplers = samplers || [];
  46427. this._samplers.push("textureSampler");
  46428. this._fragmentUrl = fragmentUrl;
  46429. this._vertexUrl = vertexUrl;
  46430. this._parameters = parameters || [];
  46431. this._parameters.push("scale");
  46432. this._indexParameters = indexParameters;
  46433. if (!blockCompilation) {
  46434. this.updateEffect(defines);
  46435. }
  46436. }
  46437. Object.defineProperty(PostProcess.prototype, "onActivate", {
  46438. set: function (callback) {
  46439. if (this._onActivateObserver) {
  46440. this.onActivateObservable.remove(this._onActivateObserver);
  46441. }
  46442. this._onActivateObserver = this.onActivateObservable.add(callback);
  46443. },
  46444. enumerable: true,
  46445. configurable: true
  46446. });
  46447. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  46448. set: function (callback) {
  46449. if (this._onSizeChangedObserver) {
  46450. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  46451. }
  46452. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  46453. },
  46454. enumerable: true,
  46455. configurable: true
  46456. });
  46457. Object.defineProperty(PostProcess.prototype, "onApply", {
  46458. set: function (callback) {
  46459. if (this._onApplyObserver) {
  46460. this.onApplyObservable.remove(this._onApplyObserver);
  46461. }
  46462. this._onApplyObserver = this.onApplyObservable.add(callback);
  46463. },
  46464. enumerable: true,
  46465. configurable: true
  46466. });
  46467. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  46468. set: function (callback) {
  46469. if (this._onBeforeRenderObserver) {
  46470. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  46471. }
  46472. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  46473. },
  46474. enumerable: true,
  46475. configurable: true
  46476. });
  46477. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  46478. set: function (callback) {
  46479. if (this._onAfterRenderObserver) {
  46480. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  46481. }
  46482. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  46483. },
  46484. enumerable: true,
  46485. configurable: true
  46486. });
  46487. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  46488. get: function () {
  46489. return this._textures.data[this._currentRenderTextureInd];
  46490. },
  46491. set: function (value) {
  46492. this._forcedOutputTexture = value;
  46493. },
  46494. enumerable: true,
  46495. configurable: true
  46496. });
  46497. PostProcess.prototype.getCamera = function () {
  46498. return this._camera;
  46499. };
  46500. Object.defineProperty(PostProcess.prototype, "texelSize", {
  46501. get: function () {
  46502. if (this._shareOutputWithPostProcess) {
  46503. return this._shareOutputWithPostProcess.texelSize;
  46504. }
  46505. if (this._forcedOutputTexture) {
  46506. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  46507. }
  46508. return this._texelSize;
  46509. },
  46510. enumerable: true,
  46511. configurable: true
  46512. });
  46513. PostProcess.prototype.getEngine = function () {
  46514. return this._engine;
  46515. };
  46516. PostProcess.prototype.getEffect = function () {
  46517. return this._effect;
  46518. };
  46519. PostProcess.prototype.shareOutputWith = function (postProcess) {
  46520. this._disposeTextures();
  46521. this._shareOutputWithPostProcess = postProcess;
  46522. return this;
  46523. };
  46524. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  46525. 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);
  46526. };
  46527. PostProcess.prototype.isReusable = function () {
  46528. return this._reusable;
  46529. };
  46530. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  46531. PostProcess.prototype.markTextureDirty = function () {
  46532. this.width = -1;
  46533. };
  46534. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  46535. var _this = this;
  46536. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  46537. camera = camera || this._camera;
  46538. var scene = camera.getScene();
  46539. var engine = scene.getEngine();
  46540. var maxSize = engine.getCaps().maxTextureSize;
  46541. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  46542. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  46543. var desiredWidth = this._options.width || requiredWidth;
  46544. var desiredHeight = this._options.height || requiredHeight;
  46545. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  46546. if (!this._options.width) {
  46547. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  46548. }
  46549. if (!this._options.height) {
  46550. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  46551. }
  46552. }
  46553. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  46554. if (this._textures.length > 0) {
  46555. for (var i = 0; i < this._textures.length; i++) {
  46556. this._engine._releaseTexture(this._textures.data[i]);
  46557. }
  46558. this._textures.reset();
  46559. }
  46560. this.width = desiredWidth;
  46561. this.height = desiredHeight;
  46562. var textureSize = { width: this.width, height: this.height };
  46563. var textureOptions = {
  46564. generateMipMaps: false,
  46565. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  46566. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  46567. samplingMode: this.renderTargetSamplingMode,
  46568. type: this._textureType
  46569. };
  46570. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  46571. if (this._reusable) {
  46572. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  46573. }
  46574. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  46575. this.onSizeChangedObservable.notifyObservers(this);
  46576. }
  46577. this._textures.forEach(function (texture) {
  46578. if (texture.samples !== _this.samples) {
  46579. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  46580. }
  46581. });
  46582. }
  46583. var target;
  46584. if (this._shareOutputWithPostProcess) {
  46585. target = this._shareOutputWithPostProcess.outputTexture;
  46586. }
  46587. else if (this._forcedOutputTexture) {
  46588. target = this._forcedOutputTexture;
  46589. this.width = this._forcedOutputTexture.width;
  46590. this.height = this._forcedOutputTexture.height;
  46591. }
  46592. else {
  46593. target = this.outputTexture;
  46594. }
  46595. if (this.enablePixelPerfectMode) {
  46596. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  46597. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  46598. }
  46599. else {
  46600. this._scaleRatio.copyFromFloats(1, 1);
  46601. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  46602. }
  46603. this.onActivateObservable.notifyObservers(camera);
  46604. // Clear
  46605. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  46606. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  46607. }
  46608. if (this._reusable) {
  46609. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  46610. }
  46611. };
  46612. Object.defineProperty(PostProcess.prototype, "isSupported", {
  46613. get: function () {
  46614. return this._effect.isSupported;
  46615. },
  46616. enumerable: true,
  46617. configurable: true
  46618. });
  46619. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  46620. get: function () {
  46621. if (this._shareOutputWithPostProcess) {
  46622. return this._shareOutputWithPostProcess.aspectRatio;
  46623. }
  46624. if (this._forcedOutputTexture) {
  46625. var size = this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  46626. }
  46627. return this.width / this.height;
  46628. },
  46629. enumerable: true,
  46630. configurable: true
  46631. });
  46632. PostProcess.prototype.apply = function () {
  46633. // Check
  46634. if (!this._effect || !this._effect.isReady())
  46635. return null;
  46636. // States
  46637. this._engine.enableEffect(this._effect);
  46638. this._engine.setState(false);
  46639. this._engine.setDepthBuffer(false);
  46640. this._engine.setDepthWrite(false);
  46641. // Alpha
  46642. this._engine.setAlphaMode(this.alphaMode);
  46643. if (this.alphaConstants) {
  46644. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  46645. }
  46646. // Texture
  46647. var source;
  46648. if (this._shareOutputWithPostProcess) {
  46649. source = this._shareOutputWithPostProcess.outputTexture;
  46650. }
  46651. else if (this._forcedOutputTexture) {
  46652. source = this._forcedOutputTexture;
  46653. }
  46654. else {
  46655. source = this.outputTexture;
  46656. }
  46657. this._effect._bindTexture("textureSampler", source);
  46658. // Parameters
  46659. this._effect.setVector2("scale", this._scaleRatio);
  46660. this.onApplyObservable.notifyObservers(this._effect);
  46661. return this._effect;
  46662. };
  46663. PostProcess.prototype._disposeTextures = function () {
  46664. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  46665. return;
  46666. }
  46667. if (this._textures.length > 0) {
  46668. for (var i = 0; i < this._textures.length; i++) {
  46669. this._engine._releaseTexture(this._textures.data[i]);
  46670. }
  46671. }
  46672. this._textures.dispose();
  46673. };
  46674. PostProcess.prototype.dispose = function (camera) {
  46675. camera = camera || this._camera;
  46676. this._disposeTextures();
  46677. if (this._scene) {
  46678. var index_1 = this._scene.postProcesses.indexOf(this);
  46679. if (index_1 !== -1) {
  46680. this._scene.postProcesses.splice(index_1, 1);
  46681. }
  46682. }
  46683. else {
  46684. var index_2 = this._engine.postProcesses.indexOf(this);
  46685. if (index_2 !== -1) {
  46686. this._engine.postProcesses.splice(index_2, 1);
  46687. }
  46688. }
  46689. if (!camera) {
  46690. return;
  46691. }
  46692. camera.detachPostProcess(this);
  46693. var index = camera._postProcesses.indexOf(this);
  46694. if (index === 0 && camera._postProcesses.length > 0) {
  46695. this._camera._postProcesses[0].markTextureDirty();
  46696. }
  46697. this.onActivateObservable.clear();
  46698. this.onAfterRenderObservable.clear();
  46699. this.onApplyObservable.clear();
  46700. this.onBeforeRenderObservable.clear();
  46701. this.onSizeChangedObservable.clear();
  46702. };
  46703. return PostProcess;
  46704. }());
  46705. BABYLON.PostProcess = PostProcess;
  46706. })(BABYLON || (BABYLON = {}));
  46707. //# sourceMappingURL=babylon.postProcess.js.map
  46708. var BABYLON;
  46709. (function (BABYLON) {
  46710. var PassPostProcess = (function (_super) {
  46711. __extends(PassPostProcess, _super);
  46712. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  46713. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  46714. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  46715. }
  46716. return PassPostProcess;
  46717. }(BABYLON.PostProcess));
  46718. BABYLON.PassPostProcess = PassPostProcess;
  46719. })(BABYLON || (BABYLON = {}));
  46720. //# sourceMappingURL=babylon.passPostProcess.js.map
  46721. var BABYLON;
  46722. (function (BABYLON) {
  46723. var ShadowGenerator = (function () {
  46724. /**
  46725. * Creates a ShadowGenerator object.
  46726. * A ShadowGenerator is the required tool to use the shadows.
  46727. * Each light casting shadows needs to use its own ShadowGenerator.
  46728. * Required parameters :
  46729. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  46730. * - `light`: the light object generating the shadows.
  46731. * - `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.
  46732. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  46733. */
  46734. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  46735. // Members
  46736. this._bias = 0.00005;
  46737. this._blurBoxOffset = 1;
  46738. this._blurScale = 2;
  46739. this._blurKernel = 1;
  46740. this._useKernelBlur = false;
  46741. this._filter = ShadowGenerator.FILTER_NONE;
  46742. this._darkness = 0;
  46743. this._transparencyShadow = false;
  46744. /**
  46745. * Controls the extent to which the shadows fade out at the edge of the frustum
  46746. * Used only by directionals and spots
  46747. */
  46748. this.frustumEdgeFalloff = 0;
  46749. this.forceBackFacesOnly = false;
  46750. this._lightDirection = BABYLON.Vector3.Zero();
  46751. this._viewMatrix = BABYLON.Matrix.Zero();
  46752. this._projectionMatrix = BABYLON.Matrix.Zero();
  46753. this._transformMatrix = BABYLON.Matrix.Zero();
  46754. this._worldViewProjection = BABYLON.Matrix.Zero();
  46755. this._currentFaceIndex = 0;
  46756. this._currentFaceIndexCache = 0;
  46757. this._isCube = false;
  46758. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  46759. this._mapSize = mapSize;
  46760. this._light = light;
  46761. this._scene = light.getScene();
  46762. light._shadowGenerator = this;
  46763. // Texture type fallback from float to int if not supported.
  46764. var caps = this._scene.getEngine().getCaps();
  46765. if (!useFullFloatFirst) {
  46766. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  46767. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  46768. }
  46769. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  46770. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  46771. }
  46772. else {
  46773. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  46774. }
  46775. }
  46776. else {
  46777. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  46778. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  46779. }
  46780. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  46781. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  46782. }
  46783. else {
  46784. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  46785. }
  46786. }
  46787. this._initializeGenerator();
  46788. }
  46789. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  46790. // Static
  46791. get: function () {
  46792. return ShadowGenerator._FILTER_NONE;
  46793. },
  46794. enumerable: true,
  46795. configurable: true
  46796. });
  46797. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  46798. get: function () {
  46799. return ShadowGenerator._FILTER_POISSONSAMPLING;
  46800. },
  46801. enumerable: true,
  46802. configurable: true
  46803. });
  46804. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  46805. get: function () {
  46806. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  46807. },
  46808. enumerable: true,
  46809. configurable: true
  46810. });
  46811. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  46812. get: function () {
  46813. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  46814. },
  46815. enumerable: true,
  46816. configurable: true
  46817. });
  46818. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  46819. get: function () {
  46820. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  46821. },
  46822. enumerable: true,
  46823. configurable: true
  46824. });
  46825. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  46826. get: function () {
  46827. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  46828. },
  46829. enumerable: true,
  46830. configurable: true
  46831. });
  46832. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  46833. get: function () {
  46834. return this._bias;
  46835. },
  46836. set: function (bias) {
  46837. this._bias = bias;
  46838. },
  46839. enumerable: true,
  46840. configurable: true
  46841. });
  46842. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  46843. get: function () {
  46844. return this._blurBoxOffset;
  46845. },
  46846. set: function (value) {
  46847. if (this._blurBoxOffset === value) {
  46848. return;
  46849. }
  46850. this._blurBoxOffset = value;
  46851. this._disposeBlurPostProcesses();
  46852. },
  46853. enumerable: true,
  46854. configurable: true
  46855. });
  46856. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  46857. get: function () {
  46858. return this._blurScale;
  46859. },
  46860. set: function (value) {
  46861. if (this._blurScale === value) {
  46862. return;
  46863. }
  46864. this._blurScale = value;
  46865. this._disposeBlurPostProcesses();
  46866. },
  46867. enumerable: true,
  46868. configurable: true
  46869. });
  46870. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  46871. get: function () {
  46872. return this._blurKernel;
  46873. },
  46874. set: function (value) {
  46875. if (this._blurKernel === value) {
  46876. return;
  46877. }
  46878. this._blurKernel = value;
  46879. this._disposeBlurPostProcesses();
  46880. },
  46881. enumerable: true,
  46882. configurable: true
  46883. });
  46884. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  46885. get: function () {
  46886. return this._useKernelBlur;
  46887. },
  46888. set: function (value) {
  46889. if (this._useKernelBlur === value) {
  46890. return;
  46891. }
  46892. this._useKernelBlur = value;
  46893. this._disposeBlurPostProcesses();
  46894. },
  46895. enumerable: true,
  46896. configurable: true
  46897. });
  46898. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  46899. get: function () {
  46900. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  46901. },
  46902. set: function (value) {
  46903. this._depthScale = value;
  46904. },
  46905. enumerable: true,
  46906. configurable: true
  46907. });
  46908. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  46909. get: function () {
  46910. return this._filter;
  46911. },
  46912. set: function (value) {
  46913. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  46914. if (this._light.needCube()) {
  46915. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  46916. this.useExponentialShadowMap = true;
  46917. return;
  46918. }
  46919. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  46920. this.useCloseExponentialShadowMap = true;
  46921. return;
  46922. }
  46923. }
  46924. if (this._filter === value) {
  46925. return;
  46926. }
  46927. this._filter = value;
  46928. this._disposeBlurPostProcesses();
  46929. this._applyFilterValues();
  46930. this._light._markMeshesAsLightDirty();
  46931. },
  46932. enumerable: true,
  46933. configurable: true
  46934. });
  46935. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  46936. get: function () {
  46937. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  46938. },
  46939. set: function (value) {
  46940. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  46941. return;
  46942. }
  46943. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  46944. },
  46945. enumerable: true,
  46946. configurable: true
  46947. });
  46948. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  46949. get: function () {
  46950. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  46951. return this.useExponentialShadowMap;
  46952. },
  46953. set: function (value) {
  46954. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  46955. this.useExponentialShadowMap = value;
  46956. },
  46957. enumerable: true,
  46958. configurable: true
  46959. });
  46960. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  46961. get: function () {
  46962. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  46963. return this.useBlurExponentialShadowMap;
  46964. },
  46965. set: function (value) {
  46966. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  46967. this.useBlurExponentialShadowMap = value;
  46968. },
  46969. enumerable: true,
  46970. configurable: true
  46971. });
  46972. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  46973. get: function () {
  46974. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  46975. },
  46976. set: function (value) {
  46977. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  46978. return;
  46979. }
  46980. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  46981. },
  46982. enumerable: true,
  46983. configurable: true
  46984. });
  46985. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  46986. get: function () {
  46987. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  46988. },
  46989. set: function (value) {
  46990. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  46991. return;
  46992. }
  46993. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  46994. },
  46995. enumerable: true,
  46996. configurable: true
  46997. });
  46998. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  46999. get: function () {
  47000. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  47001. },
  47002. set: function (value) {
  47003. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  47004. return;
  47005. }
  47006. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  47007. },
  47008. enumerable: true,
  47009. configurable: true
  47010. });
  47011. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  47012. get: function () {
  47013. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  47014. },
  47015. set: function (value) {
  47016. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  47017. return;
  47018. }
  47019. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  47020. },
  47021. enumerable: true,
  47022. configurable: true
  47023. });
  47024. /**
  47025. * Returns the darkness value (float).
  47026. */
  47027. ShadowGenerator.prototype.getDarkness = function () {
  47028. return this._darkness;
  47029. };
  47030. /**
  47031. * Sets the ShadowGenerator darkness value (float <= 1.0).
  47032. * Returns the ShadowGenerator.
  47033. */
  47034. ShadowGenerator.prototype.setDarkness = function (darkness) {
  47035. if (darkness >= 1.0)
  47036. this._darkness = 1.0;
  47037. else if (darkness <= 0.0)
  47038. this._darkness = 0.0;
  47039. else
  47040. this._darkness = darkness;
  47041. return this;
  47042. };
  47043. /**
  47044. * Sets the ability to have transparent shadow (boolean).
  47045. * Returns the ShadowGenerator.
  47046. */
  47047. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  47048. this._transparencyShadow = hasShadow;
  47049. return this;
  47050. };
  47051. /**
  47052. * Returns a RenderTargetTexture object : the shadow map texture.
  47053. */
  47054. ShadowGenerator.prototype.getShadowMap = function () {
  47055. return this._shadowMap;
  47056. };
  47057. /**
  47058. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  47059. */
  47060. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  47061. if (this._shadowMap2) {
  47062. return this._shadowMap2;
  47063. }
  47064. return this._shadowMap;
  47065. };
  47066. /**
  47067. * Returns the associated light object.
  47068. */
  47069. ShadowGenerator.prototype.getLight = function () {
  47070. return this._light;
  47071. };
  47072. ShadowGenerator.prototype._initializeGenerator = function () {
  47073. this._light._markMeshesAsLightDirty();
  47074. this._initializeShadowMap();
  47075. };
  47076. ShadowGenerator.prototype._initializeShadowMap = function () {
  47077. var _this = this;
  47078. // Render target
  47079. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  47080. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47081. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47082. this._shadowMap.anisotropicFilteringLevel = 1;
  47083. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  47084. this._shadowMap.renderParticles = false;
  47085. // Record Face Index before render.
  47086. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  47087. _this._currentFaceIndex = faceIndex;
  47088. });
  47089. // Custom render function.
  47090. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  47091. // Blur if required afer render.
  47092. this._shadowMap.onAfterUnbindObservable.add(function () {
  47093. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  47094. return;
  47095. }
  47096. if (!_this._blurPostProcesses) {
  47097. _this._initializeBlurRTTAndPostProcesses();
  47098. }
  47099. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, _this.getShadowMapForRendering().getInternalTexture());
  47100. });
  47101. // Clear according to the chosen filter.
  47102. this._shadowMap.onClearObservable.add(function (engine) {
  47103. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  47104. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  47105. }
  47106. else {
  47107. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  47108. }
  47109. });
  47110. };
  47111. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  47112. var _this = this;
  47113. var engine = this._scene.getEngine();
  47114. var targetSize = this._mapSize / this.blurScale;
  47115. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  47116. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  47117. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47118. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47119. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  47120. }
  47121. if (this.useKernelBlur) {
  47122. 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);
  47123. this._kernelBlurXPostprocess.width = targetSize;
  47124. this._kernelBlurXPostprocess.height = targetSize;
  47125. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  47126. effect.setTexture("textureSampler", _this._shadowMap);
  47127. });
  47128. 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);
  47129. this._kernelBlurXPostprocess.autoClear = false;
  47130. this._kernelBlurYPostprocess.autoClear = false;
  47131. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  47132. this._kernelBlurXPostprocess.packedFloat = true;
  47133. this._kernelBlurYPostprocess.packedFloat = true;
  47134. }
  47135. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  47136. }
  47137. else {
  47138. 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);
  47139. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  47140. effect.setFloat2("screenSize", targetSize, targetSize);
  47141. effect.setTexture("textureSampler", _this._shadowMap);
  47142. });
  47143. this._boxBlurPostprocess.autoClear = false;
  47144. this._blurPostProcesses = [this._boxBlurPostprocess];
  47145. }
  47146. };
  47147. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  47148. var index;
  47149. for (index = 0; index < opaqueSubMeshes.length; index++) {
  47150. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  47151. }
  47152. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  47153. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  47154. }
  47155. if (this._transparencyShadow) {
  47156. for (index = 0; index < transparentSubMeshes.length; index++) {
  47157. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  47158. }
  47159. }
  47160. };
  47161. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  47162. var _this = this;
  47163. var mesh = subMesh.getRenderingMesh();
  47164. var scene = this._scene;
  47165. var engine = scene.getEngine();
  47166. // Culling
  47167. engine.setState(subMesh.getMaterial().backFaceCulling);
  47168. // Managing instances
  47169. var batch = mesh._getInstancesRenderList(subMesh._id);
  47170. if (batch.mustReturn) {
  47171. return;
  47172. }
  47173. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  47174. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  47175. engine.enableEffect(this._effect);
  47176. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  47177. var material = subMesh.getMaterial();
  47178. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  47179. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  47180. this._effect.setVector3("lightPosition", this.getLight().position);
  47181. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  47182. // Alpha test
  47183. if (material && material.needAlphaTesting()) {
  47184. var alphaTexture = material.getAlphaTestTexture();
  47185. if (alphaTexture) {
  47186. this._effect.setTexture("diffuseSampler", alphaTexture);
  47187. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  47188. }
  47189. }
  47190. // Bones
  47191. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47192. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  47193. }
  47194. if (this.forceBackFacesOnly) {
  47195. engine.setState(true, 0, false, true);
  47196. }
  47197. // Draw
  47198. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  47199. if (this.forceBackFacesOnly) {
  47200. engine.setState(true, 0, false, false);
  47201. }
  47202. }
  47203. else {
  47204. // Need to reset refresh rate of the shadowMap
  47205. this._shadowMap.resetRefreshCounter();
  47206. }
  47207. };
  47208. ShadowGenerator.prototype._applyFilterValues = function () {
  47209. if (this.filter === ShadowGenerator.FILTER_NONE) {
  47210. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  47211. }
  47212. else {
  47213. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  47214. }
  47215. };
  47216. /**
  47217. * Force shader compilation including textures ready check
  47218. */
  47219. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  47220. var _this = this;
  47221. var scene = this._scene;
  47222. var engine = scene.getEngine();
  47223. var subMeshes = new Array();
  47224. var currentIndex = 0;
  47225. for (var _i = 0, _a = this.getShadowMap().renderList; _i < _a.length; _i++) {
  47226. var mesh = _a[_i];
  47227. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  47228. }
  47229. var checkReady = function () {
  47230. if (!_this._scene || !_this._scene.getEngine()) {
  47231. return;
  47232. }
  47233. var subMesh = subMeshes[currentIndex];
  47234. if (_this.isReady(subMesh, options ? options.useInstances : false)) {
  47235. currentIndex++;
  47236. if (currentIndex >= subMeshes.length) {
  47237. if (onCompiled) {
  47238. onCompiled(_this);
  47239. }
  47240. return;
  47241. }
  47242. }
  47243. setTimeout(checkReady, 16);
  47244. };
  47245. if (subMeshes.length > 0) {
  47246. checkReady();
  47247. }
  47248. };
  47249. /**
  47250. * Boolean : true when the ShadowGenerator is finally computed.
  47251. */
  47252. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  47253. var defines = [];
  47254. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  47255. defines.push("#define FLOAT");
  47256. }
  47257. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  47258. defines.push("#define ESM");
  47259. }
  47260. var attribs = [BABYLON.VertexBuffer.PositionKind];
  47261. var mesh = subMesh.getMesh();
  47262. var material = subMesh.getMaterial();
  47263. // Alpha test
  47264. if (material && material.needAlphaTesting()) {
  47265. var alphaTexture = material.getAlphaTestTexture();
  47266. if (alphaTexture) {
  47267. defines.push("#define ALPHATEST");
  47268. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  47269. attribs.push(BABYLON.VertexBuffer.UVKind);
  47270. defines.push("#define UV1");
  47271. }
  47272. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  47273. if (alphaTexture.coordinatesIndex === 1) {
  47274. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  47275. defines.push("#define UV2");
  47276. }
  47277. }
  47278. }
  47279. }
  47280. // Bones
  47281. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47282. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  47283. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  47284. if (mesh.numBoneInfluencers > 4) {
  47285. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  47286. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  47287. }
  47288. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47289. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47290. }
  47291. else {
  47292. defines.push("#define NUM_BONE_INFLUENCERS 0");
  47293. }
  47294. // Instances
  47295. if (useInstances) {
  47296. defines.push("#define INSTANCES");
  47297. attribs.push("world0");
  47298. attribs.push("world1");
  47299. attribs.push("world2");
  47300. attribs.push("world3");
  47301. }
  47302. // Get correct effect
  47303. var join = defines.join("\n");
  47304. if (this._cachedDefines !== join) {
  47305. this._cachedDefines = join;
  47306. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  47307. }
  47308. return this._effect.isReady();
  47309. };
  47310. /**
  47311. * This creates the defines related to the standard BJS materials.
  47312. */
  47313. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  47314. var scene = this._scene;
  47315. var light = this._light;
  47316. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  47317. return;
  47318. }
  47319. defines["SHADOW" + lightIndex] = true;
  47320. if (this.usePoissonSampling) {
  47321. defines["SHADOWPCF" + lightIndex] = true;
  47322. }
  47323. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  47324. defines["SHADOWESM" + lightIndex] = true;
  47325. }
  47326. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  47327. defines["SHADOWCLOSEESM" + lightIndex] = true;
  47328. }
  47329. if (light.needCube()) {
  47330. defines["SHADOWCUBE" + lightIndex] = true;
  47331. }
  47332. };
  47333. /**
  47334. * This binds shadow lights related to the standard BJS materials.
  47335. * It implies the unifroms available on the materials are the standard BJS ones.
  47336. */
  47337. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  47338. var light = this._light;
  47339. var scene = this._scene;
  47340. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  47341. return;
  47342. }
  47343. if (!light.needCube()) {
  47344. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  47345. }
  47346. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  47347. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / this.getShadowMap().getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  47348. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera), lightIndex);
  47349. };
  47350. // Methods
  47351. /**
  47352. * Returns a Matrix object : the updated transformation matrix.
  47353. */
  47354. ShadowGenerator.prototype.getTransformMatrix = function () {
  47355. var scene = this._scene;
  47356. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  47357. return this._transformMatrix;
  47358. }
  47359. this._currentRenderID = scene.getRenderId();
  47360. this._currentFaceIndexCache = this._currentFaceIndex;
  47361. var lightPosition = this._light.position;
  47362. if (this._light.computeTransformedInformation()) {
  47363. lightPosition = this._light.transformedPosition;
  47364. }
  47365. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  47366. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  47367. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  47368. }
  47369. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  47370. this._cachedPosition = lightPosition.clone();
  47371. this._cachedDirection = this._lightDirection.clone();
  47372. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  47373. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  47374. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  47375. }
  47376. return this._transformMatrix;
  47377. };
  47378. ShadowGenerator.prototype.recreateShadowMap = function () {
  47379. // Track render list.
  47380. var renderList = this._shadowMap.renderList;
  47381. // Clean up existing data.
  47382. this._disposeRTTandPostProcesses();
  47383. // Reinitializes.
  47384. this._initializeGenerator();
  47385. // Reaffect the filter to ensure a correct fallback if necessary.
  47386. this.filter = this.filter;
  47387. // Reaffect the filter.
  47388. this._applyFilterValues();
  47389. // Reaffect Render List.
  47390. this._shadowMap.renderList = renderList;
  47391. };
  47392. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  47393. if (this._shadowMap2) {
  47394. this._shadowMap2.dispose();
  47395. this._shadowMap2 = null;
  47396. }
  47397. if (this._downSamplePostprocess) {
  47398. this._downSamplePostprocess.dispose();
  47399. this._downSamplePostprocess = null;
  47400. }
  47401. if (this._boxBlurPostprocess) {
  47402. this._boxBlurPostprocess.dispose();
  47403. this._boxBlurPostprocess = null;
  47404. }
  47405. if (this._kernelBlurXPostprocess) {
  47406. this._kernelBlurXPostprocess.dispose();
  47407. this._kernelBlurXPostprocess = null;
  47408. }
  47409. if (this._kernelBlurYPostprocess) {
  47410. this._kernelBlurYPostprocess.dispose();
  47411. this._kernelBlurYPostprocess = null;
  47412. }
  47413. this._blurPostProcesses = null;
  47414. };
  47415. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  47416. if (this._shadowMap) {
  47417. this._shadowMap.dispose();
  47418. this._shadowMap = null;
  47419. }
  47420. this._disposeBlurPostProcesses();
  47421. };
  47422. /**
  47423. * Disposes the ShadowGenerator.
  47424. * Returns nothing.
  47425. */
  47426. ShadowGenerator.prototype.dispose = function () {
  47427. this._disposeRTTandPostProcesses();
  47428. this._light._shadowGenerator = null;
  47429. this._light._markMeshesAsLightDirty();
  47430. };
  47431. /**
  47432. * Serializes the ShadowGenerator and returns a serializationObject.
  47433. */
  47434. ShadowGenerator.prototype.serialize = function () {
  47435. var serializationObject = {};
  47436. var shadowMap = this.getShadowMap();
  47437. serializationObject.lightId = this._light.id;
  47438. serializationObject.mapSize = shadowMap.getRenderSize();
  47439. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  47440. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  47441. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  47442. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  47443. serializationObject.usePoissonSampling = this.usePoissonSampling;
  47444. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  47445. serializationObject.depthScale = this.depthScale;
  47446. serializationObject.darkness = this.getDarkness();
  47447. serializationObject.blurBoxOffset = this.blurBoxOffset;
  47448. serializationObject.blurKernel = this.blurKernel;
  47449. serializationObject.blurScale = this.blurScale;
  47450. serializationObject.useKernelBlur = this.useKernelBlur;
  47451. serializationObject.transparencyShadow = this._transparencyShadow;
  47452. serializationObject.renderList = [];
  47453. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  47454. var mesh = shadowMap.renderList[meshIndex];
  47455. serializationObject.renderList.push(mesh.id);
  47456. }
  47457. return serializationObject;
  47458. };
  47459. /**
  47460. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  47461. */
  47462. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  47463. //casting to point light, as light is missing the position attr and typescript complains.
  47464. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  47465. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  47466. var shadowMap = shadowGenerator.getShadowMap();
  47467. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  47468. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  47469. meshes.forEach(function (mesh) {
  47470. shadowMap.renderList.push(mesh);
  47471. });
  47472. }
  47473. if (parsedShadowGenerator.usePoissonSampling) {
  47474. shadowGenerator.usePoissonSampling = true;
  47475. }
  47476. else if (parsedShadowGenerator.useExponentialShadowMap) {
  47477. shadowGenerator.useExponentialShadowMap = true;
  47478. }
  47479. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  47480. shadowGenerator.useBlurExponentialShadowMap = true;
  47481. }
  47482. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  47483. shadowGenerator.useCloseExponentialShadowMap = true;
  47484. }
  47485. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  47486. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  47487. }
  47488. else if (parsedShadowGenerator.useVarianceShadowMap) {
  47489. shadowGenerator.useExponentialShadowMap = true;
  47490. }
  47491. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  47492. shadowGenerator.useBlurExponentialShadowMap = true;
  47493. }
  47494. if (parsedShadowGenerator.depthScale) {
  47495. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  47496. }
  47497. if (parsedShadowGenerator.blurScale) {
  47498. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  47499. }
  47500. if (parsedShadowGenerator.blurBoxOffset) {
  47501. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  47502. }
  47503. if (parsedShadowGenerator.useKernelBlur) {
  47504. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  47505. }
  47506. if (parsedShadowGenerator.blurKernel) {
  47507. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  47508. }
  47509. if (parsedShadowGenerator.bias !== undefined) {
  47510. shadowGenerator.bias = parsedShadowGenerator.bias;
  47511. }
  47512. if (parsedShadowGenerator.darkness) {
  47513. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  47514. }
  47515. if (parsedShadowGenerator.transparencyShadow) {
  47516. shadowGenerator.setTransparencyShadow(true);
  47517. }
  47518. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  47519. return shadowGenerator;
  47520. };
  47521. ShadowGenerator._FILTER_NONE = 0;
  47522. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  47523. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  47524. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  47525. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  47526. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  47527. return ShadowGenerator;
  47528. }());
  47529. BABYLON.ShadowGenerator = ShadowGenerator;
  47530. })(BABYLON || (BABYLON = {}));
  47531. //# sourceMappingURL=babylon.shadowGenerator.js.map
  47532. var BABYLON;
  47533. (function (BABYLON) {
  47534. var DefaultLoadingScreen = (function () {
  47535. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  47536. if (_loadingText === void 0) { _loadingText = ""; }
  47537. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  47538. var _this = this;
  47539. this._renderingCanvas = _renderingCanvas;
  47540. this._loadingText = _loadingText;
  47541. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  47542. // Resize
  47543. this._resizeLoadingUI = function () {
  47544. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  47545. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  47546. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  47547. _this._loadingDiv.style.left = canvasRect.left + "px";
  47548. _this._loadingDiv.style.top = canvasRect.top + "px";
  47549. _this._loadingDiv.style.width = canvasRect.width + "px";
  47550. _this._loadingDiv.style.height = canvasRect.height + "px";
  47551. };
  47552. }
  47553. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  47554. if (this._loadingDiv) {
  47555. // Do not add a loading screen if there is already one
  47556. return;
  47557. }
  47558. this._loadingDiv = document.createElement("div");
  47559. this._loadingDiv.id = "babylonjsLoadingDiv";
  47560. this._loadingDiv.style.opacity = "0";
  47561. this._loadingDiv.style.transition = "opacity 1.5s ease";
  47562. // Loading text
  47563. this._loadingTextDiv = document.createElement("div");
  47564. this._loadingTextDiv.style.position = "absolute";
  47565. this._loadingTextDiv.style.left = "0";
  47566. this._loadingTextDiv.style.top = "50%";
  47567. this._loadingTextDiv.style.marginTop = "80px";
  47568. this._loadingTextDiv.style.width = "100%";
  47569. this._loadingTextDiv.style.height = "20px";
  47570. this._loadingTextDiv.style.fontFamily = "Arial";
  47571. this._loadingTextDiv.style.fontSize = "14px";
  47572. this._loadingTextDiv.style.color = "white";
  47573. this._loadingTextDiv.style.textAlign = "center";
  47574. this._loadingTextDiv.innerHTML = "Loading";
  47575. this._loadingDiv.appendChild(this._loadingTextDiv);
  47576. //set the predefined text
  47577. this._loadingTextDiv.innerHTML = this._loadingText;
  47578. // Generating keyframes
  47579. var style = document.createElement('style');
  47580. style.type = 'text/css';
  47581. 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 }";
  47582. style.innerHTML = keyFrames;
  47583. document.getElementsByTagName('head')[0].appendChild(style);
  47584. // Loading img
  47585. var imgBack = new Image();
  47586. 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";
  47587. imgBack.style.position = "absolute";
  47588. imgBack.style.left = "50%";
  47589. imgBack.style.top = "50%";
  47590. imgBack.style.marginLeft = "-60px";
  47591. imgBack.style.marginTop = "-60px";
  47592. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  47593. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  47594. imgBack.style.transformOrigin = "50% 50%";
  47595. imgBack.style.webkitTransformOrigin = "50% 50%";
  47596. this._loadingDiv.appendChild(imgBack);
  47597. this._resizeLoadingUI();
  47598. window.addEventListener("resize", this._resizeLoadingUI);
  47599. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  47600. document.body.appendChild(this._loadingDiv);
  47601. this._loadingDiv.style.opacity = "1";
  47602. };
  47603. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  47604. var _this = this;
  47605. if (!this._loadingDiv) {
  47606. return;
  47607. }
  47608. var onTransitionEnd = function () {
  47609. if (!_this._loadingDiv) {
  47610. return;
  47611. }
  47612. document.body.removeChild(_this._loadingDiv);
  47613. window.removeEventListener("resize", _this._resizeLoadingUI);
  47614. _this._loadingDiv = null;
  47615. };
  47616. this._loadingDiv.style.opacity = "0";
  47617. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  47618. };
  47619. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  47620. set: function (text) {
  47621. this._loadingText = text;
  47622. if (this._loadingTextDiv) {
  47623. this._loadingTextDiv.innerHTML = this._loadingText;
  47624. }
  47625. },
  47626. enumerable: true,
  47627. configurable: true
  47628. });
  47629. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  47630. get: function () {
  47631. return this._loadingDivBackgroundColor;
  47632. },
  47633. set: function (color) {
  47634. this._loadingDivBackgroundColor = color;
  47635. if (!this._loadingDiv) {
  47636. return;
  47637. }
  47638. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  47639. },
  47640. enumerable: true,
  47641. configurable: true
  47642. });
  47643. return DefaultLoadingScreen;
  47644. }());
  47645. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  47646. })(BABYLON || (BABYLON = {}));
  47647. //# sourceMappingURL=babylon.loadingScreen.js.map
  47648. var BABYLON;
  47649. (function (BABYLON) {
  47650. var SceneLoader = (function () {
  47651. function SceneLoader() {
  47652. }
  47653. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  47654. get: function () {
  47655. return 0;
  47656. },
  47657. enumerable: true,
  47658. configurable: true
  47659. });
  47660. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  47661. get: function () {
  47662. return 1;
  47663. },
  47664. enumerable: true,
  47665. configurable: true
  47666. });
  47667. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  47668. get: function () {
  47669. return 2;
  47670. },
  47671. enumerable: true,
  47672. configurable: true
  47673. });
  47674. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  47675. get: function () {
  47676. return 3;
  47677. },
  47678. enumerable: true,
  47679. configurable: true
  47680. });
  47681. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  47682. get: function () {
  47683. return SceneLoader._ForceFullSceneLoadingForIncremental;
  47684. },
  47685. set: function (value) {
  47686. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  47687. },
  47688. enumerable: true,
  47689. configurable: true
  47690. });
  47691. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  47692. get: function () {
  47693. return SceneLoader._ShowLoadingScreen;
  47694. },
  47695. set: function (value) {
  47696. SceneLoader._ShowLoadingScreen = value;
  47697. },
  47698. enumerable: true,
  47699. configurable: true
  47700. });
  47701. Object.defineProperty(SceneLoader, "loggingLevel", {
  47702. get: function () {
  47703. return SceneLoader._loggingLevel;
  47704. },
  47705. set: function (value) {
  47706. SceneLoader._loggingLevel = value;
  47707. },
  47708. enumerable: true,
  47709. configurable: true
  47710. });
  47711. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  47712. get: function () {
  47713. return SceneLoader._CleanBoneMatrixWeights;
  47714. },
  47715. set: function (value) {
  47716. SceneLoader._CleanBoneMatrixWeights = value;
  47717. },
  47718. enumerable: true,
  47719. configurable: true
  47720. });
  47721. SceneLoader._getDefaultPlugin = function () {
  47722. return SceneLoader._registeredPlugins[".babylon"];
  47723. };
  47724. SceneLoader._getPluginForExtension = function (extension) {
  47725. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  47726. if (registeredPlugin) {
  47727. return registeredPlugin;
  47728. }
  47729. return SceneLoader._getDefaultPlugin();
  47730. };
  47731. SceneLoader._getPluginForDirectLoad = function (data) {
  47732. for (var extension in SceneLoader._registeredPlugins) {
  47733. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  47734. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  47735. return SceneLoader._registeredPlugins[extension];
  47736. }
  47737. }
  47738. return SceneLoader._getDefaultPlugin();
  47739. };
  47740. SceneLoader._getPluginForFilename = function (sceneFilename) {
  47741. if (sceneFilename.name) {
  47742. sceneFilename = sceneFilename.name;
  47743. }
  47744. var dotPosition = sceneFilename.lastIndexOf(".");
  47745. var queryStringPosition = sceneFilename.indexOf("?");
  47746. if (queryStringPosition === -1) {
  47747. queryStringPosition = sceneFilename.length;
  47748. }
  47749. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  47750. return SceneLoader._getPluginForExtension(extension);
  47751. };
  47752. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  47753. SceneLoader._getDirectLoad = function (sceneFilename) {
  47754. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  47755. return sceneFilename.substr(5);
  47756. }
  47757. return null;
  47758. };
  47759. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  47760. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  47761. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename);
  47762. var plugin = registeredPlugin.plugin;
  47763. var useArrayBuffer = registeredPlugin.isBinary;
  47764. var database;
  47765. SceneLoader.OnPluginActivatedObservable.notifyObservers(registeredPlugin.plugin);
  47766. var dataCallback = function (data) {
  47767. if (scene.isDisposed) {
  47768. onError("Scene has been disposed");
  47769. return;
  47770. }
  47771. scene.database = database;
  47772. try {
  47773. onSuccess(plugin, data);
  47774. }
  47775. catch (e) {
  47776. onError(null, e);
  47777. }
  47778. };
  47779. var manifestChecked = function (success) {
  47780. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) {
  47781. onError(request.status + " " + request.statusText);
  47782. });
  47783. };
  47784. if (directLoad) {
  47785. dataCallback(directLoad);
  47786. return;
  47787. }
  47788. if (rootUrl.indexOf("file:") === -1) {
  47789. if (scene.getEngine().enableOfflineSupport) {
  47790. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  47791. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  47792. }
  47793. else {
  47794. manifestChecked(true);
  47795. }
  47796. }
  47797. else {
  47798. BABYLON.Tools.ReadFile(sceneFilename, dataCallback, onProgress, useArrayBuffer);
  47799. }
  47800. };
  47801. // Public functions
  47802. SceneLoader.GetPluginForExtension = function (extension) {
  47803. return SceneLoader._getPluginForExtension(extension).plugin;
  47804. };
  47805. SceneLoader.RegisterPlugin = function (plugin) {
  47806. if (typeof plugin.extensions === "string") {
  47807. var extension = plugin.extensions;
  47808. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  47809. plugin: plugin,
  47810. isBinary: false
  47811. };
  47812. }
  47813. else {
  47814. var extensions = plugin.extensions;
  47815. Object.keys(extensions).forEach(function (extension) {
  47816. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  47817. plugin: plugin,
  47818. isBinary: extensions[extension].isBinary
  47819. };
  47820. });
  47821. }
  47822. };
  47823. /**
  47824. * Import meshes into a scene
  47825. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  47826. * @param rootUrl a string that defines the root url for scene and resources
  47827. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  47828. * @param scene the instance of BABYLON.Scene to append to
  47829. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  47830. * @param onProgress a callback with a progress event for each file being loaded
  47831. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  47832. */
  47833. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  47834. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  47835. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  47836. return;
  47837. }
  47838. var loadingToken = {};
  47839. scene._addPendingData(loadingToken);
  47840. var errorHandler = function (message, exception) {
  47841. if (onError) {
  47842. onError(scene, "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : ""));
  47843. }
  47844. scene._removePendingData(loadingToken);
  47845. };
  47846. var progressHandler = function (event) {
  47847. if (onProgress) {
  47848. onProgress(event);
  47849. }
  47850. };
  47851. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  47852. if (plugin.importMesh) {
  47853. var syncedPlugin = plugin;
  47854. var meshes = [];
  47855. var particleSystems = [];
  47856. var skeletons = [];
  47857. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  47858. return;
  47859. }
  47860. if (onSuccess) {
  47861. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  47862. onSuccess(meshes, particleSystems, skeletons);
  47863. scene._removePendingData(loadingToken);
  47864. }
  47865. }
  47866. else {
  47867. var asyncedPlugin = plugin;
  47868. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  47869. if (onSuccess) {
  47870. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  47871. onSuccess(meshes, particleSystems, skeletons);
  47872. scene._removePendingData(loadingToken);
  47873. }
  47874. }, progressHandler, errorHandler);
  47875. }
  47876. }, progressHandler, errorHandler);
  47877. };
  47878. /**
  47879. * Load a scene
  47880. * @param rootUrl a string that defines the root url for scene and resources
  47881. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  47882. * @param engine is the instance of BABYLON.Engine to use to create the scene
  47883. * @param onSuccess a callback with the scene when import succeeds
  47884. * @param onProgress a callback with a progress event for each file being loaded
  47885. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  47886. */
  47887. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError) {
  47888. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError);
  47889. };
  47890. /**
  47891. * Append a scene
  47892. * @param rootUrl a string that defines the root url for scene and resources
  47893. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  47894. * @param scene is the instance of BABYLON.Scene to append to
  47895. * @param onSuccess a callback with the scene when import succeeds
  47896. * @param onProgress a callback with a progress event for each file being loaded
  47897. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  47898. */
  47899. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  47900. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  47901. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  47902. return;
  47903. }
  47904. if (SceneLoader.ShowLoadingScreen) {
  47905. scene.getEngine().displayLoadingUI();
  47906. }
  47907. var loadingToken = {};
  47908. scene._addPendingData(loadingToken);
  47909. var errorHandler = function (message, exception) {
  47910. if (onError) {
  47911. onError(scene, "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : ""));
  47912. }
  47913. scene._removePendingData(loadingToken);
  47914. scene.getEngine().hideLoadingUI();
  47915. };
  47916. var progressHandler = function (event) {
  47917. if (onProgress) {
  47918. onProgress(event);
  47919. }
  47920. };
  47921. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  47922. if (plugin.load) {
  47923. var syncedPlugin = plugin;
  47924. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  47925. return;
  47926. }
  47927. if (onSuccess) {
  47928. onSuccess(scene);
  47929. }
  47930. scene.loadingPluginName = plugin.name;
  47931. scene._removePendingData(loadingToken);
  47932. }
  47933. else {
  47934. var asyncedPlugin = plugin;
  47935. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  47936. if (onSuccess) {
  47937. onSuccess(scene);
  47938. }
  47939. scene.loadingPluginName = plugin.name;
  47940. scene._removePendingData(loadingToken);
  47941. }, progressHandler, errorHandler);
  47942. }
  47943. if (SceneLoader.ShowLoadingScreen) {
  47944. scene.executeWhenReady(function () {
  47945. scene.getEngine().hideLoadingUI();
  47946. });
  47947. }
  47948. }, progressHandler, errorHandler);
  47949. };
  47950. // Flags
  47951. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  47952. SceneLoader._ShowLoadingScreen = true;
  47953. SceneLoader._CleanBoneMatrixWeights = false;
  47954. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  47955. // Members
  47956. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  47957. SceneLoader._registeredPlugins = {};
  47958. return SceneLoader;
  47959. }());
  47960. BABYLON.SceneLoader = SceneLoader;
  47961. ;
  47962. })(BABYLON || (BABYLON = {}));
  47963. //# sourceMappingURL=babylon.sceneLoader.js.map
  47964. var BABYLON;
  47965. (function (BABYLON) {
  47966. var Internals;
  47967. (function (Internals) {
  47968. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  47969. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  47970. var parsedMaterial = parsedData.materials[index];
  47971. if (parsedMaterial.id === id) {
  47972. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  47973. }
  47974. }
  47975. return null;
  47976. };
  47977. var isDescendantOf = function (mesh, names, hierarchyIds) {
  47978. for (var i in names) {
  47979. if (mesh.name === names[i]) {
  47980. hierarchyIds.push(mesh.id);
  47981. return true;
  47982. }
  47983. }
  47984. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  47985. hierarchyIds.push(mesh.id);
  47986. return true;
  47987. }
  47988. return false;
  47989. };
  47990. var logOperation = function (operation, producer) {
  47991. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  47992. };
  47993. BABYLON.SceneLoader.RegisterPlugin({
  47994. name: "babylon.js",
  47995. extensions: ".babylon",
  47996. canDirectLoad: function (data) {
  47997. if (data.indexOf("babylon") !== -1) {
  47998. return true;
  47999. }
  48000. return false;
  48001. },
  48002. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  48003. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  48004. // when SceneLoader.debugLogging = true (default), or exception encountered.
  48005. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  48006. // and avoid problems with multiple concurrent .babylon loads.
  48007. var log = "importMesh has failed JSON parse";
  48008. try {
  48009. var parsedData = JSON.parse(data);
  48010. log = "";
  48011. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  48012. if (!meshesNames) {
  48013. meshesNames = null;
  48014. }
  48015. else if (!Array.isArray(meshesNames)) {
  48016. meshesNames = [meshesNames];
  48017. }
  48018. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  48019. var loadedSkeletonsIds = [];
  48020. var loadedMaterialsIds = [];
  48021. var hierarchyIds = [];
  48022. var index;
  48023. var cache;
  48024. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  48025. var parsedMesh = parsedData.meshes[index];
  48026. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  48027. if (meshesNames !== null) {
  48028. // Remove found mesh name from list.
  48029. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  48030. }
  48031. //Geometry?
  48032. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  48033. //does the file contain geometries?
  48034. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  48035. //find the correct geometry and add it to the scene
  48036. var found = false;
  48037. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  48038. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  48039. return;
  48040. }
  48041. else {
  48042. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  48043. if (parsedGeometryData.id === parsedMesh.geometryId) {
  48044. switch (geometryType) {
  48045. case "boxes":
  48046. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  48047. break;
  48048. case "spheres":
  48049. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  48050. break;
  48051. case "cylinders":
  48052. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  48053. break;
  48054. case "toruses":
  48055. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  48056. break;
  48057. case "grounds":
  48058. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  48059. break;
  48060. case "planes":
  48061. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  48062. break;
  48063. case "torusKnots":
  48064. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  48065. break;
  48066. case "vertexData":
  48067. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  48068. break;
  48069. }
  48070. found = true;
  48071. }
  48072. });
  48073. }
  48074. });
  48075. if (found === false) {
  48076. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  48077. }
  48078. }
  48079. }
  48080. // Material ?
  48081. if (parsedMesh.materialId) {
  48082. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  48083. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  48084. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  48085. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  48086. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  48087. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  48088. var subMatId = parsedMultiMaterial.materials[matIndex];
  48089. loadedMaterialsIds.push(subMatId);
  48090. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  48091. log += "\n\tMaterial " + mat.toString(fullDetails);
  48092. }
  48093. loadedMaterialsIds.push(parsedMultiMaterial.id);
  48094. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  48095. materialFound = true;
  48096. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  48097. break;
  48098. }
  48099. }
  48100. }
  48101. if (materialFound === false) {
  48102. loadedMaterialsIds.push(parsedMesh.materialId);
  48103. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  48104. if (!mat) {
  48105. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  48106. }
  48107. else {
  48108. log += "\n\tMaterial " + mat.toString(fullDetails);
  48109. }
  48110. }
  48111. }
  48112. // Skeleton ?
  48113. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  48114. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  48115. if (skeletonAlreadyLoaded === false) {
  48116. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  48117. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  48118. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  48119. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  48120. skeletons.push(skeleton);
  48121. loadedSkeletonsIds.push(parsedSkeleton.id);
  48122. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  48123. }
  48124. }
  48125. }
  48126. }
  48127. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  48128. meshes.push(mesh);
  48129. log += "\n\tMesh " + mesh.toString(fullDetails);
  48130. }
  48131. }
  48132. // Connecting parents
  48133. var currentMesh;
  48134. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  48135. currentMesh = scene.meshes[index];
  48136. if (currentMesh._waitingParentId) {
  48137. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  48138. currentMesh._waitingParentId = undefined;
  48139. }
  48140. }
  48141. // freeze and compute world matrix application
  48142. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  48143. currentMesh = scene.meshes[index];
  48144. if (currentMesh._waitingFreezeWorldMatrix) {
  48145. currentMesh.freezeWorldMatrix();
  48146. currentMesh._waitingFreezeWorldMatrix = undefined;
  48147. }
  48148. else {
  48149. currentMesh.computeWorldMatrix(true);
  48150. }
  48151. }
  48152. }
  48153. // Particles
  48154. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  48155. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  48156. var parsedParticleSystem = parsedData.particleSystems[index];
  48157. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  48158. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  48159. }
  48160. }
  48161. }
  48162. return true;
  48163. }
  48164. catch (err) {
  48165. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  48166. log = null;
  48167. throw err;
  48168. }
  48169. finally {
  48170. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  48171. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  48172. }
  48173. }
  48174. },
  48175. load: function (scene, data, rootUrl) {
  48176. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  48177. // when SceneLoader.debugLogging = true (default), or exception encountered.
  48178. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  48179. // and avoid problems with multiple concurrent .babylon loads.
  48180. var log = "importScene has failed JSON parse";
  48181. try {
  48182. var parsedData = JSON.parse(data);
  48183. log = "";
  48184. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  48185. // Scene
  48186. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  48187. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  48188. }
  48189. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  48190. scene.autoClear = parsedData.autoClear;
  48191. }
  48192. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  48193. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  48194. }
  48195. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  48196. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  48197. }
  48198. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  48199. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  48200. }
  48201. // Fog
  48202. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  48203. scene.fogMode = parsedData.fogMode;
  48204. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  48205. scene.fogStart = parsedData.fogStart;
  48206. scene.fogEnd = parsedData.fogEnd;
  48207. scene.fogDensity = parsedData.fogDensity;
  48208. log += "\tFog mode for scene: ";
  48209. switch (scene.fogMode) {
  48210. // getters not compiling, so using hardcoded
  48211. case 1:
  48212. log += "exp\n";
  48213. break;
  48214. case 2:
  48215. log += "exp2\n";
  48216. break;
  48217. case 3:
  48218. log += "linear\n";
  48219. break;
  48220. }
  48221. }
  48222. //Physics
  48223. if (parsedData.physicsEnabled) {
  48224. var physicsPlugin;
  48225. if (parsedData.physicsEngine === "cannon") {
  48226. physicsPlugin = new BABYLON.CannonJSPlugin();
  48227. }
  48228. else if (parsedData.physicsEngine === "oimo") {
  48229. physicsPlugin = new BABYLON.OimoJSPlugin();
  48230. }
  48231. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  48232. //else - default engine, which is currently oimo
  48233. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  48234. scene.enablePhysics(physicsGravity, physicsPlugin);
  48235. }
  48236. // Metadata
  48237. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  48238. scene.metadata = parsedData.metadata;
  48239. }
  48240. //collisions, if defined. otherwise, default is true
  48241. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  48242. scene.collisionsEnabled = parsedData.collisionsEnabled;
  48243. }
  48244. scene.workerCollisions = !!parsedData.workerCollisions;
  48245. var index;
  48246. var cache;
  48247. // Lights
  48248. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  48249. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  48250. var parsedLight = parsedData.lights[index];
  48251. var light = BABYLON.Light.Parse(parsedLight, scene);
  48252. log += (index === 0 ? "\n\tLights:" : "");
  48253. log += "\n\t\t" + light.toString(fullDetails);
  48254. }
  48255. }
  48256. // Animations
  48257. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  48258. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  48259. var parsedAnimation = parsedData.animations[index];
  48260. var animation = BABYLON.Animation.Parse(parsedAnimation);
  48261. scene.animations.push(animation);
  48262. log += (index === 0 ? "\n\tAnimations:" : "");
  48263. log += "\n\t\t" + animation.toString(fullDetails);
  48264. }
  48265. }
  48266. if (parsedData.autoAnimate) {
  48267. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  48268. }
  48269. // Materials
  48270. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  48271. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  48272. var parsedMaterial = parsedData.materials[index];
  48273. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  48274. log += (index === 0 ? "\n\tMaterials:" : "");
  48275. log += "\n\t\t" + mat.toString(fullDetails);
  48276. }
  48277. }
  48278. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  48279. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  48280. var parsedMultiMaterial = parsedData.multiMaterials[index];
  48281. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  48282. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  48283. log += "\n\t\t" + mmat.toString(fullDetails);
  48284. }
  48285. }
  48286. // Morph targets
  48287. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  48288. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  48289. var managerData = _a[_i];
  48290. var parsedManager = BABYLON.MorphTargetManager.Parse(managerData, scene);
  48291. }
  48292. }
  48293. // Skeletons
  48294. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  48295. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  48296. var parsedSkeleton = parsedData.skeletons[index];
  48297. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  48298. log += (index === 0 ? "\n\tSkeletons:" : "");
  48299. log += "\n\t\t" + skeleton.toString(fullDetails);
  48300. }
  48301. }
  48302. // Geometries
  48303. var geometries = parsedData.geometries;
  48304. if (geometries !== undefined && geometries !== null) {
  48305. // Boxes
  48306. var boxes = geometries.boxes;
  48307. if (boxes !== undefined && boxes !== null) {
  48308. for (index = 0, cache = boxes.length; index < cache; index++) {
  48309. var parsedBox = boxes[index];
  48310. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  48311. }
  48312. }
  48313. // Spheres
  48314. var spheres = geometries.spheres;
  48315. if (spheres !== undefined && spheres !== null) {
  48316. for (index = 0, cache = spheres.length; index < cache; index++) {
  48317. var parsedSphere = spheres[index];
  48318. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  48319. }
  48320. }
  48321. // Cylinders
  48322. var cylinders = geometries.cylinders;
  48323. if (cylinders !== undefined && cylinders !== null) {
  48324. for (index = 0, cache = cylinders.length; index < cache; index++) {
  48325. var parsedCylinder = cylinders[index];
  48326. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  48327. }
  48328. }
  48329. // Toruses
  48330. var toruses = geometries.toruses;
  48331. if (toruses !== undefined && toruses !== null) {
  48332. for (index = 0, cache = toruses.length; index < cache; index++) {
  48333. var parsedTorus = toruses[index];
  48334. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  48335. }
  48336. }
  48337. // Grounds
  48338. var grounds = geometries.grounds;
  48339. if (grounds !== undefined && grounds !== null) {
  48340. for (index = 0, cache = grounds.length; index < cache; index++) {
  48341. var parsedGround = grounds[index];
  48342. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  48343. }
  48344. }
  48345. // Planes
  48346. var planes = geometries.planes;
  48347. if (planes !== undefined && planes !== null) {
  48348. for (index = 0, cache = planes.length; index < cache; index++) {
  48349. var parsedPlane = planes[index];
  48350. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  48351. }
  48352. }
  48353. // TorusKnots
  48354. var torusKnots = geometries.torusKnots;
  48355. if (torusKnots !== undefined && torusKnots !== null) {
  48356. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  48357. var parsedTorusKnot = torusKnots[index];
  48358. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  48359. }
  48360. }
  48361. // VertexData
  48362. var vertexData = geometries.vertexData;
  48363. if (vertexData !== undefined && vertexData !== null) {
  48364. for (index = 0, cache = vertexData.length; index < cache; index++) {
  48365. var parsedVertexData = vertexData[index];
  48366. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  48367. }
  48368. }
  48369. }
  48370. // Meshes
  48371. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  48372. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  48373. var parsedMesh = parsedData.meshes[index];
  48374. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  48375. log += (index === 0 ? "\n\tMeshes:" : "");
  48376. log += "\n\t\t" + mesh.toString(fullDetails);
  48377. }
  48378. }
  48379. // Cameras
  48380. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  48381. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  48382. var parsedCamera = parsedData.cameras[index];
  48383. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  48384. log += (index === 0 ? "\n\tCameras:" : "");
  48385. log += "\n\t\t" + camera.toString(fullDetails);
  48386. }
  48387. }
  48388. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  48389. scene.setActiveCameraByID(parsedData.activeCameraID);
  48390. }
  48391. // Browsing all the graph to connect the dots
  48392. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  48393. var camera = scene.cameras[index];
  48394. if (camera._waitingParentId) {
  48395. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  48396. camera._waitingParentId = undefined;
  48397. }
  48398. }
  48399. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  48400. var light = scene.lights[index];
  48401. if (light._waitingParentId) {
  48402. light.parent = scene.getLastEntryByID(light._waitingParentId);
  48403. light._waitingParentId = undefined;
  48404. }
  48405. }
  48406. // Sounds
  48407. var loadedSounds = [];
  48408. var loadedSound;
  48409. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  48410. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  48411. var parsedSound = parsedData.sounds[index];
  48412. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48413. if (!parsedSound.url)
  48414. parsedSound.url = parsedSound.name;
  48415. if (!loadedSounds[parsedSound.url]) {
  48416. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  48417. loadedSounds[parsedSound.url] = loadedSound;
  48418. }
  48419. else {
  48420. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  48421. }
  48422. }
  48423. else {
  48424. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  48425. }
  48426. }
  48427. }
  48428. loadedSounds = [];
  48429. // Connect parents & children and parse actions
  48430. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  48431. var mesh = scene.meshes[index];
  48432. if (mesh._waitingParentId) {
  48433. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  48434. mesh._waitingParentId = undefined;
  48435. }
  48436. if (mesh._waitingActions) {
  48437. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  48438. mesh._waitingActions = undefined;
  48439. }
  48440. }
  48441. // freeze world matrix application
  48442. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  48443. var currentMesh = scene.meshes[index];
  48444. if (currentMesh._waitingFreezeWorldMatrix) {
  48445. currentMesh.freezeWorldMatrix();
  48446. currentMesh._waitingFreezeWorldMatrix = undefined;
  48447. }
  48448. else {
  48449. currentMesh.computeWorldMatrix(true);
  48450. }
  48451. }
  48452. // Particles Systems
  48453. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  48454. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  48455. var parsedParticleSystem = parsedData.particleSystems[index];
  48456. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  48457. }
  48458. }
  48459. // Lens flares
  48460. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  48461. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  48462. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  48463. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  48464. }
  48465. }
  48466. // Shadows
  48467. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  48468. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  48469. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  48470. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  48471. }
  48472. }
  48473. // Lights exclusions / inclusions
  48474. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  48475. var light = scene.lights[index];
  48476. // Excluded check
  48477. if (light._excludedMeshesIds.length > 0) {
  48478. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  48479. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  48480. if (excludedMesh) {
  48481. light.excludedMeshes.push(excludedMesh);
  48482. }
  48483. }
  48484. light._excludedMeshesIds = [];
  48485. }
  48486. // Included check
  48487. if (light._includedOnlyMeshesIds.length > 0) {
  48488. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  48489. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  48490. if (includedOnlyMesh) {
  48491. light.includedOnlyMeshes.push(includedOnlyMesh);
  48492. }
  48493. }
  48494. light._includedOnlyMeshesIds = [];
  48495. }
  48496. }
  48497. // Actions (scene)
  48498. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  48499. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  48500. }
  48501. // Finish
  48502. return true;
  48503. }
  48504. catch (err) {
  48505. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  48506. log = null;
  48507. throw err;
  48508. }
  48509. finally {
  48510. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  48511. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  48512. }
  48513. }
  48514. }
  48515. });
  48516. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48517. })(BABYLON || (BABYLON = {}));
  48518. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  48519. var BABYLON;
  48520. (function (BABYLON) {
  48521. var FilesInput = (function () {
  48522. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback) {
  48523. this._engine = engine;
  48524. this._currentScene = scene;
  48525. this._sceneLoadedCallback = sceneLoadedCallback;
  48526. this._progressCallback = progressCallback;
  48527. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  48528. this._textureLoadingCallback = textureLoadingCallback;
  48529. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  48530. this._onReloadCallback = onReloadCallback;
  48531. }
  48532. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  48533. var _this = this;
  48534. if (elementToMonitor) {
  48535. this._elementToMonitor = elementToMonitor;
  48536. this._dragEnterHandler = function (e) { _this.drag(e); };
  48537. this._dragOverHandler = function (e) { _this.drag(e); };
  48538. this._dropHandler = function (e) { _this.drop(e); };
  48539. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  48540. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  48541. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  48542. }
  48543. };
  48544. FilesInput.prototype.dispose = function () {
  48545. if (!this._elementToMonitor) {
  48546. return;
  48547. }
  48548. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  48549. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  48550. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  48551. };
  48552. FilesInput.prototype.renderFunction = function () {
  48553. if (this._additionalRenderLoopLogicCallback) {
  48554. this._additionalRenderLoopLogicCallback();
  48555. }
  48556. if (this._currentScene) {
  48557. if (this._textureLoadingCallback) {
  48558. var remaining = this._currentScene.getWaitingItemsCount();
  48559. if (remaining > 0) {
  48560. this._textureLoadingCallback(remaining);
  48561. }
  48562. }
  48563. this._currentScene.render();
  48564. }
  48565. };
  48566. FilesInput.prototype.drag = function (e) {
  48567. e.stopPropagation();
  48568. e.preventDefault();
  48569. };
  48570. FilesInput.prototype.drop = function (eventDrop) {
  48571. eventDrop.stopPropagation();
  48572. eventDrop.preventDefault();
  48573. this.loadFiles(eventDrop);
  48574. };
  48575. FilesInput.prototype._handleFolderDrop = function (entry, files, callback) {
  48576. var reader = entry.createReader(), relativePath = entry.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  48577. reader.readEntries(function (fileEntries) {
  48578. var remaining = fileEntries.length;
  48579. for (var _i = 0, fileEntries_1 = fileEntries; _i < fileEntries_1.length; _i++) {
  48580. var fileEntry = fileEntries_1[_i];
  48581. if (fileEntry.isFile) {
  48582. fileEntry.file(function (file) {
  48583. file.correctName = relativePath + file.name;
  48584. files.push(file);
  48585. remaining--;
  48586. if (remaining === 0) {
  48587. callback();
  48588. }
  48589. });
  48590. }
  48591. else {
  48592. remaining--;
  48593. if (remaining === 0) {
  48594. callback();
  48595. }
  48596. }
  48597. }
  48598. });
  48599. };
  48600. FilesInput.prototype._processFiles = function (files) {
  48601. for (var i = 0; i < files.length; i++) {
  48602. var name = files[i].correctName.toLowerCase();
  48603. var extension = name.split('.').pop();
  48604. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  48605. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  48606. this._sceneFileToLoad = files[i];
  48607. }
  48608. else {
  48609. FilesInput.FilesToLoad[name] = files[i];
  48610. }
  48611. }
  48612. if (this._onReloadCallback) {
  48613. this._onReloadCallback(this._sceneFileToLoad);
  48614. }
  48615. else {
  48616. this.reload();
  48617. }
  48618. };
  48619. FilesInput.prototype.loadFiles = function (event) {
  48620. var _this = this;
  48621. if (this._startingProcessingFilesCallback)
  48622. this._startingProcessingFilesCallback();
  48623. // Handling data transfer via drag'n'drop
  48624. if (event && event.dataTransfer && event.dataTransfer.files) {
  48625. this._filesToLoad = event.dataTransfer.files;
  48626. }
  48627. // Handling files from input files
  48628. if (event && event.target && event.target.files) {
  48629. this._filesToLoad = event.target.files;
  48630. }
  48631. if (this._filesToLoad && this._filesToLoad.length > 0) {
  48632. var files_1 = [];
  48633. var folders = [];
  48634. var items = event.dataTransfer ? event.dataTransfer.items : null;
  48635. for (var i = 0; i < this._filesToLoad.length; i++) {
  48636. var fileToLoad = this._filesToLoad[i];
  48637. var name_1 = fileToLoad.name.toLowerCase();
  48638. var type = fileToLoad.type;
  48639. var entry = void 0;
  48640. fileToLoad.correctName = name_1;
  48641. if (items) {
  48642. var item = items[i];
  48643. if (item.getAsEntry) {
  48644. entry = item.getAsEntry();
  48645. }
  48646. else if (item.webkitGetAsEntry) {
  48647. entry = item.webkitGetAsEntry();
  48648. }
  48649. }
  48650. if (!entry) {
  48651. files_1.push(fileToLoad);
  48652. }
  48653. else {
  48654. if (entry.isDirectory) {
  48655. folders.push(entry);
  48656. }
  48657. else {
  48658. files_1.push(fileToLoad);
  48659. }
  48660. }
  48661. }
  48662. if (folders.length === 0) {
  48663. this._processFiles(files_1);
  48664. }
  48665. else {
  48666. var remaining = folders.length;
  48667. // Extract folder content
  48668. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  48669. var folder = folders_1[_i];
  48670. this._handleFolderDrop(folder, files_1, function () {
  48671. remaining--;
  48672. if (remaining === 0) {
  48673. _this._processFiles(files_1);
  48674. }
  48675. });
  48676. }
  48677. }
  48678. }
  48679. };
  48680. FilesInput.prototype.reload = function () {
  48681. var _this = this;
  48682. // If a ".babylon" file has been provided
  48683. if (this._sceneFileToLoad) {
  48684. if (this._currentScene) {
  48685. if (BABYLON.Tools.errorsCount > 0) {
  48686. BABYLON.Tools.ClearLogCache();
  48687. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  48688. }
  48689. this._engine.stopRenderLoop();
  48690. this._currentScene.dispose();
  48691. }
  48692. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  48693. _this._currentScene = newScene;
  48694. if (_this._sceneLoadedCallback) {
  48695. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  48696. }
  48697. // Wait for textures and shaders to be ready
  48698. _this._currentScene.executeWhenReady(function () {
  48699. _this._engine.runRenderLoop(function () {
  48700. _this.renderFunction();
  48701. });
  48702. });
  48703. }, function (progress) {
  48704. if (_this._progressCallback) {
  48705. _this._progressCallback(progress);
  48706. }
  48707. });
  48708. }
  48709. else {
  48710. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  48711. }
  48712. };
  48713. FilesInput.FilesToLoad = new Array();
  48714. return FilesInput;
  48715. }());
  48716. BABYLON.FilesInput = FilesInput;
  48717. })(BABYLON || (BABYLON = {}));
  48718. //# sourceMappingURL=babylon.filesInput.js.map
  48719. var BABYLON;
  48720. (function (BABYLON) {
  48721. /**
  48722. * This class implement a typical dictionary using a string as key and the generic type T as value.
  48723. * The underlying implementation relies on an associative array to ensure the best performances.
  48724. * The value can be anything including 'null' but except 'undefined'
  48725. */
  48726. var StringDictionary = (function () {
  48727. function StringDictionary() {
  48728. this._count = 0;
  48729. this._data = {};
  48730. }
  48731. /**
  48732. * This will clear this dictionary and copy the content from the 'source' one.
  48733. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  48734. * @param source the dictionary to take the content from and copy to this dictionary
  48735. */
  48736. StringDictionary.prototype.copyFrom = function (source) {
  48737. var _this = this;
  48738. this.clear();
  48739. source.forEach(function (t, v) { return _this.add(t, v); });
  48740. };
  48741. /**
  48742. * Get a value based from its key
  48743. * @param key the given key to get the matching value from
  48744. * @return the value if found, otherwise undefined is returned
  48745. */
  48746. StringDictionary.prototype.get = function (key) {
  48747. var val = this._data[key];
  48748. if (val !== undefined) {
  48749. return val;
  48750. }
  48751. return undefined;
  48752. };
  48753. /**
  48754. * Get a value from its key or add it if it doesn't exist.
  48755. * This method will ensure you that a given key/data will be present in the dictionary.
  48756. * @param key the given key to get the matching value from
  48757. * @param factory the factory that will create the value if the key is not present in the dictionary.
  48758. * The factory will only be invoked if there's no data for the given key.
  48759. * @return the value corresponding to the key.
  48760. */
  48761. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  48762. var val = this.get(key);
  48763. if (val !== undefined) {
  48764. return val;
  48765. }
  48766. val = factory(key);
  48767. if (val) {
  48768. this.add(key, val);
  48769. }
  48770. return val;
  48771. };
  48772. /**
  48773. * Get a value from its key if present in the dictionary otherwise add it
  48774. * @param key the key to get the value from
  48775. * @param val if there's no such key/value pair in the dictionary add it with this value
  48776. * @return the value corresponding to the key
  48777. */
  48778. StringDictionary.prototype.getOrAdd = function (key, val) {
  48779. var curVal = this.get(key);
  48780. if (curVal !== undefined) {
  48781. return curVal;
  48782. }
  48783. this.add(key, val);
  48784. return val;
  48785. };
  48786. /**
  48787. * Check if there's a given key in the dictionary
  48788. * @param key the key to check for
  48789. * @return true if the key is present, false otherwise
  48790. */
  48791. StringDictionary.prototype.contains = function (key) {
  48792. return this._data[key] !== undefined;
  48793. };
  48794. /**
  48795. * Add a new key and its corresponding value
  48796. * @param key the key to add
  48797. * @param value the value corresponding to the key
  48798. * @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
  48799. */
  48800. StringDictionary.prototype.add = function (key, value) {
  48801. if (this._data[key] !== undefined) {
  48802. return false;
  48803. }
  48804. this._data[key] = value;
  48805. ++this._count;
  48806. return true;
  48807. };
  48808. StringDictionary.prototype.set = function (key, value) {
  48809. if (this._data[key] === undefined) {
  48810. return false;
  48811. }
  48812. this._data[key] = value;
  48813. return true;
  48814. };
  48815. /**
  48816. * Get the element of the given key and remove it from the dictionary
  48817. * @param key
  48818. */
  48819. StringDictionary.prototype.getAndRemove = function (key) {
  48820. var val = this.get(key);
  48821. if (val !== undefined) {
  48822. delete this._data[key];
  48823. --this._count;
  48824. return val;
  48825. }
  48826. return null;
  48827. };
  48828. /**
  48829. * Remove a key/value from the dictionary.
  48830. * @param key the key to remove
  48831. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  48832. */
  48833. StringDictionary.prototype.remove = function (key) {
  48834. if (this.contains(key)) {
  48835. delete this._data[key];
  48836. --this._count;
  48837. return true;
  48838. }
  48839. return false;
  48840. };
  48841. /**
  48842. * Clear the whole content of the dictionary
  48843. */
  48844. StringDictionary.prototype.clear = function () {
  48845. this._data = {};
  48846. this._count = 0;
  48847. };
  48848. Object.defineProperty(StringDictionary.prototype, "count", {
  48849. get: function () {
  48850. return this._count;
  48851. },
  48852. enumerable: true,
  48853. configurable: true
  48854. });
  48855. /**
  48856. * Execute a callback on each key/val of the dictionary.
  48857. * Note that you can remove any element in this dictionary in the callback implementation
  48858. * @param callback the callback to execute on a given key/value pair
  48859. */
  48860. StringDictionary.prototype.forEach = function (callback) {
  48861. for (var cur in this._data) {
  48862. var val = this._data[cur];
  48863. callback(cur, val);
  48864. }
  48865. };
  48866. /**
  48867. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  48868. * If the callback returns null or undefined the method will iterate to the next key/value pair
  48869. * Note that you can remove any element in this dictionary in the callback implementation
  48870. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  48871. */
  48872. StringDictionary.prototype.first = function (callback) {
  48873. for (var cur in this._data) {
  48874. var val = this._data[cur];
  48875. var res = callback(cur, val);
  48876. if (res) {
  48877. return res;
  48878. }
  48879. }
  48880. return null;
  48881. };
  48882. return StringDictionary;
  48883. }());
  48884. BABYLON.StringDictionary = StringDictionary;
  48885. })(BABYLON || (BABYLON = {}));
  48886. //# sourceMappingURL=babylon.stringDictionary.js.map
  48887. var BABYLON;
  48888. (function (BABYLON) {
  48889. var Tags = (function () {
  48890. function Tags() {
  48891. }
  48892. Tags.EnableFor = function (obj) {
  48893. obj._tags = obj._tags || {};
  48894. obj.hasTags = function () {
  48895. return Tags.HasTags(obj);
  48896. };
  48897. obj.addTags = function (tagsString) {
  48898. return Tags.AddTagsTo(obj, tagsString);
  48899. };
  48900. obj.removeTags = function (tagsString) {
  48901. return Tags.RemoveTagsFrom(obj, tagsString);
  48902. };
  48903. obj.matchesTagsQuery = function (tagsQuery) {
  48904. return Tags.MatchesQuery(obj, tagsQuery);
  48905. };
  48906. };
  48907. Tags.DisableFor = function (obj) {
  48908. delete obj._tags;
  48909. delete obj.hasTags;
  48910. delete obj.addTags;
  48911. delete obj.removeTags;
  48912. delete obj.matchesTagsQuery;
  48913. };
  48914. Tags.HasTags = function (obj) {
  48915. if (!obj._tags) {
  48916. return false;
  48917. }
  48918. return !BABYLON.Tools.IsEmpty(obj._tags);
  48919. };
  48920. Tags.GetTags = function (obj, asString) {
  48921. if (asString === void 0) { asString = true; }
  48922. if (!obj._tags) {
  48923. return null;
  48924. }
  48925. if (asString) {
  48926. var tagsArray = [];
  48927. for (var tag in obj._tags) {
  48928. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  48929. tagsArray.push(tag);
  48930. }
  48931. }
  48932. return tagsArray.join(" ");
  48933. }
  48934. else {
  48935. return obj._tags;
  48936. }
  48937. };
  48938. // the tags 'true' and 'false' are reserved and cannot be used as tags
  48939. // a tag cannot start with '||', '&&', and '!'
  48940. // it cannot contain whitespaces
  48941. Tags.AddTagsTo = function (obj, tagsString) {
  48942. if (!tagsString) {
  48943. return;
  48944. }
  48945. if (typeof tagsString !== "string") {
  48946. return;
  48947. }
  48948. var tags = tagsString.split(" ");
  48949. tags.forEach(function (tag, index, array) {
  48950. Tags._AddTagTo(obj, tag);
  48951. });
  48952. };
  48953. Tags._AddTagTo = function (obj, tag) {
  48954. tag = tag.trim();
  48955. if (tag === "" || tag === "true" || tag === "false") {
  48956. return;
  48957. }
  48958. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  48959. return;
  48960. }
  48961. Tags.EnableFor(obj);
  48962. obj._tags[tag] = true;
  48963. };
  48964. Tags.RemoveTagsFrom = function (obj, tagsString) {
  48965. if (!Tags.HasTags(obj)) {
  48966. return;
  48967. }
  48968. var tags = tagsString.split(" ");
  48969. for (var t in tags) {
  48970. Tags._RemoveTagFrom(obj, tags[t]);
  48971. }
  48972. };
  48973. Tags._RemoveTagFrom = function (obj, tag) {
  48974. delete obj._tags[tag];
  48975. };
  48976. Tags.MatchesQuery = function (obj, tagsQuery) {
  48977. if (tagsQuery === undefined) {
  48978. return true;
  48979. }
  48980. if (tagsQuery === "") {
  48981. return Tags.HasTags(obj);
  48982. }
  48983. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  48984. };
  48985. return Tags;
  48986. }());
  48987. BABYLON.Tags = Tags;
  48988. })(BABYLON || (BABYLON = {}));
  48989. //# sourceMappingURL=babylon.tags.js.map
  48990. var BABYLON;
  48991. (function (BABYLON) {
  48992. var Internals;
  48993. (function (Internals) {
  48994. var AndOrNotEvaluator = (function () {
  48995. function AndOrNotEvaluator() {
  48996. }
  48997. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  48998. if (!query.match(/\([^\(\)]*\)/g)) {
  48999. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  49000. }
  49001. else {
  49002. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  49003. // remove parenthesis
  49004. r = r.slice(1, r.length - 1);
  49005. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  49006. });
  49007. }
  49008. if (query === "true") {
  49009. return true;
  49010. }
  49011. if (query === "false") {
  49012. return false;
  49013. }
  49014. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  49015. };
  49016. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  49017. evaluateCallback = evaluateCallback || (function (r) {
  49018. return r === "true" ? true : false;
  49019. });
  49020. var result;
  49021. var or = parenthesisContent.split("||");
  49022. for (var i in or) {
  49023. if (or.hasOwnProperty(i)) {
  49024. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  49025. var and = ori.split("&&");
  49026. if (and.length > 1) {
  49027. for (var j = 0; j < and.length; ++j) {
  49028. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  49029. if (andj !== "true" && andj !== "false") {
  49030. if (andj[0] === "!") {
  49031. result = !evaluateCallback(andj.substring(1));
  49032. }
  49033. else {
  49034. result = evaluateCallback(andj);
  49035. }
  49036. }
  49037. else {
  49038. result = andj === "true" ? true : false;
  49039. }
  49040. if (!result) {
  49041. ori = "false";
  49042. break;
  49043. }
  49044. }
  49045. }
  49046. if (result || ori === "true") {
  49047. result = true;
  49048. break;
  49049. }
  49050. // result equals false (or undefined)
  49051. if (ori !== "true" && ori !== "false") {
  49052. if (ori[0] === "!") {
  49053. result = !evaluateCallback(ori.substring(1));
  49054. }
  49055. else {
  49056. result = evaluateCallback(ori);
  49057. }
  49058. }
  49059. else {
  49060. result = ori === "true" ? true : false;
  49061. }
  49062. }
  49063. }
  49064. // the whole parenthesis scope is replaced by 'true' or 'false'
  49065. return result ? "true" : "false";
  49066. };
  49067. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  49068. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  49069. // remove whitespaces
  49070. r = r.replace(/[\s]/g, function () { return ""; });
  49071. return r.length % 2 ? "!" : "";
  49072. });
  49073. booleanString = booleanString.trim();
  49074. if (booleanString === "!true") {
  49075. booleanString = "false";
  49076. }
  49077. else if (booleanString === "!false") {
  49078. booleanString = "true";
  49079. }
  49080. return booleanString;
  49081. };
  49082. return AndOrNotEvaluator;
  49083. }());
  49084. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  49085. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49086. })(BABYLON || (BABYLON = {}));
  49087. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  49088. var BABYLON;
  49089. (function (BABYLON) {
  49090. var Database = (function () {
  49091. function Database(urlToScene, callbackManifestChecked) {
  49092. // Handling various flavors of prefixed version of IndexedDB
  49093. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  49094. this.callbackManifestChecked = callbackManifestChecked;
  49095. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  49096. this.db = null;
  49097. this.enableSceneOffline = false;
  49098. this.enableTexturesOffline = false;
  49099. this.manifestVersionFound = 0;
  49100. this.mustUpdateRessources = false;
  49101. this.hasReachedQuota = false;
  49102. if (!Database.IDBStorageEnabled) {
  49103. this.callbackManifestChecked(true);
  49104. }
  49105. else {
  49106. this.checkManifestFile();
  49107. }
  49108. }
  49109. Database.prototype.checkManifestFile = function () {
  49110. var _this = this;
  49111. function noManifestFile() {
  49112. that.enableSceneOffline = false;
  49113. that.enableTexturesOffline = false;
  49114. that.callbackManifestChecked(false);
  49115. }
  49116. var that = this;
  49117. var timeStampUsed = false;
  49118. var manifestURL = this.currentSceneUrl + ".manifest";
  49119. var xhr = new XMLHttpRequest();
  49120. if (navigator.onLine) {
  49121. // Adding a timestamp to by-pass browsers' cache
  49122. timeStampUsed = true;
  49123. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  49124. }
  49125. xhr.open("GET", manifestURL, true);
  49126. xhr.addEventListener("load", function () {
  49127. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  49128. try {
  49129. var manifestFile = JSON.parse(xhr.response);
  49130. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  49131. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  49132. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  49133. _this.manifestVersionFound = manifestFile.version;
  49134. }
  49135. if (_this.callbackManifestChecked) {
  49136. _this.callbackManifestChecked(true);
  49137. }
  49138. }
  49139. catch (ex) {
  49140. noManifestFile();
  49141. }
  49142. }
  49143. else {
  49144. noManifestFile();
  49145. }
  49146. }, false);
  49147. xhr.addEventListener("error", function (event) {
  49148. if (timeStampUsed) {
  49149. timeStampUsed = false;
  49150. // Let's retry without the timeStamp
  49151. // It could fail when coupled with HTML5 Offline API
  49152. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  49153. xhr.open("GET", retryManifestURL, true);
  49154. xhr.send();
  49155. }
  49156. else {
  49157. noManifestFile();
  49158. }
  49159. }, false);
  49160. try {
  49161. xhr.send();
  49162. }
  49163. catch (ex) {
  49164. BABYLON.Tools.Error("Error on XHR send request.");
  49165. that.callbackManifestChecked(false);
  49166. }
  49167. };
  49168. Database.prototype.openAsync = function (successCallback, errorCallback) {
  49169. var _this = this;
  49170. function handleError() {
  49171. that.isSupported = false;
  49172. if (errorCallback)
  49173. errorCallback();
  49174. }
  49175. var that = this;
  49176. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  49177. // Your browser doesn't support IndexedDB
  49178. this.isSupported = false;
  49179. if (errorCallback)
  49180. errorCallback();
  49181. }
  49182. else {
  49183. // If the DB hasn't been opened or created yet
  49184. if (!this.db) {
  49185. this.hasReachedQuota = false;
  49186. this.isSupported = true;
  49187. var request = this.idbFactory.open("babylonjs", 1);
  49188. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  49189. request.onerror = function (event) {
  49190. handleError();
  49191. };
  49192. // executes when a version change transaction cannot complete due to other active transactions
  49193. request.onblocked = function (event) {
  49194. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  49195. handleError();
  49196. };
  49197. // DB has been opened successfully
  49198. request.onsuccess = function (event) {
  49199. _this.db = request.result;
  49200. successCallback();
  49201. };
  49202. // Initialization of the DB. Creating Scenes & Textures stores
  49203. request.onupgradeneeded = function (event) {
  49204. _this.db = (event.target).result;
  49205. try {
  49206. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  49207. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  49208. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  49209. }
  49210. catch (ex) {
  49211. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  49212. handleError();
  49213. }
  49214. };
  49215. }
  49216. else {
  49217. if (successCallback)
  49218. successCallback();
  49219. }
  49220. }
  49221. };
  49222. Database.prototype.loadImageFromDB = function (url, image) {
  49223. var _this = this;
  49224. var completeURL = Database.ReturnFullUrlLocation(url);
  49225. var saveAndLoadImage = function () {
  49226. if (!_this.hasReachedQuota && _this.db !== null) {
  49227. // the texture is not yet in the DB, let's try to save it
  49228. _this._saveImageIntoDBAsync(completeURL, image);
  49229. }
  49230. else {
  49231. image.src = url;
  49232. }
  49233. };
  49234. if (!this.mustUpdateRessources) {
  49235. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  49236. }
  49237. else {
  49238. saveAndLoadImage();
  49239. }
  49240. };
  49241. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  49242. if (this.isSupported && this.db !== null) {
  49243. var texture;
  49244. var transaction = this.db.transaction(["textures"]);
  49245. transaction.onabort = function (event) {
  49246. image.src = url;
  49247. };
  49248. transaction.oncomplete = function (event) {
  49249. var blobTextureURL;
  49250. if (texture) {
  49251. var URL = window.URL || window.webkitURL;
  49252. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  49253. image.onerror = function () {
  49254. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  49255. image.src = url;
  49256. };
  49257. image.src = blobTextureURL;
  49258. }
  49259. else {
  49260. notInDBCallback();
  49261. }
  49262. };
  49263. var getRequest = transaction.objectStore("textures").get(url);
  49264. getRequest.onsuccess = function (event) {
  49265. texture = (event.target).result;
  49266. };
  49267. getRequest.onerror = function (event) {
  49268. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  49269. image.src = url;
  49270. };
  49271. }
  49272. else {
  49273. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  49274. image.src = url;
  49275. }
  49276. };
  49277. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  49278. var _this = this;
  49279. if (this.isSupported) {
  49280. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  49281. var generateBlobUrl = function () {
  49282. var blobTextureURL;
  49283. if (blob) {
  49284. var URL = window.URL || window.webkitURL;
  49285. try {
  49286. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  49287. }
  49288. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  49289. catch (ex) {
  49290. blobTextureURL = URL.createObjectURL(blob);
  49291. }
  49292. }
  49293. image.src = blobTextureURL;
  49294. };
  49295. if (Database.IsUASupportingBlobStorage) {
  49296. var xhr = new XMLHttpRequest(), blob;
  49297. xhr.open("GET", url, true);
  49298. xhr.responseType = "blob";
  49299. xhr.addEventListener("load", function () {
  49300. if (xhr.status === 200) {
  49301. // Blob as response (XHR2)
  49302. blob = xhr.response;
  49303. var transaction = _this.db.transaction(["textures"], "readwrite");
  49304. // the transaction could abort because of a QuotaExceededError error
  49305. transaction.onabort = function (event) {
  49306. try {
  49307. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  49308. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  49309. _this.hasReachedQuota = true;
  49310. }
  49311. }
  49312. catch (ex) { }
  49313. generateBlobUrl();
  49314. };
  49315. transaction.oncomplete = function (event) {
  49316. generateBlobUrl();
  49317. };
  49318. var newTexture = { textureUrl: url, data: blob };
  49319. try {
  49320. // Put the blob into the dabase
  49321. var addRequest = transaction.objectStore("textures").put(newTexture);
  49322. addRequest.onsuccess = function (event) {
  49323. };
  49324. addRequest.onerror = function (event) {
  49325. generateBlobUrl();
  49326. };
  49327. }
  49328. catch (ex) {
  49329. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  49330. if (ex.code === 25) {
  49331. Database.IsUASupportingBlobStorage = false;
  49332. }
  49333. image.src = url;
  49334. }
  49335. }
  49336. else {
  49337. image.src = url;
  49338. }
  49339. }, false);
  49340. xhr.addEventListener("error", function (event) {
  49341. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  49342. image.src = url;
  49343. }, false);
  49344. xhr.send();
  49345. }
  49346. else {
  49347. image.src = url;
  49348. }
  49349. }
  49350. else {
  49351. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  49352. image.src = url;
  49353. }
  49354. };
  49355. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  49356. var _this = this;
  49357. var updateVersion = function (event) {
  49358. // the version is not yet in the DB or we need to update it
  49359. _this._saveVersionIntoDBAsync(url, versionLoaded);
  49360. };
  49361. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  49362. };
  49363. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  49364. var _this = this;
  49365. if (this.isSupported) {
  49366. var version;
  49367. try {
  49368. var transaction = this.db.transaction(["versions"]);
  49369. transaction.oncomplete = function (event) {
  49370. if (version) {
  49371. // If the version in the JSON file is > than the version in DB
  49372. if (_this.manifestVersionFound > version.data) {
  49373. _this.mustUpdateRessources = true;
  49374. updateInDBCallback();
  49375. }
  49376. else {
  49377. callback(version.data);
  49378. }
  49379. }
  49380. else {
  49381. _this.mustUpdateRessources = true;
  49382. updateInDBCallback();
  49383. }
  49384. };
  49385. transaction.onabort = function (event) {
  49386. callback(-1);
  49387. };
  49388. var getRequest = transaction.objectStore("versions").get(url);
  49389. getRequest.onsuccess = function (event) {
  49390. version = (event.target).result;
  49391. };
  49392. getRequest.onerror = function (event) {
  49393. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  49394. callback(-1);
  49395. };
  49396. }
  49397. catch (ex) {
  49398. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  49399. callback(-1);
  49400. }
  49401. }
  49402. else {
  49403. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  49404. callback(-1);
  49405. }
  49406. };
  49407. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  49408. var _this = this;
  49409. if (this.isSupported && !this.hasReachedQuota) {
  49410. try {
  49411. // Open a transaction to the database
  49412. var transaction = this.db.transaction(["versions"], "readwrite");
  49413. // the transaction could abort because of a QuotaExceededError error
  49414. transaction.onabort = function (event) {
  49415. try {
  49416. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  49417. _this.hasReachedQuota = true;
  49418. }
  49419. }
  49420. catch (ex) { }
  49421. callback(-1);
  49422. };
  49423. transaction.oncomplete = function (event) {
  49424. callback(_this.manifestVersionFound);
  49425. };
  49426. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  49427. // Put the scene into the database
  49428. var addRequest = transaction.objectStore("versions").put(newVersion);
  49429. addRequest.onsuccess = function (event) {
  49430. };
  49431. addRequest.onerror = function (event) {
  49432. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  49433. };
  49434. }
  49435. catch (ex) {
  49436. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  49437. callback(-1);
  49438. }
  49439. }
  49440. else {
  49441. callback(-1);
  49442. }
  49443. };
  49444. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  49445. var _this = this;
  49446. var completeUrl = Database.ReturnFullUrlLocation(url);
  49447. var saveAndLoadFile = function (event) {
  49448. // the scene is not yet in the DB, let's try to save it
  49449. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  49450. };
  49451. this._checkVersionFromDB(completeUrl, function (version) {
  49452. if (version !== -1) {
  49453. if (!_this.mustUpdateRessources) {
  49454. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  49455. }
  49456. else {
  49457. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  49458. }
  49459. }
  49460. else {
  49461. errorCallback();
  49462. }
  49463. });
  49464. };
  49465. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  49466. if (this.isSupported) {
  49467. var targetStore;
  49468. if (url.indexOf(".babylon") !== -1) {
  49469. targetStore = "scenes";
  49470. }
  49471. else {
  49472. targetStore = "textures";
  49473. }
  49474. var file;
  49475. var transaction = this.db.transaction([targetStore]);
  49476. transaction.oncomplete = function (event) {
  49477. if (file) {
  49478. callback(file.data);
  49479. }
  49480. else {
  49481. notInDBCallback();
  49482. }
  49483. };
  49484. transaction.onabort = function (event) {
  49485. notInDBCallback();
  49486. };
  49487. var getRequest = transaction.objectStore(targetStore).get(url);
  49488. getRequest.onsuccess = function (event) {
  49489. file = (event.target).result;
  49490. };
  49491. getRequest.onerror = function (event) {
  49492. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  49493. notInDBCallback();
  49494. };
  49495. }
  49496. else {
  49497. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  49498. callback();
  49499. }
  49500. };
  49501. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  49502. var _this = this;
  49503. if (this.isSupported) {
  49504. var targetStore;
  49505. if (url.indexOf(".babylon") !== -1) {
  49506. targetStore = "scenes";
  49507. }
  49508. else {
  49509. targetStore = "textures";
  49510. }
  49511. // Create XHR
  49512. var xhr = new XMLHttpRequest(), fileData;
  49513. xhr.open("GET", url, true);
  49514. if (useArrayBuffer) {
  49515. xhr.responseType = "arraybuffer";
  49516. }
  49517. xhr.onprogress = progressCallback;
  49518. xhr.addEventListener("load", function () {
  49519. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  49520. // Blob as response (XHR2)
  49521. //fileData = xhr.responseText;
  49522. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  49523. if (!_this.hasReachedQuota) {
  49524. // Open a transaction to the database
  49525. var transaction = _this.db.transaction([targetStore], "readwrite");
  49526. // the transaction could abort because of a QuotaExceededError error
  49527. transaction.onabort = function (event) {
  49528. try {
  49529. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  49530. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  49531. _this.hasReachedQuota = true;
  49532. }
  49533. }
  49534. catch (ex) { }
  49535. callback(fileData);
  49536. };
  49537. transaction.oncomplete = function (event) {
  49538. callback(fileData);
  49539. };
  49540. var newFile;
  49541. if (targetStore === "scenes") {
  49542. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  49543. }
  49544. else {
  49545. newFile = { textureUrl: url, data: fileData };
  49546. }
  49547. try {
  49548. // Put the scene into the database
  49549. var addRequest = transaction.objectStore(targetStore).put(newFile);
  49550. addRequest.onsuccess = function (event) {
  49551. };
  49552. addRequest.onerror = function (event) {
  49553. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  49554. };
  49555. }
  49556. catch (ex) {
  49557. callback(fileData);
  49558. }
  49559. }
  49560. else {
  49561. callback(fileData);
  49562. }
  49563. }
  49564. else {
  49565. callback();
  49566. }
  49567. }, false);
  49568. xhr.addEventListener("error", function (event) {
  49569. BABYLON.Tools.Error("error on XHR request.");
  49570. callback();
  49571. }, false);
  49572. xhr.send();
  49573. }
  49574. else {
  49575. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  49576. callback();
  49577. }
  49578. };
  49579. Database.IsUASupportingBlobStorage = true;
  49580. Database.IDBStorageEnabled = true;
  49581. Database.parseURL = function (url) {
  49582. var a = document.createElement('a');
  49583. a.href = url;
  49584. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  49585. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  49586. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  49587. return absLocation;
  49588. };
  49589. Database.ReturnFullUrlLocation = function (url) {
  49590. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  49591. return (Database.parseURL(window.location.href) + url);
  49592. }
  49593. else {
  49594. return url;
  49595. }
  49596. };
  49597. return Database;
  49598. }());
  49599. BABYLON.Database = Database;
  49600. })(BABYLON || (BABYLON = {}));
  49601. //# sourceMappingURL=babylon.database.js.map
  49602. var BABYLON;
  49603. (function (BABYLON) {
  49604. var FresnelParameters = (function () {
  49605. function FresnelParameters() {
  49606. this._isEnabled = true;
  49607. this.leftColor = BABYLON.Color3.White();
  49608. this.rightColor = BABYLON.Color3.Black();
  49609. this.bias = 0;
  49610. this.power = 1;
  49611. }
  49612. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  49613. get: function () {
  49614. return this._isEnabled;
  49615. },
  49616. set: function (value) {
  49617. if (this._isEnabled === value) {
  49618. return;
  49619. }
  49620. this._isEnabled = value;
  49621. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  49622. },
  49623. enumerable: true,
  49624. configurable: true
  49625. });
  49626. FresnelParameters.prototype.clone = function () {
  49627. var newFresnelParameters = new FresnelParameters();
  49628. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  49629. return newFresnelParameters;
  49630. };
  49631. FresnelParameters.prototype.serialize = function () {
  49632. var serializationObject = {};
  49633. serializationObject.isEnabled = this.isEnabled;
  49634. serializationObject.leftColor = this.leftColor;
  49635. serializationObject.rightColor = this.rightColor;
  49636. serializationObject.bias = this.bias;
  49637. serializationObject.power = this.power;
  49638. return serializationObject;
  49639. };
  49640. FresnelParameters.Parse = function (parsedFresnelParameters) {
  49641. var fresnelParameters = new FresnelParameters();
  49642. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  49643. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  49644. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  49645. fresnelParameters.bias = parsedFresnelParameters.bias;
  49646. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  49647. return fresnelParameters;
  49648. };
  49649. return FresnelParameters;
  49650. }());
  49651. BABYLON.FresnelParameters = FresnelParameters;
  49652. })(BABYLON || (BABYLON = {}));
  49653. //# sourceMappingURL=babylon.fresnelParameters.js.map
  49654. var BABYLON;
  49655. (function (BABYLON) {
  49656. var MultiMaterial = (function (_super) {
  49657. __extends(MultiMaterial, _super);
  49658. function MultiMaterial(name, scene) {
  49659. var _this = _super.call(this, name, scene, true) || this;
  49660. scene.multiMaterials.push(_this);
  49661. _this.subMaterials = new Array();
  49662. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  49663. return _this;
  49664. }
  49665. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  49666. get: function () {
  49667. return this._subMaterials;
  49668. },
  49669. set: function (value) {
  49670. this._subMaterials = value;
  49671. this._hookArray(value);
  49672. },
  49673. enumerable: true,
  49674. configurable: true
  49675. });
  49676. MultiMaterial.prototype._hookArray = function (array) {
  49677. var _this = this;
  49678. var oldPush = array.push;
  49679. array.push = function () {
  49680. var items = [];
  49681. for (var _i = 0; _i < arguments.length; _i++) {
  49682. items[_i] = arguments[_i];
  49683. }
  49684. var result = oldPush.apply(array, items);
  49685. _this._markAllSubMeshesAsTexturesDirty();
  49686. return result;
  49687. };
  49688. var oldSplice = array.splice;
  49689. array.splice = function (index, deleteCount) {
  49690. var deleted = oldSplice.apply(array, [index, deleteCount]);
  49691. _this._markAllSubMeshesAsTexturesDirty();
  49692. return deleted;
  49693. };
  49694. };
  49695. // Properties
  49696. MultiMaterial.prototype.getSubMaterial = function (index) {
  49697. if (index < 0 || index >= this.subMaterials.length) {
  49698. return this.getScene().defaultMaterial;
  49699. }
  49700. return this.subMaterials[index];
  49701. };
  49702. MultiMaterial.prototype.getActiveTextures = function () {
  49703. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) { return subMaterial.getActiveTextures(); }));
  49704. var _a;
  49705. };
  49706. // Methods
  49707. MultiMaterial.prototype.getClassName = function () {
  49708. return "MultiMaterial";
  49709. };
  49710. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  49711. for (var index = 0; index < this.subMaterials.length; index++) {
  49712. var subMaterial = this.subMaterials[index];
  49713. if (subMaterial) {
  49714. if (this.subMaterials[index].storeEffectOnSubMeshes) {
  49715. if (!this.subMaterials[index].isReadyForSubMesh(mesh, subMesh, useInstances)) {
  49716. return false;
  49717. }
  49718. continue;
  49719. }
  49720. if (!this.subMaterials[index].isReady(mesh)) {
  49721. return false;
  49722. }
  49723. }
  49724. }
  49725. return true;
  49726. };
  49727. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  49728. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  49729. for (var index = 0; index < this.subMaterials.length; index++) {
  49730. var subMaterial = null;
  49731. if (cloneChildren) {
  49732. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  49733. }
  49734. else {
  49735. subMaterial = this.subMaterials[index];
  49736. }
  49737. newMultiMaterial.subMaterials.push(subMaterial);
  49738. }
  49739. return newMultiMaterial;
  49740. };
  49741. MultiMaterial.prototype.serialize = function () {
  49742. var serializationObject = {};
  49743. serializationObject.name = this.name;
  49744. serializationObject.id = this.id;
  49745. serializationObject.tags = BABYLON.Tags.GetTags(this);
  49746. serializationObject.materials = [];
  49747. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  49748. var subMat = this.subMaterials[matIndex];
  49749. if (subMat) {
  49750. serializationObject.materials.push(subMat.id);
  49751. }
  49752. else {
  49753. serializationObject.materials.push(null);
  49754. }
  49755. }
  49756. return serializationObject;
  49757. };
  49758. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  49759. var scene = this.getScene();
  49760. if (!scene) {
  49761. return;
  49762. }
  49763. var index = scene.multiMaterials.indexOf(this);
  49764. if (index >= 0) {
  49765. scene.multiMaterials.splice(index, 1);
  49766. }
  49767. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  49768. };
  49769. return MultiMaterial;
  49770. }(BABYLON.Material));
  49771. BABYLON.MultiMaterial = MultiMaterial;
  49772. })(BABYLON || (BABYLON = {}));
  49773. //# sourceMappingURL=babylon.multiMaterial.js.map
  49774. var BABYLON;
  49775. (function (BABYLON) {
  49776. var FreeCameraTouchInput = (function () {
  49777. function FreeCameraTouchInput() {
  49778. this._offsetX = null;
  49779. this._offsetY = null;
  49780. this._pointerCount = 0;
  49781. this._pointerPressed = [];
  49782. this.touchAngularSensibility = 200000.0;
  49783. this.touchMoveSensibility = 250.0;
  49784. }
  49785. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  49786. var _this = this;
  49787. var previousPosition;
  49788. if (this._pointerInput === undefined) {
  49789. this._onLostFocus = function (evt) {
  49790. _this._offsetX = null;
  49791. _this._offsetY = null;
  49792. };
  49793. this._pointerInput = function (p, s) {
  49794. var evt = p.event;
  49795. if (evt.pointerType === "mouse") {
  49796. return;
  49797. }
  49798. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  49799. if (!noPreventDefault) {
  49800. evt.preventDefault();
  49801. }
  49802. _this._pointerPressed.push(evt.pointerId);
  49803. if (_this._pointerPressed.length !== 1) {
  49804. return;
  49805. }
  49806. previousPosition = {
  49807. x: evt.clientX,
  49808. y: evt.clientY
  49809. };
  49810. }
  49811. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  49812. if (!noPreventDefault) {
  49813. evt.preventDefault();
  49814. }
  49815. var index = _this._pointerPressed.indexOf(evt.pointerId);
  49816. if (index === -1) {
  49817. return;
  49818. }
  49819. _this._pointerPressed.splice(index, 1);
  49820. if (index != 0) {
  49821. return;
  49822. }
  49823. previousPosition = null;
  49824. _this._offsetX = null;
  49825. _this._offsetY = null;
  49826. }
  49827. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  49828. if (!noPreventDefault) {
  49829. evt.preventDefault();
  49830. }
  49831. if (!previousPosition) {
  49832. return;
  49833. }
  49834. var index = _this._pointerPressed.indexOf(evt.pointerId);
  49835. if (index != 0) {
  49836. return;
  49837. }
  49838. _this._offsetX = evt.clientX - previousPosition.x;
  49839. _this._offsetY = -(evt.clientY - previousPosition.y);
  49840. }
  49841. };
  49842. }
  49843. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  49844. element.addEventListener("blur", this._onLostFocus);
  49845. };
  49846. FreeCameraTouchInput.prototype.detachControl = function (element) {
  49847. if (this._pointerInput && element) {
  49848. this.camera.getScene().onPointerObservable.remove(this._observer);
  49849. this._observer = null;
  49850. element.removeEventListener("blur", this._onLostFocus);
  49851. this._onLostFocus = null;
  49852. this._pointerPressed = [];
  49853. this._offsetX = null;
  49854. this._offsetY = null;
  49855. this._pointerCount = 0;
  49856. }
  49857. };
  49858. FreeCameraTouchInput.prototype.checkInputs = function () {
  49859. if (this._offsetX) {
  49860. var camera = this.camera;
  49861. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  49862. if (this._pointerPressed.length > 1) {
  49863. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  49864. }
  49865. else {
  49866. var speed = camera._computeLocalCameraSpeed();
  49867. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  49868. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  49869. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  49870. }
  49871. }
  49872. };
  49873. FreeCameraTouchInput.prototype.getClassName = function () {
  49874. return "FreeCameraTouchInput";
  49875. };
  49876. FreeCameraTouchInput.prototype.getSimpleName = function () {
  49877. return "touch";
  49878. };
  49879. __decorate([
  49880. BABYLON.serialize()
  49881. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  49882. __decorate([
  49883. BABYLON.serialize()
  49884. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  49885. return FreeCameraTouchInput;
  49886. }());
  49887. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  49888. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  49889. })(BABYLON || (BABYLON = {}));
  49890. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  49891. /// <reference path="babylon.freeCamera.ts" />
  49892. var BABYLON;
  49893. (function (BABYLON) {
  49894. // We're mainly based on the logic defined into the FreeCamera code
  49895. var TouchCamera = (function (_super) {
  49896. __extends(TouchCamera, _super);
  49897. //-- end properties for backward compatibility for inputs
  49898. function TouchCamera(name, position, scene) {
  49899. var _this = _super.call(this, name, position, scene) || this;
  49900. _this.inputs.addTouch();
  49901. _this._setupInputs();
  49902. return _this;
  49903. }
  49904. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  49905. //-- Begin properties for backward compatibility for inputs
  49906. get: function () {
  49907. var touch = this.inputs.attached["touch"];
  49908. if (touch)
  49909. return touch.touchAngularSensibility;
  49910. },
  49911. set: function (value) {
  49912. var touch = this.inputs.attached["touch"];
  49913. if (touch)
  49914. touch.touchAngularSensibility = value;
  49915. },
  49916. enumerable: true,
  49917. configurable: true
  49918. });
  49919. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  49920. get: function () {
  49921. var touch = this.inputs.attached["touch"];
  49922. if (touch)
  49923. return touch.touchMoveSensibility;
  49924. },
  49925. set: function (value) {
  49926. var touch = this.inputs.attached["touch"];
  49927. if (touch)
  49928. touch.touchMoveSensibility = value;
  49929. },
  49930. enumerable: true,
  49931. configurable: true
  49932. });
  49933. TouchCamera.prototype.getClassName = function () {
  49934. return "TouchCamera";
  49935. };
  49936. TouchCamera.prototype._setupInputs = function () {
  49937. var mouse = this.inputs.attached["mouse"];
  49938. if (mouse) {
  49939. mouse.touchEnabled = false;
  49940. }
  49941. };
  49942. return TouchCamera;
  49943. }(BABYLON.FreeCamera));
  49944. BABYLON.TouchCamera = TouchCamera;
  49945. })(BABYLON || (BABYLON = {}));
  49946. //# sourceMappingURL=babylon.touchCamera.js.map
  49947. var BABYLON;
  49948. (function (BABYLON) {
  49949. var ProceduralTexture = (function (_super) {
  49950. __extends(ProceduralTexture, _super);
  49951. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  49952. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49953. if (isCube === void 0) { isCube = false; }
  49954. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  49955. _this.isCube = isCube;
  49956. _this.isEnabled = true;
  49957. _this._currentRefreshId = -1;
  49958. _this._refreshRate = 1;
  49959. _this._vertexBuffers = {};
  49960. _this._uniforms = new Array();
  49961. _this._samplers = new Array();
  49962. _this._textures = new Array();
  49963. _this._floats = new Array();
  49964. _this._floatsArrays = {};
  49965. _this._colors3 = new Array();
  49966. _this._colors4 = new Array();
  49967. _this._vectors2 = new Array();
  49968. _this._vectors3 = new Array();
  49969. _this._matrices = new Array();
  49970. _this._fallbackTextureUsed = false;
  49971. scene._proceduralTextures.push(_this);
  49972. _this.name = name;
  49973. _this.isRenderTarget = true;
  49974. _this._size = size;
  49975. _this._generateMipMaps = generateMipMaps;
  49976. _this.setFragment(fragment);
  49977. _this._fallbackTexture = fallbackTexture;
  49978. var engine = scene.getEngine();
  49979. if (isCube) {
  49980. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  49981. _this.setFloat("face", 0);
  49982. }
  49983. else {
  49984. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  49985. }
  49986. // VBO
  49987. var vertices = [];
  49988. vertices.push(1, 1);
  49989. vertices.push(-1, 1);
  49990. vertices.push(-1, -1);
  49991. vertices.push(1, -1);
  49992. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  49993. // Indices
  49994. var indices = [];
  49995. indices.push(0);
  49996. indices.push(1);
  49997. indices.push(2);
  49998. indices.push(0);
  49999. indices.push(2);
  50000. indices.push(3);
  50001. _this._indexBuffer = engine.createIndexBuffer(indices);
  50002. return _this;
  50003. }
  50004. ProceduralTexture.prototype.reset = function () {
  50005. if (this._effect === undefined) {
  50006. return;
  50007. }
  50008. var engine = this.getScene().getEngine();
  50009. engine._releaseEffect(this._effect);
  50010. };
  50011. ProceduralTexture.prototype.isReady = function () {
  50012. var _this = this;
  50013. var engine = this.getScene().getEngine();
  50014. var shaders;
  50015. if (!this._fragment) {
  50016. return false;
  50017. }
  50018. if (this._fallbackTextureUsed) {
  50019. return true;
  50020. }
  50021. if (this._fragment.fragmentElement !== undefined) {
  50022. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  50023. }
  50024. else {
  50025. shaders = { vertex: "procedural", fragment: this._fragment };
  50026. }
  50027. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  50028. _this.releaseInternalTexture();
  50029. if (_this._fallbackTexture) {
  50030. _this._texture = _this._fallbackTexture._texture;
  50031. _this._texture.incrementReferences();
  50032. }
  50033. _this._fallbackTextureUsed = true;
  50034. });
  50035. return this._effect.isReady();
  50036. };
  50037. ProceduralTexture.prototype.resetRefreshCounter = function () {
  50038. this._currentRefreshId = -1;
  50039. };
  50040. ProceduralTexture.prototype.setFragment = function (fragment) {
  50041. this._fragment = fragment;
  50042. };
  50043. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  50044. get: function () {
  50045. return this._refreshRate;
  50046. },
  50047. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  50048. set: function (value) {
  50049. this._refreshRate = value;
  50050. this.resetRefreshCounter();
  50051. },
  50052. enumerable: true,
  50053. configurable: true
  50054. });
  50055. ProceduralTexture.prototype._shouldRender = function () {
  50056. if (!this.isEnabled || !this.isReady() || !this._texture) {
  50057. return false;
  50058. }
  50059. if (this._fallbackTextureUsed) {
  50060. return false;
  50061. }
  50062. if (this._currentRefreshId === -1) {
  50063. this._currentRefreshId = 1;
  50064. return true;
  50065. }
  50066. if (this.refreshRate === this._currentRefreshId) {
  50067. this._currentRefreshId = 1;
  50068. return true;
  50069. }
  50070. this._currentRefreshId++;
  50071. return false;
  50072. };
  50073. ProceduralTexture.prototype.getRenderSize = function () {
  50074. return this._size;
  50075. };
  50076. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  50077. if (this._fallbackTextureUsed) {
  50078. return;
  50079. }
  50080. this.releaseInternalTexture();
  50081. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  50082. };
  50083. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  50084. if (this._uniforms.indexOf(uniformName) === -1) {
  50085. this._uniforms.push(uniformName);
  50086. }
  50087. };
  50088. ProceduralTexture.prototype.setTexture = function (name, texture) {
  50089. if (this._samplers.indexOf(name) === -1) {
  50090. this._samplers.push(name);
  50091. }
  50092. this._textures[name] = texture;
  50093. return this;
  50094. };
  50095. ProceduralTexture.prototype.setFloat = function (name, value) {
  50096. this._checkUniform(name);
  50097. this._floats[name] = value;
  50098. return this;
  50099. };
  50100. ProceduralTexture.prototype.setFloats = function (name, value) {
  50101. this._checkUniform(name);
  50102. this._floatsArrays[name] = value;
  50103. return this;
  50104. };
  50105. ProceduralTexture.prototype.setColor3 = function (name, value) {
  50106. this._checkUniform(name);
  50107. this._colors3[name] = value;
  50108. return this;
  50109. };
  50110. ProceduralTexture.prototype.setColor4 = function (name, value) {
  50111. this._checkUniform(name);
  50112. this._colors4[name] = value;
  50113. return this;
  50114. };
  50115. ProceduralTexture.prototype.setVector2 = function (name, value) {
  50116. this._checkUniform(name);
  50117. this._vectors2[name] = value;
  50118. return this;
  50119. };
  50120. ProceduralTexture.prototype.setVector3 = function (name, value) {
  50121. this._checkUniform(name);
  50122. this._vectors3[name] = value;
  50123. return this;
  50124. };
  50125. ProceduralTexture.prototype.setMatrix = function (name, value) {
  50126. this._checkUniform(name);
  50127. this._matrices[name] = value;
  50128. return this;
  50129. };
  50130. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  50131. var scene = this.getScene();
  50132. var engine = scene.getEngine();
  50133. // Render
  50134. engine.enableEffect(this._effect);
  50135. engine.setState(false);
  50136. // Texture
  50137. for (var name in this._textures) {
  50138. this._effect.setTexture(name, this._textures[name]);
  50139. }
  50140. // Float
  50141. for (name in this._floats) {
  50142. this._effect.setFloat(name, this._floats[name]);
  50143. }
  50144. // Floats
  50145. for (name in this._floatsArrays) {
  50146. this._effect.setArray(name, this._floatsArrays[name]);
  50147. }
  50148. // Color3
  50149. for (name in this._colors3) {
  50150. this._effect.setColor3(name, this._colors3[name]);
  50151. }
  50152. // Color4
  50153. for (name in this._colors4) {
  50154. var color = this._colors4[name];
  50155. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  50156. }
  50157. // Vector2
  50158. for (name in this._vectors2) {
  50159. this._effect.setVector2(name, this._vectors2[name]);
  50160. }
  50161. // Vector3
  50162. for (name in this._vectors3) {
  50163. this._effect.setVector3(name, this._vectors3[name]);
  50164. }
  50165. // Matrix
  50166. for (name in this._matrices) {
  50167. this._effect.setMatrix(name, this._matrices[name]);
  50168. }
  50169. if (this.isCube) {
  50170. for (var face = 0; face < 6; face++) {
  50171. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  50172. // VBOs
  50173. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  50174. this._effect.setFloat("face", face);
  50175. // Clear
  50176. engine.clear(scene.clearColor, true, true, true);
  50177. // Draw order
  50178. engine.draw(true, 0, 6);
  50179. // Mipmaps
  50180. if (face === 5) {
  50181. engine.generateMipMapsForCubemap(this._texture);
  50182. }
  50183. }
  50184. }
  50185. else {
  50186. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  50187. // VBOs
  50188. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  50189. // Clear
  50190. engine.clear(scene.clearColor, true, true, true);
  50191. // Draw order
  50192. engine.draw(true, 0, 6);
  50193. }
  50194. // Unbind
  50195. engine.unBindFramebuffer(this._texture, this.isCube);
  50196. if (this.onGenerated) {
  50197. this.onGenerated();
  50198. }
  50199. };
  50200. ProceduralTexture.prototype.clone = function () {
  50201. var textureSize = this.getSize();
  50202. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  50203. // Base texture
  50204. newTexture.hasAlpha = this.hasAlpha;
  50205. newTexture.level = this.level;
  50206. // RenderTarget Texture
  50207. newTexture.coordinatesMode = this.coordinatesMode;
  50208. return newTexture;
  50209. };
  50210. ProceduralTexture.prototype.dispose = function () {
  50211. var index = this.getScene()._proceduralTextures.indexOf(this);
  50212. if (index >= 0) {
  50213. this.getScene()._proceduralTextures.splice(index, 1);
  50214. }
  50215. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  50216. if (vertexBuffer) {
  50217. vertexBuffer.dispose();
  50218. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  50219. }
  50220. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  50221. this._indexBuffer = null;
  50222. }
  50223. _super.prototype.dispose.call(this);
  50224. };
  50225. return ProceduralTexture;
  50226. }(BABYLON.Texture));
  50227. BABYLON.ProceduralTexture = ProceduralTexture;
  50228. })(BABYLON || (BABYLON = {}));
  50229. //# sourceMappingURL=babylon.proceduralTexture.js.map
  50230. /// <reference path="babylon.proceduralTexture.ts" />
  50231. var BABYLON;
  50232. (function (BABYLON) {
  50233. var CustomProceduralTexture = (function (_super) {
  50234. __extends(CustomProceduralTexture, _super);
  50235. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  50236. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  50237. _this._animate = true;
  50238. _this._time = 0;
  50239. _this._texturePath = texturePath;
  50240. //Try to load json
  50241. _this.loadJson(texturePath);
  50242. _this.refreshRate = 1;
  50243. return _this;
  50244. }
  50245. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  50246. var _this = this;
  50247. var that = this;
  50248. function noConfigFile() {
  50249. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  50250. try {
  50251. that.setFragment(that._texturePath);
  50252. }
  50253. catch (ex) {
  50254. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  50255. }
  50256. }
  50257. var configFileUrl = jsonUrl + "/config.json";
  50258. var xhr = new XMLHttpRequest();
  50259. xhr.open("GET", configFileUrl, true);
  50260. xhr.addEventListener("load", function () {
  50261. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  50262. try {
  50263. _this._config = JSON.parse(xhr.response);
  50264. _this.updateShaderUniforms();
  50265. _this.updateTextures();
  50266. _this.setFragment(_this._texturePath + "/custom");
  50267. _this._animate = _this._config.animate;
  50268. _this.refreshRate = _this._config.refreshrate;
  50269. }
  50270. catch (ex) {
  50271. noConfigFile();
  50272. }
  50273. }
  50274. else {
  50275. noConfigFile();
  50276. }
  50277. }, false);
  50278. xhr.addEventListener("error", function () {
  50279. noConfigFile();
  50280. }, false);
  50281. try {
  50282. xhr.send();
  50283. }
  50284. catch (ex) {
  50285. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  50286. }
  50287. };
  50288. CustomProceduralTexture.prototype.isReady = function () {
  50289. if (!_super.prototype.isReady.call(this)) {
  50290. return false;
  50291. }
  50292. for (var name in this._textures) {
  50293. var texture = this._textures[name];
  50294. if (!texture.isReady()) {
  50295. return false;
  50296. }
  50297. }
  50298. return true;
  50299. };
  50300. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  50301. if (this._animate) {
  50302. this._time += this.getScene().getAnimationRatio() * 0.03;
  50303. this.updateShaderUniforms();
  50304. }
  50305. _super.prototype.render.call(this, useCameraPostProcess);
  50306. };
  50307. CustomProceduralTexture.prototype.updateTextures = function () {
  50308. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  50309. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  50310. }
  50311. };
  50312. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  50313. if (this._config) {
  50314. for (var j = 0; j < this._config.uniforms.length; j++) {
  50315. var uniform = this._config.uniforms[j];
  50316. switch (uniform.type) {
  50317. case "float":
  50318. this.setFloat(uniform.name, uniform.value);
  50319. break;
  50320. case "color3":
  50321. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  50322. break;
  50323. case "color4":
  50324. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  50325. break;
  50326. case "vector2":
  50327. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  50328. break;
  50329. case "vector3":
  50330. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  50331. break;
  50332. }
  50333. }
  50334. }
  50335. this.setFloat("time", this._time);
  50336. };
  50337. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  50338. get: function () {
  50339. return this._animate;
  50340. },
  50341. set: function (value) {
  50342. this._animate = value;
  50343. },
  50344. enumerable: true,
  50345. configurable: true
  50346. });
  50347. return CustomProceduralTexture;
  50348. }(BABYLON.ProceduralTexture));
  50349. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  50350. })(BABYLON || (BABYLON = {}));
  50351. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  50352. var BABYLON;
  50353. (function (BABYLON) {
  50354. var FreeCameraGamepadInput = (function () {
  50355. function FreeCameraGamepadInput() {
  50356. this.gamepadAngularSensibility = 200;
  50357. this.gamepadMoveSensibility = 40;
  50358. // private members
  50359. this._cameraTransform = BABYLON.Matrix.Identity();
  50360. this._deltaTransform = BABYLON.Vector3.Zero();
  50361. this._vector3 = BABYLON.Vector3.Zero();
  50362. this._vector2 = BABYLON.Vector2.Zero();
  50363. }
  50364. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  50365. var _this = this;
  50366. var manager = this.camera.getScene().gamepadManager;
  50367. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  50368. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  50369. // prioritize XBOX gamepads.
  50370. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  50371. _this.gamepad = gamepad;
  50372. }
  50373. }
  50374. });
  50375. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  50376. if (_this.gamepad === gamepad) {
  50377. _this.gamepad = null;
  50378. }
  50379. });
  50380. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  50381. };
  50382. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  50383. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  50384. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  50385. this.gamepad = null;
  50386. };
  50387. FreeCameraGamepadInput.prototype.checkInputs = function () {
  50388. if (this.gamepad && this.gamepad.leftStick) {
  50389. var camera = this.camera;
  50390. var LSValues = this.gamepad.leftStick;
  50391. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  50392. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  50393. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  50394. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  50395. var RSValues = this.gamepad.rightStick;
  50396. if (RSValues) {
  50397. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  50398. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  50399. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  50400. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  50401. }
  50402. else {
  50403. RSValues = { x: 0, y: 0 };
  50404. }
  50405. if (!camera.rotationQuaternion) {
  50406. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  50407. }
  50408. else {
  50409. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  50410. }
  50411. var speed = camera._computeLocalCameraSpeed() * 50.0;
  50412. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  50413. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  50414. camera.cameraDirection.addInPlace(this._deltaTransform);
  50415. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  50416. camera.cameraRotation.addInPlace(this._vector2);
  50417. }
  50418. };
  50419. FreeCameraGamepadInput.prototype.getClassName = function () {
  50420. return "FreeCameraGamepadInput";
  50421. };
  50422. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  50423. return "gamepad";
  50424. };
  50425. __decorate([
  50426. BABYLON.serialize()
  50427. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  50428. __decorate([
  50429. BABYLON.serialize()
  50430. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  50431. return FreeCameraGamepadInput;
  50432. }());
  50433. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  50434. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  50435. })(BABYLON || (BABYLON = {}));
  50436. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  50437. var BABYLON;
  50438. (function (BABYLON) {
  50439. var ArcRotateCameraGamepadInput = (function () {
  50440. function ArcRotateCameraGamepadInput() {
  50441. this.gamepadRotationSensibility = 80;
  50442. this.gamepadMoveSensibility = 40;
  50443. }
  50444. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  50445. var _this = this;
  50446. var manager = this.camera.getScene().gamepadManager;
  50447. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  50448. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  50449. // prioritize XBOX gamepads.
  50450. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  50451. _this.gamepad = gamepad;
  50452. }
  50453. }
  50454. });
  50455. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  50456. if (_this.gamepad === gamepad) {
  50457. _this.gamepad = null;
  50458. }
  50459. });
  50460. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  50461. };
  50462. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  50463. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  50464. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  50465. this.gamepad = null;
  50466. };
  50467. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  50468. if (this.gamepad) {
  50469. var camera = this.camera;
  50470. var RSValues = this.gamepad.rightStick;
  50471. if (RSValues) {
  50472. if (RSValues.x != 0) {
  50473. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  50474. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  50475. camera.inertialAlphaOffset += normalizedRX;
  50476. }
  50477. }
  50478. if (RSValues.y != 0) {
  50479. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  50480. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  50481. camera.inertialBetaOffset += normalizedRY;
  50482. }
  50483. }
  50484. }
  50485. var LSValues = this.gamepad.leftStick;
  50486. if (LSValues && LSValues.y != 0) {
  50487. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  50488. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  50489. this.camera.inertialRadiusOffset -= normalizedLY;
  50490. }
  50491. }
  50492. }
  50493. };
  50494. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  50495. return "ArcRotateCameraGamepadInput";
  50496. };
  50497. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  50498. return "gamepad";
  50499. };
  50500. __decorate([
  50501. BABYLON.serialize()
  50502. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  50503. __decorate([
  50504. BABYLON.serialize()
  50505. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  50506. return ArcRotateCameraGamepadInput;
  50507. }());
  50508. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  50509. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  50510. })(BABYLON || (BABYLON = {}));
  50511. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  50512. var BABYLON;
  50513. (function (BABYLON) {
  50514. var GamepadManager = (function () {
  50515. function GamepadManager() {
  50516. var _this = this;
  50517. this._babylonGamepads = [];
  50518. this._oneGamepadConnected = false;
  50519. this._isMonitoring = false;
  50520. this._gamepadEventSupported = 'GamepadEvent' in window;
  50521. this._gamepadSupport = (navigator.getGamepads ||
  50522. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  50523. this.onGamepadConnectedObservable = new BABYLON.Observable();
  50524. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  50525. this._onGamepadConnectedEvent = function (evt) {
  50526. var gamepad = evt.gamepad;
  50527. // Protection code for Chrome which has a very buggy gamepad implementation...
  50528. // And raises a connected event on disconnection for instance
  50529. if (gamepad.index in _this._babylonGamepads) {
  50530. return;
  50531. }
  50532. var newGamepad = _this._addNewGamepad(gamepad);
  50533. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  50534. _this._startMonitoringGamepads();
  50535. };
  50536. this._onGamepadDisconnectedEvent = function (evt) {
  50537. var gamepad = evt.gamepad;
  50538. // Remove the gamepad from the list of gamepads to monitor.
  50539. for (var i in _this._babylonGamepads) {
  50540. if (_this._babylonGamepads[i].index === gamepad.index) {
  50541. var gamepadToRemove = _this._babylonGamepads[i];
  50542. _this._babylonGamepads[i] = null;
  50543. _this.onGamepadDisconnectedObservable.notifyObservers(gamepadToRemove);
  50544. gamepadToRemove.dispose();
  50545. break;
  50546. }
  50547. }
  50548. };
  50549. if (this._gamepadSupport) {
  50550. //first add already-connected gamepads
  50551. this._updateGamepadObjects();
  50552. if (this._babylonGamepads.length) {
  50553. this._startMonitoringGamepads();
  50554. }
  50555. // Checking if the gamepad connected event is supported (like in Firefox)
  50556. if (this._gamepadEventSupported) {
  50557. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  50558. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  50559. }
  50560. else {
  50561. this._startMonitoringGamepads();
  50562. }
  50563. }
  50564. }
  50565. GamepadManager.prototype.getGamepadByType = function (type) {
  50566. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  50567. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  50568. var gamepad = _a[_i];
  50569. if (gamepad && gamepad.type === type) {
  50570. return gamepad;
  50571. }
  50572. }
  50573. return null;
  50574. };
  50575. GamepadManager.prototype.dispose = function () {
  50576. if (this._gamepadEventSupported) {
  50577. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  50578. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  50579. this._onGamepadConnectedEvent = null;
  50580. this._onGamepadDisconnectedEvent = null;
  50581. }
  50582. this._oneGamepadConnected = false;
  50583. this._stopMonitoringGamepads();
  50584. this._babylonGamepads = [];
  50585. };
  50586. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  50587. if (!this._oneGamepadConnected) {
  50588. this._oneGamepadConnected = true;
  50589. }
  50590. var newGamepad;
  50591. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  50592. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  50593. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  50594. }
  50595. else if (gamepad.pose) {
  50596. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  50597. }
  50598. else {
  50599. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  50600. }
  50601. this._babylonGamepads[newGamepad.index] = newGamepad;
  50602. return newGamepad;
  50603. };
  50604. GamepadManager.prototype._startMonitoringGamepads = function () {
  50605. if (!this._isMonitoring) {
  50606. this._isMonitoring = true;
  50607. this._checkGamepadsStatus();
  50608. }
  50609. };
  50610. GamepadManager.prototype._stopMonitoringGamepads = function () {
  50611. this._isMonitoring = false;
  50612. };
  50613. GamepadManager.prototype._checkGamepadsStatus = function () {
  50614. var _this = this;
  50615. // Hack to be compatible Chrome
  50616. this._updateGamepadObjects();
  50617. for (var i in this._babylonGamepads) {
  50618. var gamepad = this._babylonGamepads[i];
  50619. if (!gamepad) {
  50620. continue;
  50621. }
  50622. gamepad.update();
  50623. }
  50624. if (this._isMonitoring) {
  50625. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  50626. }
  50627. };
  50628. // This function is called only on Chrome, which does not properly support
  50629. // connection/disconnection events and forces you to recopy again the gamepad object
  50630. GamepadManager.prototype._updateGamepadObjects = function () {
  50631. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  50632. for (var i = 0; i < gamepads.length; i++) {
  50633. if (gamepads[i]) {
  50634. if (!this._babylonGamepads[gamepads[i].index]) {
  50635. var newGamepad = this._addNewGamepad(gamepads[i]);
  50636. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  50637. }
  50638. else {
  50639. // Forced to copy again this object for Chrome for unknown reason
  50640. this._babylonGamepads[i].browserGamepad = gamepads[i];
  50641. }
  50642. }
  50643. }
  50644. };
  50645. return GamepadManager;
  50646. }());
  50647. BABYLON.GamepadManager = GamepadManager;
  50648. })(BABYLON || (BABYLON = {}));
  50649. //# sourceMappingURL=babylon.gamepadManager.js.map
  50650. var BABYLON;
  50651. (function (BABYLON) {
  50652. var StickValues = (function () {
  50653. function StickValues(x, y) {
  50654. this.x = x;
  50655. this.y = y;
  50656. }
  50657. return StickValues;
  50658. }());
  50659. BABYLON.StickValues = StickValues;
  50660. var Gamepad = (function () {
  50661. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  50662. if (leftStickX === void 0) { leftStickX = 0; }
  50663. if (leftStickY === void 0) { leftStickY = 1; }
  50664. if (rightStickX === void 0) { rightStickX = 2; }
  50665. if (rightStickY === void 0) { rightStickY = 3; }
  50666. this.id = id;
  50667. this.index = index;
  50668. this.browserGamepad = browserGamepad;
  50669. this.type = Gamepad.GAMEPAD;
  50670. this._leftStickAxisX = leftStickX;
  50671. this._leftStickAxisY = leftStickY;
  50672. this._rightStickAxisX = rightStickX;
  50673. this._rightStickAxisY = rightStickY;
  50674. if (this.browserGamepad.axes.length >= 2) {
  50675. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  50676. }
  50677. if (this.browserGamepad.axes.length >= 4) {
  50678. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  50679. }
  50680. }
  50681. Gamepad.prototype.onleftstickchanged = function (callback) {
  50682. this._onleftstickchanged = callback;
  50683. };
  50684. Gamepad.prototype.onrightstickchanged = function (callback) {
  50685. this._onrightstickchanged = callback;
  50686. };
  50687. Object.defineProperty(Gamepad.prototype, "leftStick", {
  50688. get: function () {
  50689. return this._leftStick;
  50690. },
  50691. set: function (newValues) {
  50692. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  50693. this._onleftstickchanged(newValues);
  50694. }
  50695. this._leftStick = newValues;
  50696. },
  50697. enumerable: true,
  50698. configurable: true
  50699. });
  50700. Object.defineProperty(Gamepad.prototype, "rightStick", {
  50701. get: function () {
  50702. return this._rightStick;
  50703. },
  50704. set: function (newValues) {
  50705. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  50706. this._onrightstickchanged(newValues);
  50707. }
  50708. this._rightStick = newValues;
  50709. },
  50710. enumerable: true,
  50711. configurable: true
  50712. });
  50713. Gamepad.prototype.update = function () {
  50714. if (this._leftStick) {
  50715. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  50716. }
  50717. if (this._rightStick) {
  50718. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  50719. }
  50720. };
  50721. Gamepad.prototype.dispose = function () {
  50722. };
  50723. Gamepad.GAMEPAD = 0;
  50724. Gamepad.GENERIC = 1;
  50725. Gamepad.XBOX = 2;
  50726. Gamepad.POSE_ENABLED = 3;
  50727. return Gamepad;
  50728. }());
  50729. BABYLON.Gamepad = Gamepad;
  50730. var GenericPad = (function (_super) {
  50731. __extends(GenericPad, _super);
  50732. function GenericPad(id, index, browserGamepad) {
  50733. var _this = _super.call(this, id, index, browserGamepad) || this;
  50734. _this.type = Gamepad.GENERIC;
  50735. _this._buttons = new Array(browserGamepad.buttons.length);
  50736. return _this;
  50737. }
  50738. GenericPad.prototype.onbuttondown = function (callback) {
  50739. this._onbuttondown = callback;
  50740. };
  50741. GenericPad.prototype.onbuttonup = function (callback) {
  50742. this._onbuttonup = callback;
  50743. };
  50744. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  50745. if (newValue !== currentValue) {
  50746. if (this._onbuttondown && newValue === 1) {
  50747. this._onbuttondown(buttonIndex);
  50748. }
  50749. if (this._onbuttonup && newValue === 0) {
  50750. this._onbuttonup(buttonIndex);
  50751. }
  50752. }
  50753. return newValue;
  50754. };
  50755. GenericPad.prototype.update = function () {
  50756. _super.prototype.update.call(this);
  50757. for (var index = 0; index < this._buttons.length; index++) {
  50758. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  50759. }
  50760. };
  50761. return GenericPad;
  50762. }(Gamepad));
  50763. BABYLON.GenericPad = GenericPad;
  50764. })(BABYLON || (BABYLON = {}));
  50765. //# sourceMappingURL=babylon.gamepad.js.map
  50766. var BABYLON;
  50767. (function (BABYLON) {
  50768. var Xbox360Button;
  50769. (function (Xbox360Button) {
  50770. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  50771. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  50772. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  50773. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  50774. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  50775. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  50776. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  50777. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  50778. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  50779. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  50780. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  50781. var Xbox360Dpad;
  50782. (function (Xbox360Dpad) {
  50783. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  50784. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  50785. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  50786. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  50787. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  50788. var Xbox360Pad = (function (_super) {
  50789. __extends(Xbox360Pad, _super);
  50790. function Xbox360Pad(id, index, gamepad, xboxOne) {
  50791. if (xboxOne === void 0) { xboxOne = false; }
  50792. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  50793. _this._leftTrigger = 0;
  50794. _this._rightTrigger = 0;
  50795. _this._buttonA = 0;
  50796. _this._buttonB = 0;
  50797. _this._buttonX = 0;
  50798. _this._buttonY = 0;
  50799. _this._buttonBack = 0;
  50800. _this._buttonStart = 0;
  50801. _this._buttonLB = 0;
  50802. _this._buttonRB = 0;
  50803. _this._buttonLeftStick = 0;
  50804. _this._buttonRightStick = 0;
  50805. _this._dPadUp = 0;
  50806. _this._dPadDown = 0;
  50807. _this._dPadLeft = 0;
  50808. _this._dPadRight = 0;
  50809. _this._isXboxOnePad = false;
  50810. _this.type = BABYLON.Gamepad.XBOX;
  50811. _this._isXboxOnePad = xboxOne;
  50812. return _this;
  50813. }
  50814. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  50815. this._onlefttriggerchanged = callback;
  50816. };
  50817. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  50818. this._onrighttriggerchanged = callback;
  50819. };
  50820. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  50821. get: function () {
  50822. return this._leftTrigger;
  50823. },
  50824. set: function (newValue) {
  50825. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  50826. this._onlefttriggerchanged(newValue);
  50827. }
  50828. this._leftTrigger = newValue;
  50829. },
  50830. enumerable: true,
  50831. configurable: true
  50832. });
  50833. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  50834. get: function () {
  50835. return this._rightTrigger;
  50836. },
  50837. set: function (newValue) {
  50838. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  50839. this._onrighttriggerchanged(newValue);
  50840. }
  50841. this._rightTrigger = newValue;
  50842. },
  50843. enumerable: true,
  50844. configurable: true
  50845. });
  50846. Xbox360Pad.prototype.onbuttondown = function (callback) {
  50847. this._onbuttondown = callback;
  50848. };
  50849. Xbox360Pad.prototype.onbuttonup = function (callback) {
  50850. this._onbuttonup = callback;
  50851. };
  50852. Xbox360Pad.prototype.ondpaddown = function (callback) {
  50853. this._ondpaddown = callback;
  50854. };
  50855. Xbox360Pad.prototype.ondpadup = function (callback) {
  50856. this._ondpadup = callback;
  50857. };
  50858. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  50859. if (newValue !== currentValue) {
  50860. if (this._onbuttondown && newValue === 1) {
  50861. this._onbuttondown(buttonType);
  50862. }
  50863. if (this._onbuttonup && newValue === 0) {
  50864. this._onbuttonup(buttonType);
  50865. }
  50866. }
  50867. return newValue;
  50868. };
  50869. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  50870. if (newValue !== currentValue) {
  50871. if (this._ondpaddown && newValue === 1) {
  50872. this._ondpaddown(buttonType);
  50873. }
  50874. if (this._ondpadup && newValue === 0) {
  50875. this._ondpadup(buttonType);
  50876. }
  50877. }
  50878. return newValue;
  50879. };
  50880. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  50881. get: function () {
  50882. return this._buttonA;
  50883. },
  50884. set: function (value) {
  50885. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  50886. },
  50887. enumerable: true,
  50888. configurable: true
  50889. });
  50890. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  50891. get: function () {
  50892. return this._buttonB;
  50893. },
  50894. set: function (value) {
  50895. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  50896. },
  50897. enumerable: true,
  50898. configurable: true
  50899. });
  50900. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  50901. get: function () {
  50902. return this._buttonX;
  50903. },
  50904. set: function (value) {
  50905. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  50906. },
  50907. enumerable: true,
  50908. configurable: true
  50909. });
  50910. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  50911. get: function () {
  50912. return this._buttonY;
  50913. },
  50914. set: function (value) {
  50915. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  50916. },
  50917. enumerable: true,
  50918. configurable: true
  50919. });
  50920. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  50921. get: function () {
  50922. return this._buttonStart;
  50923. },
  50924. set: function (value) {
  50925. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  50926. },
  50927. enumerable: true,
  50928. configurable: true
  50929. });
  50930. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  50931. get: function () {
  50932. return this._buttonBack;
  50933. },
  50934. set: function (value) {
  50935. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  50936. },
  50937. enumerable: true,
  50938. configurable: true
  50939. });
  50940. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  50941. get: function () {
  50942. return this._buttonLB;
  50943. },
  50944. set: function (value) {
  50945. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  50946. },
  50947. enumerable: true,
  50948. configurable: true
  50949. });
  50950. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  50951. get: function () {
  50952. return this._buttonRB;
  50953. },
  50954. set: function (value) {
  50955. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  50956. },
  50957. enumerable: true,
  50958. configurable: true
  50959. });
  50960. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  50961. get: function () {
  50962. return this._buttonLeftStick;
  50963. },
  50964. set: function (value) {
  50965. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  50966. },
  50967. enumerable: true,
  50968. configurable: true
  50969. });
  50970. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  50971. get: function () {
  50972. return this._buttonRightStick;
  50973. },
  50974. set: function (value) {
  50975. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  50976. },
  50977. enumerable: true,
  50978. configurable: true
  50979. });
  50980. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  50981. get: function () {
  50982. return this._dPadUp;
  50983. },
  50984. set: function (value) {
  50985. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  50986. },
  50987. enumerable: true,
  50988. configurable: true
  50989. });
  50990. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  50991. get: function () {
  50992. return this._dPadDown;
  50993. },
  50994. set: function (value) {
  50995. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  50996. },
  50997. enumerable: true,
  50998. configurable: true
  50999. });
  51000. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  51001. get: function () {
  51002. return this._dPadLeft;
  51003. },
  51004. set: function (value) {
  51005. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  51006. },
  51007. enumerable: true,
  51008. configurable: true
  51009. });
  51010. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  51011. get: function () {
  51012. return this._dPadRight;
  51013. },
  51014. set: function (value) {
  51015. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  51016. },
  51017. enumerable: true,
  51018. configurable: true
  51019. });
  51020. Xbox360Pad.prototype.update = function () {
  51021. _super.prototype.update.call(this);
  51022. if (this._isXboxOnePad) {
  51023. this.buttonA = this.browserGamepad.buttons[0].value;
  51024. this.buttonB = this.browserGamepad.buttons[1].value;
  51025. this.buttonX = this.browserGamepad.buttons[2].value;
  51026. this.buttonY = this.browserGamepad.buttons[3].value;
  51027. this.buttonLB = this.browserGamepad.buttons[4].value;
  51028. this.buttonRB = this.browserGamepad.buttons[5].value;
  51029. this.leftTrigger = this.browserGamepad.axes[2];
  51030. this.rightTrigger = this.browserGamepad.axes[5];
  51031. this.buttonBack = this.browserGamepad.buttons[9].value;
  51032. this.buttonStart = this.browserGamepad.buttons[8].value;
  51033. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  51034. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  51035. this.dPadUp = this.browserGamepad.buttons[11].value;
  51036. this.dPadDown = this.browserGamepad.buttons[12].value;
  51037. this.dPadLeft = this.browserGamepad.buttons[13].value;
  51038. this.dPadRight = this.browserGamepad.buttons[14].value;
  51039. }
  51040. else {
  51041. this.buttonA = this.browserGamepad.buttons[0].value;
  51042. this.buttonB = this.browserGamepad.buttons[1].value;
  51043. this.buttonX = this.browserGamepad.buttons[2].value;
  51044. this.buttonY = this.browserGamepad.buttons[3].value;
  51045. this.buttonLB = this.browserGamepad.buttons[4].value;
  51046. this.buttonRB = this.browserGamepad.buttons[5].value;
  51047. this.leftTrigger = this.browserGamepad.buttons[6].value;
  51048. this.rightTrigger = this.browserGamepad.buttons[7].value;
  51049. this.buttonBack = this.browserGamepad.buttons[8].value;
  51050. this.buttonStart = this.browserGamepad.buttons[9].value;
  51051. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  51052. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  51053. this.dPadUp = this.browserGamepad.buttons[12].value;
  51054. this.dPadDown = this.browserGamepad.buttons[13].value;
  51055. this.dPadLeft = this.browserGamepad.buttons[14].value;
  51056. this.dPadRight = this.browserGamepad.buttons[15].value;
  51057. }
  51058. };
  51059. return Xbox360Pad;
  51060. }(BABYLON.Gamepad));
  51061. BABYLON.Xbox360Pad = Xbox360Pad;
  51062. })(BABYLON || (BABYLON = {}));
  51063. //# sourceMappingURL=babylon.xboxGamepad.js.map
  51064. var BABYLON;
  51065. (function (BABYLON) {
  51066. var PoseEnabledControllerType;
  51067. (function (PoseEnabledControllerType) {
  51068. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  51069. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  51070. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  51071. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 3] = "GENERIC";
  51072. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  51073. var PoseEnabledControllerHelper = (function () {
  51074. function PoseEnabledControllerHelper() {
  51075. }
  51076. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  51077. // Oculus Touch
  51078. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  51079. return new BABYLON.OculusTouchController(vrGamepad);
  51080. }
  51081. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  51082. return new BABYLON.ViveController(vrGamepad);
  51083. }
  51084. else {
  51085. return new BABYLON.GenericController(vrGamepad);
  51086. }
  51087. };
  51088. return PoseEnabledControllerHelper;
  51089. }());
  51090. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  51091. var PoseEnabledController = (function (_super) {
  51092. __extends(PoseEnabledController, _super);
  51093. function PoseEnabledController(vrGamepad) {
  51094. var _this = _super.call(this, vrGamepad.id, vrGamepad.index, vrGamepad) || this;
  51095. _this.vrGamepad = vrGamepad;
  51096. _this.deviceScaleFactor = 1;
  51097. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  51098. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  51099. _this.controllerType = PoseEnabledControllerType.GENERIC;
  51100. _this.position = BABYLON.Vector3.Zero();
  51101. _this.rotationQuaternion = new BABYLON.Quaternion();
  51102. _this.devicePosition = BABYLON.Vector3.Zero();
  51103. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  51104. _this._calculatedPosition = BABYLON.Vector3.Zero();
  51105. _this._calculatedRotation = new BABYLON.Quaternion();
  51106. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  51107. return _this;
  51108. }
  51109. PoseEnabledController.prototype.update = function () {
  51110. _super.prototype.update.call(this);
  51111. var pose = this.vrGamepad.pose;
  51112. this.updateFromDevice(pose);
  51113. if (this._mesh) {
  51114. this._mesh.position.copyFrom(this._calculatedPosition);
  51115. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  51116. }
  51117. };
  51118. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  51119. if (poseData) {
  51120. this.rawPose = poseData;
  51121. if (poseData.position) {
  51122. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  51123. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  51124. this.devicePosition.z *= -1;
  51125. }
  51126. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  51127. this._calculatedPosition.addInPlace(this.position);
  51128. }
  51129. if (poseData.orientation) {
  51130. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  51131. if (this._mesh) {
  51132. if (this._mesh.getScene().useRightHandedSystem) {
  51133. this.deviceRotationQuaternion.z *= -1;
  51134. this.deviceRotationQuaternion.w *= -1;
  51135. }
  51136. else {
  51137. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  51138. }
  51139. }
  51140. // if the camera is set, rotate to the camera's rotation
  51141. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  51142. }
  51143. }
  51144. };
  51145. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  51146. if (this._mesh) {
  51147. this._mesh.parent = undefined;
  51148. }
  51149. this._mesh = mesh;
  51150. if (this._poseControlledCamera) {
  51151. this._mesh.parent = this._poseControlledCamera;
  51152. }
  51153. if (!this._mesh.rotationQuaternion) {
  51154. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  51155. }
  51156. };
  51157. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  51158. this._poseControlledCamera = camera;
  51159. if (this._mesh) {
  51160. this._mesh.parent = this._poseControlledCamera;
  51161. }
  51162. };
  51163. PoseEnabledController.prototype.dispose = function () {
  51164. if (this._mesh) {
  51165. this._mesh.dispose();
  51166. }
  51167. this._mesh = undefined;
  51168. _super.prototype.dispose.call(this);
  51169. };
  51170. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  51171. get: function () {
  51172. return this._mesh;
  51173. },
  51174. enumerable: true,
  51175. configurable: true
  51176. });
  51177. PoseEnabledController.prototype.getForwardRay = function (length) {
  51178. if (length === void 0) { length = 100; }
  51179. if (!this.mesh) {
  51180. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  51181. }
  51182. var m = this.mesh.getWorldMatrix();
  51183. var origin = m.getTranslation();
  51184. var forward = new BABYLON.Vector3(0, 0, -1);
  51185. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  51186. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  51187. return new BABYLON.Ray(origin, direction, length);
  51188. };
  51189. return PoseEnabledController;
  51190. }(BABYLON.Gamepad));
  51191. BABYLON.PoseEnabledController = PoseEnabledController;
  51192. })(BABYLON || (BABYLON = {}));
  51193. //# sourceMappingURL=babylon.poseEnabledController.js.map
  51194. var BABYLON;
  51195. (function (BABYLON) {
  51196. var WebVRController = (function (_super) {
  51197. __extends(WebVRController, _super);
  51198. function WebVRController(vrGamepad) {
  51199. var _this = _super.call(this, vrGamepad) || this;
  51200. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  51201. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  51202. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  51203. _this.onPadStateChangedObservable = new BABYLON.Observable();
  51204. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  51205. _this.pad = { x: 0, y: 0 };
  51206. // avoid GC, store state in a tmp object
  51207. _this._changes = {
  51208. pressChanged: false,
  51209. touchChanged: false,
  51210. valueChanged: false,
  51211. changed: false
  51212. };
  51213. _this._buttons = new Array(vrGamepad.buttons.length);
  51214. _this.hand = vrGamepad.hand;
  51215. return _this;
  51216. }
  51217. WebVRController.prototype.onButtonStateChange = function (callback) {
  51218. this._onButtonStateChange = callback;
  51219. };
  51220. WebVRController.prototype.update = function () {
  51221. _super.prototype.update.call(this);
  51222. for (var index = 0; index < this._buttons.length; index++) {
  51223. this._setButtonValue(this.vrGamepad.buttons[index], this._buttons[index], index);
  51224. }
  51225. ;
  51226. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  51227. this.pad.x = this.leftStick.x;
  51228. this.pad.y = this.leftStick.y;
  51229. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  51230. }
  51231. };
  51232. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  51233. if (!newState) {
  51234. newState = {
  51235. pressed: false,
  51236. touched: false,
  51237. value: 0
  51238. };
  51239. }
  51240. if (!currentState) {
  51241. this._buttons[buttonIndex] = {
  51242. pressed: newState.pressed,
  51243. touched: newState.touched,
  51244. value: newState.value
  51245. };
  51246. return;
  51247. }
  51248. this._checkChanges(newState, currentState);
  51249. if (this._changes.changed) {
  51250. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  51251. this.handleButtonChange(buttonIndex, newState, this._changes);
  51252. }
  51253. this._buttons[buttonIndex].pressed = newState.pressed;
  51254. this._buttons[buttonIndex].touched = newState.touched;
  51255. // oculus triggers are never 0, thou not touched.
  51256. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  51257. };
  51258. WebVRController.prototype._checkChanges = function (newState, currentState) {
  51259. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  51260. this._changes.touchChanged = newState.touched !== currentState.touched;
  51261. this._changes.valueChanged = newState.value !== currentState.value;
  51262. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  51263. return this._changes;
  51264. };
  51265. return WebVRController;
  51266. }(BABYLON.PoseEnabledController));
  51267. BABYLON.WebVRController = WebVRController;
  51268. })(BABYLON || (BABYLON = {}));
  51269. //# sourceMappingURL=babylon.webVRController.js.map
  51270. var BABYLON;
  51271. (function (BABYLON) {
  51272. var OculusTouchController = (function (_super) {
  51273. __extends(OculusTouchController, _super);
  51274. function OculusTouchController(vrGamepad) {
  51275. var _this = _super.call(this, vrGamepad) || this;
  51276. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  51277. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  51278. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  51279. return _this;
  51280. }
  51281. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  51282. var _this = this;
  51283. var meshName = this.hand === 'right' ? 'RightTouch.babylon' : 'LeftTouch.babylon';
  51284. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", meshName, scene, function (newMeshes) {
  51285. /*
  51286. Parent Mesh name: oculus_touch_left
  51287. - body
  51288. - trigger
  51289. - thumbstick
  51290. - grip
  51291. - button_y
  51292. - button_x
  51293. - button_enter
  51294. */
  51295. _this._defaultModel = newMeshes[1];
  51296. if (meshLoaded) {
  51297. meshLoaded(_this._defaultModel);
  51298. }
  51299. _this.attachToMesh(_this._defaultModel);
  51300. });
  51301. };
  51302. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  51303. // helper getters for left and right hand.
  51304. get: function () {
  51305. if (this.hand === 'right') {
  51306. return this.onMainButtonStateChangedObservable;
  51307. }
  51308. else {
  51309. throw new Error('No A button on left hand');
  51310. }
  51311. },
  51312. enumerable: true,
  51313. configurable: true
  51314. });
  51315. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  51316. get: function () {
  51317. if (this.hand === 'right') {
  51318. return this.onSecondaryButtonStateChangedObservable;
  51319. }
  51320. else {
  51321. throw new Error('No B button on left hand');
  51322. }
  51323. },
  51324. enumerable: true,
  51325. configurable: true
  51326. });
  51327. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  51328. get: function () {
  51329. if (this.hand === 'left') {
  51330. return this.onMainButtonStateChangedObservable;
  51331. }
  51332. else {
  51333. throw new Error('No X button on right hand');
  51334. }
  51335. },
  51336. enumerable: true,
  51337. configurable: true
  51338. });
  51339. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  51340. get: function () {
  51341. if (this.hand === 'left') {
  51342. return this.onSecondaryButtonStateChangedObservable;
  51343. }
  51344. else {
  51345. throw new Error('No Y button on right hand');
  51346. }
  51347. },
  51348. enumerable: true,
  51349. configurable: true
  51350. });
  51351. /*
  51352. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  51353. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  51354. 2) secondary trigger (same)
  51355. 3) A (right) X (left), touch, pressed = value
  51356. 4) B / Y
  51357. 5) thumb rest
  51358. */
  51359. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  51360. var notifyObject = state; //{ state: state, changes: changes };
  51361. var triggerDirection = this.hand === 'right' ? -1 : 1;
  51362. switch (buttonIdx) {
  51363. case 0:
  51364. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  51365. return;
  51366. case 1:// index trigger
  51367. if (this._defaultModel) {
  51368. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  51369. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  51370. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  51371. }
  51372. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  51373. return;
  51374. case 2:// secondary trigger
  51375. if (this._defaultModel) {
  51376. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  51377. }
  51378. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  51379. return;
  51380. case 3:
  51381. if (this._defaultModel) {
  51382. if (notifyObject.pressed) {
  51383. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  51384. }
  51385. else {
  51386. (this._defaultModel.getChildren()[1]).position.y = 0;
  51387. }
  51388. }
  51389. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  51390. return;
  51391. case 4:
  51392. if (this._defaultModel) {
  51393. if (notifyObject.pressed) {
  51394. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  51395. }
  51396. else {
  51397. (this._defaultModel.getChildren()[2]).position.y = 0;
  51398. }
  51399. }
  51400. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  51401. return;
  51402. case 5:
  51403. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  51404. return;
  51405. }
  51406. };
  51407. return OculusTouchController;
  51408. }(BABYLON.WebVRController));
  51409. BABYLON.OculusTouchController = OculusTouchController;
  51410. })(BABYLON || (BABYLON = {}));
  51411. //# sourceMappingURL=babylon.oculusTouchController.js.map
  51412. var BABYLON;
  51413. (function (BABYLON) {
  51414. var ViveController = (function (_super) {
  51415. __extends(ViveController, _super);
  51416. function ViveController(vrGamepad) {
  51417. var _this = _super.call(this, vrGamepad) || this;
  51418. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  51419. return _this;
  51420. }
  51421. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  51422. var _this = this;
  51423. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", "ViveWand.babylon", scene, function (newMeshes) {
  51424. /*
  51425. Parent Mesh name: ViveWand
  51426. - body
  51427. - r_gripper
  51428. - l_gripper
  51429. - menu_button
  51430. - system_button
  51431. - trackpad
  51432. - trigger
  51433. - LED
  51434. */
  51435. _this._defaultModel = newMeshes[1];
  51436. if (meshLoaded) {
  51437. meshLoaded(_this._defaultModel);
  51438. }
  51439. _this.attachToMesh(_this._defaultModel);
  51440. });
  51441. };
  51442. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  51443. get: function () {
  51444. return this.onMainButtonStateChangedObservable;
  51445. },
  51446. enumerable: true,
  51447. configurable: true
  51448. });
  51449. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  51450. get: function () {
  51451. return this.onMainButtonStateChangedObservable;
  51452. },
  51453. enumerable: true,
  51454. configurable: true
  51455. });
  51456. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  51457. get: function () {
  51458. return this.onSecondaryButtonStateChangedObservable;
  51459. },
  51460. enumerable: true,
  51461. configurable: true
  51462. });
  51463. /**
  51464. * Vive mapping:
  51465. * 0: touchpad
  51466. * 1: trigger
  51467. * 2: left AND right buttons
  51468. * 3: menu button
  51469. */
  51470. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  51471. var notifyObject = state; //{ state: state, changes: changes };
  51472. switch (buttonIdx) {
  51473. case 0:
  51474. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  51475. return;
  51476. case 1:// index trigger
  51477. if (this._defaultModel) {
  51478. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  51479. }
  51480. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  51481. return;
  51482. case 2:// left AND right button
  51483. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  51484. return;
  51485. case 3:
  51486. if (this._defaultModel) {
  51487. if (notifyObject.pressed) {
  51488. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  51489. }
  51490. else {
  51491. (this._defaultModel.getChildren()[2]).position.y = 0;
  51492. }
  51493. }
  51494. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  51495. return;
  51496. }
  51497. };
  51498. return ViveController;
  51499. }(BABYLON.WebVRController));
  51500. BABYLON.ViveController = ViveController;
  51501. })(BABYLON || (BABYLON = {}));
  51502. //# sourceMappingURL=babylon.viveController.js.map
  51503. var BABYLON;
  51504. (function (BABYLON) {
  51505. var GenericController = (function (_super) {
  51506. __extends(GenericController, _super);
  51507. function GenericController(vrGamepad) {
  51508. return _super.call(this, vrGamepad) || this;
  51509. }
  51510. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  51511. var _this = this;
  51512. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", "genericvrcontroller.babylon", scene, function (newMeshes) {
  51513. _this._defaultModel = newMeshes[1];
  51514. if (meshLoaded) {
  51515. meshLoaded(_this._defaultModel);
  51516. }
  51517. _this.attachToMesh(_this._defaultModel);
  51518. });
  51519. };
  51520. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  51521. console.log("Button id: " + buttonIdx + "state: ");
  51522. console.dir(state);
  51523. };
  51524. return GenericController;
  51525. }(BABYLON.WebVRController));
  51526. BABYLON.GenericController = GenericController;
  51527. })(BABYLON || (BABYLON = {}));
  51528. //# sourceMappingURL=babylon.genericController.js.map
  51529. /// <reference path="babylon.targetCamera.ts" />
  51530. var BABYLON;
  51531. (function (BABYLON) {
  51532. var FollowCamera = (function (_super) {
  51533. __extends(FollowCamera, _super);
  51534. function FollowCamera(name, position, scene, lockedTarget) {
  51535. var _this = _super.call(this, name, position, scene) || this;
  51536. _this.radius = 12;
  51537. _this.rotationOffset = 0;
  51538. _this.heightOffset = 4;
  51539. _this.cameraAcceleration = 0.05;
  51540. _this.maxCameraSpeed = 20;
  51541. _this.lockedTarget = lockedTarget;
  51542. return _this;
  51543. }
  51544. FollowCamera.prototype.getRadians = function (degrees) {
  51545. return degrees * Math.PI / 180;
  51546. };
  51547. FollowCamera.prototype.follow = function (cameraTarget) {
  51548. if (!cameraTarget)
  51549. return;
  51550. var yRotation;
  51551. if (cameraTarget.rotationQuaternion) {
  51552. var rotMatrix = new BABYLON.Matrix();
  51553. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  51554. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  51555. }
  51556. else {
  51557. yRotation = cameraTarget.rotation.y;
  51558. }
  51559. var radians = this.getRadians(this.rotationOffset) + yRotation;
  51560. var targetPosition = cameraTarget.getAbsolutePosition();
  51561. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  51562. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  51563. var dx = targetX - this.position.x;
  51564. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  51565. var dz = (targetZ) - this.position.z;
  51566. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  51567. var vy = dy * this.cameraAcceleration;
  51568. var vz = dz * this.cameraAcceleration * 2;
  51569. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  51570. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  51571. }
  51572. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  51573. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  51574. }
  51575. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  51576. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  51577. }
  51578. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  51579. this.setTarget(targetPosition);
  51580. };
  51581. FollowCamera.prototype._checkInputs = function () {
  51582. _super.prototype._checkInputs.call(this);
  51583. this.follow(this.lockedTarget);
  51584. };
  51585. FollowCamera.prototype.getClassName = function () {
  51586. return "FollowCamera";
  51587. };
  51588. __decorate([
  51589. BABYLON.serialize()
  51590. ], FollowCamera.prototype, "radius", void 0);
  51591. __decorate([
  51592. BABYLON.serialize()
  51593. ], FollowCamera.prototype, "rotationOffset", void 0);
  51594. __decorate([
  51595. BABYLON.serialize()
  51596. ], FollowCamera.prototype, "heightOffset", void 0);
  51597. __decorate([
  51598. BABYLON.serialize()
  51599. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  51600. __decorate([
  51601. BABYLON.serialize()
  51602. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  51603. __decorate([
  51604. BABYLON.serializeAsMeshReference("lockedTargetId")
  51605. ], FollowCamera.prototype, "lockedTarget", void 0);
  51606. return FollowCamera;
  51607. }(BABYLON.TargetCamera));
  51608. BABYLON.FollowCamera = FollowCamera;
  51609. var ArcFollowCamera = (function (_super) {
  51610. __extends(ArcFollowCamera, _super);
  51611. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  51612. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  51613. _this.alpha = alpha;
  51614. _this.beta = beta;
  51615. _this.radius = radius;
  51616. _this.target = target;
  51617. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  51618. _this.follow();
  51619. return _this;
  51620. }
  51621. ArcFollowCamera.prototype.follow = function () {
  51622. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  51623. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  51624. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  51625. var targetPosition = this.target.getAbsolutePosition();
  51626. this.position = targetPosition.add(this._cartesianCoordinates);
  51627. this.setTarget(targetPosition);
  51628. };
  51629. ArcFollowCamera.prototype._checkInputs = function () {
  51630. _super.prototype._checkInputs.call(this);
  51631. this.follow();
  51632. };
  51633. ArcFollowCamera.prototype.getClassName = function () {
  51634. return "ArcFollowCamera";
  51635. };
  51636. return ArcFollowCamera;
  51637. }(BABYLON.TargetCamera));
  51638. BABYLON.ArcFollowCamera = ArcFollowCamera;
  51639. })(BABYLON || (BABYLON = {}));
  51640. //# sourceMappingURL=babylon.followCamera.js.map
  51641. /// <reference path="babylon.touchCamera.ts" />
  51642. var BABYLON;
  51643. (function (BABYLON) {
  51644. // We're mainly based on the logic defined into the FreeCamera code
  51645. var UniversalCamera = (function (_super) {
  51646. __extends(UniversalCamera, _super);
  51647. //-- end properties for backward compatibility for inputs
  51648. function UniversalCamera(name, position, scene) {
  51649. var _this = _super.call(this, name, position, scene) || this;
  51650. _this.inputs.addGamepad();
  51651. return _this;
  51652. }
  51653. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  51654. //-- Begin properties for backward compatibility for inputs
  51655. get: function () {
  51656. var gamepad = this.inputs.attached["gamepad"];
  51657. if (gamepad)
  51658. return gamepad.gamepadAngularSensibility;
  51659. },
  51660. set: function (value) {
  51661. var gamepad = this.inputs.attached["gamepad"];
  51662. if (gamepad)
  51663. gamepad.gamepadAngularSensibility = value;
  51664. },
  51665. enumerable: true,
  51666. configurable: true
  51667. });
  51668. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  51669. get: function () {
  51670. var gamepad = this.inputs.attached["gamepad"];
  51671. if (gamepad)
  51672. return gamepad.gamepadMoveSensibility;
  51673. },
  51674. set: function (value) {
  51675. var gamepad = this.inputs.attached["gamepad"];
  51676. if (gamepad)
  51677. gamepad.gamepadMoveSensibility = value;
  51678. },
  51679. enumerable: true,
  51680. configurable: true
  51681. });
  51682. UniversalCamera.prototype.getClassName = function () {
  51683. return "UniversalCamera";
  51684. };
  51685. return UniversalCamera;
  51686. }(BABYLON.TouchCamera));
  51687. BABYLON.UniversalCamera = UniversalCamera;
  51688. })(BABYLON || (BABYLON = {}));
  51689. //# sourceMappingURL=babylon.universalCamera.js.map
  51690. /// <reference path="babylon.universalCamera.ts" />
  51691. var BABYLON;
  51692. (function (BABYLON) {
  51693. // We're mainly based on the logic defined into the FreeCamera code
  51694. var GamepadCamera = (function (_super) {
  51695. __extends(GamepadCamera, _super);
  51696. //-- end properties for backward compatibility for inputs
  51697. function GamepadCamera(name, position, scene) {
  51698. return _super.call(this, name, position, scene) || this;
  51699. }
  51700. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  51701. //-- Begin properties for backward compatibility for inputs
  51702. get: function () {
  51703. var gamepad = this.inputs.attached["gamepad"];
  51704. if (gamepad)
  51705. return gamepad.gamepadAngularSensibility;
  51706. },
  51707. set: function (value) {
  51708. var gamepad = this.inputs.attached["gamepad"];
  51709. if (gamepad)
  51710. gamepad.gamepadAngularSensibility = value;
  51711. },
  51712. enumerable: true,
  51713. configurable: true
  51714. });
  51715. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  51716. get: function () {
  51717. var gamepad = this.inputs.attached["gamepad"];
  51718. if (gamepad)
  51719. return gamepad.gamepadMoveSensibility;
  51720. },
  51721. set: function (value) {
  51722. var gamepad = this.inputs.attached["gamepad"];
  51723. if (gamepad)
  51724. gamepad.gamepadMoveSensibility = value;
  51725. },
  51726. enumerable: true,
  51727. configurable: true
  51728. });
  51729. GamepadCamera.prototype.getClassName = function () {
  51730. return "GamepadCamera";
  51731. };
  51732. return GamepadCamera;
  51733. }(BABYLON.UniversalCamera));
  51734. BABYLON.GamepadCamera = GamepadCamera;
  51735. })(BABYLON || (BABYLON = {}));
  51736. //# sourceMappingURL=babylon.gamepadCamera.js.map
  51737. var BABYLON;
  51738. (function (BABYLON) {
  51739. var PostProcessRenderPipelineManager = (function () {
  51740. function PostProcessRenderPipelineManager() {
  51741. this._renderPipelines = {};
  51742. }
  51743. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  51744. this._renderPipelines[renderPipeline._name] = renderPipeline;
  51745. };
  51746. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  51747. var renderPipeline = this._renderPipelines[renderPipelineName];
  51748. if (!renderPipeline) {
  51749. return;
  51750. }
  51751. renderPipeline._attachCameras(cameras, unique);
  51752. };
  51753. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  51754. var renderPipeline = this._renderPipelines[renderPipelineName];
  51755. if (!renderPipeline) {
  51756. return;
  51757. }
  51758. renderPipeline._detachCameras(cameras);
  51759. };
  51760. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  51761. var renderPipeline = this._renderPipelines[renderPipelineName];
  51762. if (!renderPipeline) {
  51763. return;
  51764. }
  51765. renderPipeline._enableEffect(renderEffectName, cameras);
  51766. };
  51767. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  51768. var renderPipeline = this._renderPipelines[renderPipelineName];
  51769. if (!renderPipeline) {
  51770. return;
  51771. }
  51772. renderPipeline._disableEffect(renderEffectName, cameras);
  51773. };
  51774. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  51775. var renderPipeline = this._renderPipelines[renderPipelineName];
  51776. if (!renderPipeline) {
  51777. return;
  51778. }
  51779. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  51780. };
  51781. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  51782. var renderPipeline = this._renderPipelines[renderPipelineName];
  51783. if (!renderPipeline) {
  51784. return;
  51785. }
  51786. renderPipeline._disableDisplayOnlyPass(cameras);
  51787. };
  51788. PostProcessRenderPipelineManager.prototype.update = function () {
  51789. for (var renderPipelineName in this._renderPipelines) {
  51790. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  51791. var pipeline = this._renderPipelines[renderPipelineName];
  51792. if (!pipeline.isSupported) {
  51793. pipeline.dispose();
  51794. delete this._renderPipelines[renderPipelineName];
  51795. }
  51796. else {
  51797. pipeline._update();
  51798. }
  51799. }
  51800. }
  51801. };
  51802. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  51803. for (var renderPipelineName in this._renderPipelines) {
  51804. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  51805. var pipeline = this._renderPipelines[renderPipelineName];
  51806. pipeline._rebuild();
  51807. }
  51808. }
  51809. };
  51810. PostProcessRenderPipelineManager.prototype.dispose = function () {
  51811. for (var renderPipelineName in this._renderPipelines) {
  51812. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  51813. var pipeline = this._renderPipelines[renderPipelineName];
  51814. pipeline.dispose();
  51815. }
  51816. }
  51817. };
  51818. return PostProcessRenderPipelineManager;
  51819. }());
  51820. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  51821. })(BABYLON || (BABYLON = {}));
  51822. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  51823. var BABYLON;
  51824. (function (BABYLON) {
  51825. var PostProcessRenderPass = (function () {
  51826. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  51827. this._enabled = true;
  51828. this._refCount = 0;
  51829. this._name = name;
  51830. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  51831. this.setRenderList(renderList);
  51832. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  51833. this._renderTexture.onAfterRenderObservable.add(afterRender);
  51834. this._scene = scene;
  51835. this._renderList = renderList;
  51836. }
  51837. // private
  51838. PostProcessRenderPass.prototype._incRefCount = function () {
  51839. if (this._refCount === 0) {
  51840. this._scene.customRenderTargets.push(this._renderTexture);
  51841. }
  51842. return ++this._refCount;
  51843. };
  51844. PostProcessRenderPass.prototype._decRefCount = function () {
  51845. this._refCount--;
  51846. if (this._refCount <= 0) {
  51847. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  51848. }
  51849. return this._refCount;
  51850. };
  51851. PostProcessRenderPass.prototype._update = function () {
  51852. this.setRenderList(this._renderList);
  51853. };
  51854. // public
  51855. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  51856. this._renderTexture.renderList = renderList;
  51857. };
  51858. PostProcessRenderPass.prototype.getRenderTexture = function () {
  51859. return this._renderTexture;
  51860. };
  51861. return PostProcessRenderPass;
  51862. }());
  51863. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  51864. })(BABYLON || (BABYLON = {}));
  51865. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  51866. var BABYLON;
  51867. (function (BABYLON) {
  51868. var PostProcessRenderEffect = (function () {
  51869. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  51870. this._engine = engine;
  51871. this._name = name;
  51872. this._singleInstance = singleInstance || true;
  51873. this._getPostProcess = getPostProcess;
  51874. this._cameras = [];
  51875. this._indicesForCamera = [];
  51876. this._postProcesses = {};
  51877. this._renderPasses = {};
  51878. this._renderEffectAsPasses = {};
  51879. }
  51880. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  51881. get: function () {
  51882. for (var index in this._postProcesses) {
  51883. if (!this._postProcesses[index].isSupported) {
  51884. return false;
  51885. }
  51886. }
  51887. return true;
  51888. },
  51889. enumerable: true,
  51890. configurable: true
  51891. });
  51892. PostProcessRenderEffect.prototype._update = function () {
  51893. for (var renderPassName in this._renderPasses) {
  51894. this._renderPasses[renderPassName]._update();
  51895. }
  51896. };
  51897. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  51898. this._renderPasses[renderPass._name] = renderPass;
  51899. this._linkParameters();
  51900. };
  51901. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  51902. delete this._renderPasses[renderPass._name];
  51903. this._linkParameters();
  51904. };
  51905. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  51906. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  51907. this._linkParameters();
  51908. };
  51909. PostProcessRenderEffect.prototype.getPass = function (passName) {
  51910. for (var renderPassName in this._renderPasses) {
  51911. if (renderPassName === passName) {
  51912. return this._renderPasses[passName];
  51913. }
  51914. }
  51915. };
  51916. PostProcessRenderEffect.prototype.emptyPasses = function () {
  51917. this._renderPasses = {};
  51918. this._linkParameters();
  51919. };
  51920. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  51921. var cameraKey;
  51922. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  51923. for (var i = 0; i < _cam.length; i++) {
  51924. var camera = _cam[i];
  51925. var cameraName = camera.name;
  51926. if (this._singleInstance) {
  51927. cameraKey = 0;
  51928. }
  51929. else {
  51930. cameraKey = cameraName;
  51931. }
  51932. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  51933. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  51934. if (!this._indicesForCamera[cameraName]) {
  51935. this._indicesForCamera[cameraName] = [];
  51936. }
  51937. this._indicesForCamera[cameraName].push(index);
  51938. if (this._cameras.indexOf(camera) === -1) {
  51939. this._cameras[cameraName] = camera;
  51940. }
  51941. for (var passName in this._renderPasses) {
  51942. this._renderPasses[passName]._incRefCount();
  51943. }
  51944. }
  51945. this._linkParameters();
  51946. };
  51947. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  51948. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  51949. for (var i = 0; i < _cam.length; i++) {
  51950. var camera = _cam[i];
  51951. var cameraName = camera.name;
  51952. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  51953. var index = this._cameras.indexOf(cameraName);
  51954. this._indicesForCamera.splice(index, 1);
  51955. this._cameras.splice(index, 1);
  51956. for (var passName in this._renderPasses) {
  51957. this._renderPasses[passName]._decRefCount();
  51958. }
  51959. }
  51960. };
  51961. PostProcessRenderEffect.prototype._enable = function (cameras) {
  51962. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  51963. for (var i = 0; i < _cam.length; i++) {
  51964. var camera = _cam[i];
  51965. var cameraName = camera.name;
  51966. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  51967. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  51968. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  51969. }
  51970. }
  51971. for (var passName in this._renderPasses) {
  51972. this._renderPasses[passName]._incRefCount();
  51973. }
  51974. }
  51975. };
  51976. PostProcessRenderEffect.prototype._disable = function (cameras) {
  51977. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  51978. for (var i = 0; i < _cam.length; i++) {
  51979. var camera = _cam[i];
  51980. var cameraName = camera.Name;
  51981. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  51982. for (var passName in this._renderPasses) {
  51983. this._renderPasses[passName]._decRefCount();
  51984. }
  51985. }
  51986. };
  51987. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  51988. if (this._singleInstance) {
  51989. return this._postProcesses[0];
  51990. }
  51991. else {
  51992. return this._postProcesses[camera.name];
  51993. }
  51994. };
  51995. PostProcessRenderEffect.prototype._linkParameters = function () {
  51996. var _this = this;
  51997. for (var index in this._postProcesses) {
  51998. if (this.applyParameters) {
  51999. this.applyParameters(this._postProcesses[index]);
  52000. }
  52001. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  52002. _this._linkTextures(effect);
  52003. });
  52004. }
  52005. };
  52006. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  52007. for (var renderPassName in this._renderPasses) {
  52008. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  52009. }
  52010. for (var renderEffectName in this._renderEffectAsPasses) {
  52011. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  52012. }
  52013. };
  52014. return PostProcessRenderEffect;
  52015. }());
  52016. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  52017. })(BABYLON || (BABYLON = {}));
  52018. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  52019. var BABYLON;
  52020. (function (BABYLON) {
  52021. var PostProcessRenderPipeline = (function () {
  52022. function PostProcessRenderPipeline(engine, name) {
  52023. this._engine = engine;
  52024. this._name = name;
  52025. this._renderEffects = new Array();
  52026. this._renderEffectsForIsolatedPass = new Array();
  52027. this._cameras = [];
  52028. }
  52029. PostProcessRenderPipeline.prototype.getClassName = function () {
  52030. return "PostProcessRenderPipeline";
  52031. };
  52032. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  52033. get: function () {
  52034. for (var renderEffectName in this._renderEffects) {
  52035. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  52036. if (!this._renderEffects[renderEffectName].isSupported) {
  52037. return false;
  52038. }
  52039. }
  52040. }
  52041. return true;
  52042. },
  52043. enumerable: true,
  52044. configurable: true
  52045. });
  52046. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  52047. this._renderEffects[renderEffect._name] = renderEffect;
  52048. };
  52049. // private
  52050. PostProcessRenderPipeline.prototype._rebuild = function () {
  52051. };
  52052. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  52053. var renderEffects = this._renderEffects[renderEffectName];
  52054. if (!renderEffects) {
  52055. return;
  52056. }
  52057. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  52058. };
  52059. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  52060. var renderEffects = this._renderEffects[renderEffectName];
  52061. if (!renderEffects) {
  52062. return;
  52063. }
  52064. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  52065. };
  52066. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  52067. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  52068. var indicesToDelete = [];
  52069. var i;
  52070. for (i = 0; i < _cam.length; i++) {
  52071. var camera = _cam[i];
  52072. var cameraName = camera.name;
  52073. if (this._cameras.indexOf(camera) === -1) {
  52074. this._cameras[cameraName] = camera;
  52075. }
  52076. else if (unique) {
  52077. indicesToDelete.push(i);
  52078. }
  52079. }
  52080. for (i = 0; i < indicesToDelete.length; i++) {
  52081. cameras.splice(indicesToDelete[i], 1);
  52082. }
  52083. for (var renderEffectName in this._renderEffects) {
  52084. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  52085. this._renderEffects[renderEffectName]._attachCameras(_cam);
  52086. }
  52087. }
  52088. };
  52089. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  52090. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  52091. for (var renderEffectName in this._renderEffects) {
  52092. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  52093. this._renderEffects[renderEffectName]._detachCameras(_cam);
  52094. }
  52095. }
  52096. for (var i = 0; i < _cam.length; i++) {
  52097. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  52098. }
  52099. };
  52100. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  52101. var _this = this;
  52102. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  52103. var pass = null;
  52104. var renderEffectName;
  52105. for (renderEffectName in this._renderEffects) {
  52106. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  52107. pass = this._renderEffects[renderEffectName].getPass(passName);
  52108. if (pass != null) {
  52109. break;
  52110. }
  52111. }
  52112. }
  52113. if (pass === null) {
  52114. return;
  52115. }
  52116. for (renderEffectName in this._renderEffects) {
  52117. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  52118. this._renderEffects[renderEffectName]._disable(_cam);
  52119. }
  52120. }
  52121. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  52122. for (var i = 0; i < _cam.length; i++) {
  52123. var camera = _cam[i];
  52124. var cameraName = camera.name;
  52125. 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); });
  52126. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  52127. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  52128. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  52129. }
  52130. };
  52131. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  52132. var _this = this;
  52133. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  52134. for (var i = 0; i < _cam.length; i++) {
  52135. var camera = _cam[i];
  52136. var cameraName = camera.name;
  52137. 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); });
  52138. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  52139. }
  52140. for (var renderEffectName in this._renderEffects) {
  52141. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  52142. this._renderEffects[renderEffectName]._enable(_cam);
  52143. }
  52144. }
  52145. };
  52146. PostProcessRenderPipeline.prototype._update = function () {
  52147. for (var renderEffectName in this._renderEffects) {
  52148. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  52149. this._renderEffects[renderEffectName]._update();
  52150. }
  52151. }
  52152. for (var i = 0; i < this._cameras.length; i++) {
  52153. var cameraName = this._cameras[i].name;
  52154. if (this._renderEffectsForIsolatedPass[cameraName]) {
  52155. this._renderEffectsForIsolatedPass[cameraName]._update();
  52156. }
  52157. }
  52158. };
  52159. PostProcessRenderPipeline.prototype._reset = function () {
  52160. this._renderEffects = new Array();
  52161. this._renderEffectsForIsolatedPass = new Array();
  52162. };
  52163. PostProcessRenderPipeline.prototype.dispose = function () {
  52164. // Must be implemented by children
  52165. };
  52166. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  52167. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  52168. __decorate([
  52169. BABYLON.serialize()
  52170. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  52171. return PostProcessRenderPipeline;
  52172. }());
  52173. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  52174. })(BABYLON || (BABYLON = {}));
  52175. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  52176. var BABYLON;
  52177. (function (BABYLON) {
  52178. var DepthRenderer = (function () {
  52179. function DepthRenderer(scene, type) {
  52180. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  52181. var _this = this;
  52182. this._viewMatrix = BABYLON.Matrix.Zero();
  52183. this._projectionMatrix = BABYLON.Matrix.Zero();
  52184. this._transformMatrix = BABYLON.Matrix.Zero();
  52185. this._worldViewProjection = BABYLON.Matrix.Zero();
  52186. this._scene = scene;
  52187. var engine = scene.getEngine();
  52188. // Render target
  52189. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  52190. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52191. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52192. this._depthMap.refreshRate = 1;
  52193. this._depthMap.renderParticles = false;
  52194. this._depthMap.renderList = null;
  52195. // set default depth value to 1.0 (far away)
  52196. this._depthMap.onClearObservable.add(function (engine) {
  52197. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  52198. });
  52199. // Custom render function
  52200. var renderSubMesh = function (subMesh) {
  52201. var mesh = subMesh.getRenderingMesh();
  52202. var scene = _this._scene;
  52203. var engine = scene.getEngine();
  52204. // Culling
  52205. engine.setState(subMesh.getMaterial().backFaceCulling);
  52206. // Managing instances
  52207. var batch = mesh._getInstancesRenderList(subMesh._id);
  52208. if (batch.mustReturn) {
  52209. return;
  52210. }
  52211. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  52212. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  52213. engine.enableEffect(_this._effect);
  52214. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  52215. var material = subMesh.getMaterial();
  52216. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  52217. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  52218. // Alpha test
  52219. if (material && material.needAlphaTesting()) {
  52220. var alphaTexture = material.getAlphaTestTexture();
  52221. _this._effect.setTexture("diffuseSampler", alphaTexture);
  52222. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  52223. }
  52224. // Bones
  52225. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52226. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  52227. }
  52228. // Draw
  52229. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  52230. }
  52231. };
  52232. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  52233. var index;
  52234. for (index = 0; index < opaqueSubMeshes.length; index++) {
  52235. renderSubMesh(opaqueSubMeshes.data[index]);
  52236. }
  52237. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  52238. renderSubMesh(alphaTestSubMeshes.data[index]);
  52239. }
  52240. };
  52241. }
  52242. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  52243. var material = subMesh.getMaterial();
  52244. if (material.disableDepthWrite) {
  52245. return false;
  52246. }
  52247. var defines = [];
  52248. var attribs = [BABYLON.VertexBuffer.PositionKind];
  52249. var mesh = subMesh.getMesh();
  52250. var scene = mesh.getScene();
  52251. // Alpha test
  52252. if (material && material.needAlphaTesting()) {
  52253. defines.push("#define ALPHATEST");
  52254. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  52255. attribs.push(BABYLON.VertexBuffer.UVKind);
  52256. defines.push("#define UV1");
  52257. }
  52258. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  52259. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  52260. defines.push("#define UV2");
  52261. }
  52262. }
  52263. // Bones
  52264. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52265. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52266. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52267. if (mesh.numBoneInfluencers > 4) {
  52268. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  52269. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  52270. }
  52271. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52272. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52273. }
  52274. else {
  52275. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52276. }
  52277. // Instances
  52278. if (useInstances) {
  52279. defines.push("#define INSTANCES");
  52280. attribs.push("world0");
  52281. attribs.push("world1");
  52282. attribs.push("world2");
  52283. attribs.push("world3");
  52284. }
  52285. // Get correct effect
  52286. var join = defines.join("\n");
  52287. if (this._cachedDefines !== join) {
  52288. this._cachedDefines = join;
  52289. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  52290. }
  52291. return this._effect.isReady();
  52292. };
  52293. DepthRenderer.prototype.getDepthMap = function () {
  52294. return this._depthMap;
  52295. };
  52296. // Methods
  52297. DepthRenderer.prototype.dispose = function () {
  52298. this._depthMap.dispose();
  52299. };
  52300. return DepthRenderer;
  52301. }());
  52302. BABYLON.DepthRenderer = DepthRenderer;
  52303. })(BABYLON || (BABYLON = {}));
  52304. //# sourceMappingURL=babylon.depthRenderer.js.map
  52305. var BABYLON;
  52306. (function (BABYLON) {
  52307. var SSAORenderingPipeline = (function (_super) {
  52308. __extends(SSAORenderingPipeline, _super);
  52309. /**
  52310. * @constructor
  52311. * @param {string} name - The rendering pipeline name
  52312. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  52313. * @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 }
  52314. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  52315. */
  52316. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  52317. var _this = _super.call(this, scene.getEngine(), name) || this;
  52318. // Members
  52319. /**
  52320. * The PassPostProcess id in the pipeline that contains the original scene color
  52321. * @type {string}
  52322. */
  52323. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  52324. /**
  52325. * The SSAO PostProcess id in the pipeline
  52326. * @type {string}
  52327. */
  52328. _this.SSAORenderEffect = "SSAORenderEffect";
  52329. /**
  52330. * The horizontal blur PostProcess id in the pipeline
  52331. * @type {string}
  52332. */
  52333. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  52334. /**
  52335. * The vertical blur PostProcess id in the pipeline
  52336. * @type {string}
  52337. */
  52338. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  52339. /**
  52340. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  52341. * @type {string}
  52342. */
  52343. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  52344. /**
  52345. * The output strength of the SSAO post-process. Default value is 1.0.
  52346. * @type {number}
  52347. */
  52348. _this.totalStrength = 1.0;
  52349. /**
  52350. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  52351. * @type {number}
  52352. */
  52353. _this.radius = 0.0001;
  52354. /**
  52355. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  52356. * Must not be equal to fallOff and superior to fallOff.
  52357. * Default value is 0.975
  52358. * @type {number}
  52359. */
  52360. _this.area = 0.0075;
  52361. /**
  52362. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  52363. * Must not be equal to area and inferior to area.
  52364. * Default value is 0.0
  52365. * @type {number}
  52366. */
  52367. _this.fallOff = 0.000001;
  52368. /**
  52369. * The base color of the SSAO post-process
  52370. * The final result is "base + ssao" between [0, 1]
  52371. * @type {number}
  52372. */
  52373. _this.base = 0.5;
  52374. _this._firstUpdate = true;
  52375. _this._scene = scene;
  52376. // Set up assets
  52377. _this._createRandomTexture();
  52378. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  52379. var ssaoRatio = ratio.ssaoRatio || ratio;
  52380. var combineRatio = ratio.combineRatio || ratio;
  52381. _this._ratio = {
  52382. ssaoRatio: ssaoRatio,
  52383. combineRatio: combineRatio
  52384. };
  52385. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  52386. _this._createSSAOPostProcess(ssaoRatio);
  52387. _this._createBlurPostProcess(ssaoRatio);
  52388. _this._createSSAOCombinePostProcess(combineRatio);
  52389. // Set up pipeline
  52390. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  52391. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  52392. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  52393. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  52394. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  52395. // Finish
  52396. scene.postProcessRenderPipelineManager.addPipeline(_this);
  52397. if (cameras)
  52398. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  52399. return _this;
  52400. }
  52401. // Public Methods
  52402. /**
  52403. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  52404. */
  52405. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  52406. if (disableDepthRender === void 0) { disableDepthRender = false; }
  52407. for (var i = 0; i < this._scene.cameras.length; i++) {
  52408. var camera = this._scene.cameras[i];
  52409. this._originalColorPostProcess.dispose(camera);
  52410. this._ssaoPostProcess.dispose(camera);
  52411. this._blurHPostProcess.dispose(camera);
  52412. this._blurVPostProcess.dispose(camera);
  52413. this._ssaoCombinePostProcess.dispose(camera);
  52414. }
  52415. this._randomTexture.dispose();
  52416. if (disableDepthRender)
  52417. this._scene.disableDepthRenderer();
  52418. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  52419. _super.prototype.dispose.call(this);
  52420. };
  52421. // Private Methods
  52422. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  52423. var _this = this;
  52424. /*
  52425. var samplerOffsets = [
  52426. -8.0, -6.0, -4.0, -2.0,
  52427. 0.0,
  52428. 2.0, 4.0, 6.0, 8.0
  52429. ];
  52430. */
  52431. var samples = 16;
  52432. var samplerOffsets = [];
  52433. for (var i = -8; i < 8; i++) {
  52434. samplerOffsets.push(i * 2);
  52435. }
  52436. 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");
  52437. this._blurHPostProcess.onApply = function (effect) {
  52438. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  52439. effect.setTexture("depthSampler", _this._depthTexture);
  52440. if (_this._firstUpdate) {
  52441. effect.setArray("samplerOffsets", samplerOffsets);
  52442. }
  52443. };
  52444. 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");
  52445. this._blurVPostProcess.onApply = function (effect) {
  52446. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  52447. effect.setTexture("depthSampler", _this._depthTexture);
  52448. if (_this._firstUpdate) {
  52449. effect.setArray("samplerOffsets", samplerOffsets);
  52450. _this._firstUpdate = false;
  52451. }
  52452. };
  52453. };
  52454. SSAORenderingPipeline.prototype._rebuild = function () {
  52455. this._firstUpdate = true;
  52456. _super.prototype._rebuild.call(this);
  52457. };
  52458. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  52459. var _this = this;
  52460. var numSamples = 16;
  52461. var sampleSphere = [
  52462. 0.5381, 0.1856, -0.4319,
  52463. 0.1379, 0.2486, 0.4430,
  52464. 0.3371, 0.5679, -0.0057,
  52465. -0.6999, -0.0451, -0.0019,
  52466. 0.0689, -0.1598, -0.8547,
  52467. 0.0560, 0.0069, -0.1843,
  52468. -0.0146, 0.1402, 0.0762,
  52469. 0.0100, -0.1924, -0.0344,
  52470. -0.3577, -0.5301, -0.4358,
  52471. -0.3169, 0.1063, 0.0158,
  52472. 0.0103, -0.5869, 0.0046,
  52473. -0.0897, -0.4940, 0.3287,
  52474. 0.7119, -0.0154, -0.0918,
  52475. -0.0533, 0.0596, -0.5411,
  52476. 0.0352, -0.0631, 0.5460,
  52477. -0.4776, 0.2847, -0.0271
  52478. ];
  52479. var samplesFactor = 1.0 / numSamples;
  52480. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  52481. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  52482. "area", "fallOff", "base", "range", "viewport"
  52483. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  52484. var viewport = new BABYLON.Vector2(0, 0);
  52485. this._ssaoPostProcess.onApply = function (effect) {
  52486. if (_this._firstUpdate) {
  52487. effect.setArray3("sampleSphere", sampleSphere);
  52488. effect.setFloat("samplesFactor", samplesFactor);
  52489. effect.setFloat("randTextureTiles", 4.0);
  52490. }
  52491. effect.setFloat("totalStrength", _this.totalStrength);
  52492. effect.setFloat("radius", _this.radius);
  52493. effect.setFloat("area", _this.area);
  52494. effect.setFloat("fallOff", _this.fallOff);
  52495. effect.setFloat("base", _this.base);
  52496. effect.setTexture("textureSampler", _this._depthTexture);
  52497. effect.setTexture("randomSampler", _this._randomTexture);
  52498. };
  52499. };
  52500. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  52501. var _this = this;
  52502. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  52503. this._ssaoCombinePostProcess.onApply = function (effect) {
  52504. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  52505. };
  52506. };
  52507. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  52508. var size = 512;
  52509. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  52510. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52511. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52512. var context = this._randomTexture.getContext();
  52513. var rand = function (min, max) {
  52514. return Math.random() * (max - min) + min;
  52515. };
  52516. var randVector = BABYLON.Vector3.Zero();
  52517. for (var x = 0; x < size; x++) {
  52518. for (var y = 0; y < size; y++) {
  52519. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  52520. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  52521. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  52522. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  52523. context.fillRect(x, y, 1, 1);
  52524. }
  52525. }
  52526. this._randomTexture.update(false);
  52527. };
  52528. __decorate([
  52529. BABYLON.serialize()
  52530. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  52531. __decorate([
  52532. BABYLON.serialize()
  52533. ], SSAORenderingPipeline.prototype, "radius", void 0);
  52534. __decorate([
  52535. BABYLON.serialize()
  52536. ], SSAORenderingPipeline.prototype, "area", void 0);
  52537. __decorate([
  52538. BABYLON.serialize()
  52539. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  52540. __decorate([
  52541. BABYLON.serialize()
  52542. ], SSAORenderingPipeline.prototype, "base", void 0);
  52543. __decorate([
  52544. BABYLON.serialize()
  52545. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  52546. return SSAORenderingPipeline;
  52547. }(BABYLON.PostProcessRenderPipeline));
  52548. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  52549. })(BABYLON || (BABYLON = {}));
  52550. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  52551. var BABYLON;
  52552. (function (BABYLON) {
  52553. var SSAO2RenderingPipeline = (function (_super) {
  52554. __extends(SSAO2RenderingPipeline, _super);
  52555. /**
  52556. * @constructor
  52557. * @param {string} name - The rendering pipeline name
  52558. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  52559. * @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 }
  52560. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  52561. */
  52562. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  52563. var _this = _super.call(this, scene.getEngine(), name) || this;
  52564. // Members
  52565. /**
  52566. * The PassPostProcess id in the pipeline that contains the original scene color
  52567. * @type {string}
  52568. */
  52569. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  52570. /**
  52571. * The SSAO PostProcess id in the pipeline
  52572. * @type {string}
  52573. */
  52574. _this.SSAORenderEffect = "SSAORenderEffect";
  52575. /**
  52576. * The horizontal blur PostProcess id in the pipeline
  52577. * @type {string}
  52578. */
  52579. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  52580. /**
  52581. * The vertical blur PostProcess id in the pipeline
  52582. * @type {string}
  52583. */
  52584. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  52585. /**
  52586. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  52587. * @type {string}
  52588. */
  52589. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  52590. /**
  52591. * The output strength of the SSAO post-process. Default value is 1.0.
  52592. * @type {number}
  52593. */
  52594. _this.totalStrength = 1.0;
  52595. /**
  52596. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  52597. * @type {number}
  52598. */
  52599. _this.maxZ = 100.0;
  52600. /**
  52601. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  52602. * @type {number}
  52603. */
  52604. _this.minZAspect = 0.2;
  52605. /**
  52606. * Number of samples used for the SSAO calculations. Default value is 8
  52607. * @type {number}
  52608. */
  52609. _this._samples = 8;
  52610. /**
  52611. * Are we using bilateral blur ?
  52612. * @type {boolean}
  52613. */
  52614. _this._expensiveBlur = true;
  52615. /**
  52616. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  52617. * @type {number}
  52618. */
  52619. _this.radius = 2.0;
  52620. /**
  52621. * The base color of the SSAO post-process
  52622. * The final result is "base + ssao" between [0, 1]
  52623. * @type {number}
  52624. */
  52625. _this.base = 0.1;
  52626. _this._firstUpdate = true;
  52627. _this._scene = scene;
  52628. if (!_this.isSupported) {
  52629. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  52630. return _this;
  52631. }
  52632. var ssaoRatio = ratio.ssaoRatio || ratio;
  52633. var blurRatio = ratio.blurRatio || ratio;
  52634. _this._ratio = {
  52635. ssaoRatio: ssaoRatio,
  52636. blurRatio: blurRatio
  52637. };
  52638. // Set up assets
  52639. _this._createRandomTexture();
  52640. _this._depthTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[0];
  52641. _this._normalTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[1];
  52642. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  52643. _this._createSSAOPostProcess(1.0);
  52644. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  52645. _this._createSSAOCombinePostProcess(blurRatio);
  52646. // Set up pipeline
  52647. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  52648. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  52649. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  52650. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  52651. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  52652. // Finish
  52653. scene.postProcessRenderPipelineManager.addPipeline(_this);
  52654. if (cameras)
  52655. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  52656. return _this;
  52657. }
  52658. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  52659. get: function () {
  52660. return this._samples;
  52661. },
  52662. set: function (n) {
  52663. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  52664. this._samples = n;
  52665. this._sampleSphere = this._generateHemisphere();
  52666. this._firstUpdate = true;
  52667. },
  52668. enumerable: true,
  52669. configurable: true
  52670. });
  52671. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  52672. get: function () {
  52673. return this._expensiveBlur;
  52674. },
  52675. set: function (b) {
  52676. 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"]);
  52677. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  52678. this._expensiveBlur = b;
  52679. this._firstUpdate = true;
  52680. },
  52681. enumerable: true,
  52682. configurable: true
  52683. });
  52684. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  52685. /**
  52686. * Support test.
  52687. * @type {boolean}
  52688. */
  52689. get: function () {
  52690. var engine = BABYLON.Engine.LastCreatedEngine;
  52691. return engine.webGLVersion > 1;
  52692. },
  52693. enumerable: true,
  52694. configurable: true
  52695. });
  52696. // Public Methods
  52697. /**
  52698. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  52699. */
  52700. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  52701. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  52702. for (var i = 0; i < this._scene.cameras.length; i++) {
  52703. var camera = this._scene.cameras[i];
  52704. this._originalColorPostProcess.dispose(camera);
  52705. this._ssaoPostProcess.dispose(camera);
  52706. this._blurHPostProcess.dispose(camera);
  52707. this._blurVPostProcess.dispose(camera);
  52708. this._ssaoCombinePostProcess.dispose(camera);
  52709. }
  52710. this._randomTexture.dispose();
  52711. if (disableGeometryBufferRenderer)
  52712. this._scene.disableGeometryBufferRenderer();
  52713. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  52714. _super.prototype.dispose.call(this);
  52715. };
  52716. // Private Methods
  52717. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  52718. var _this = this;
  52719. var samples = 16;
  52720. this._samplerOffsets = [];
  52721. var expensive = this.expensiveBlur;
  52722. for (var i = -8; i < 8; i++) {
  52723. this._samplerOffsets.push(i * 2 + 0.5);
  52724. }
  52725. 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");
  52726. this._blurHPostProcess.onApply = function (effect) {
  52727. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  52728. effect.setFloat("near", _this._scene.activeCamera.minZ);
  52729. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  52730. effect.setFloat("radius", _this.radius);
  52731. effect.setTexture("depthSampler", _this._depthTexture);
  52732. if (_this._firstUpdate) {
  52733. effect.setArray("samplerOffsets", _this._samplerOffsets);
  52734. }
  52735. };
  52736. 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");
  52737. this._blurVPostProcess.onApply = function (effect) {
  52738. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  52739. effect.setFloat("near", _this._scene.activeCamera.minZ);
  52740. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  52741. effect.setFloat("radius", _this.radius);
  52742. effect.setTexture("depthSampler", _this._depthTexture);
  52743. if (_this._firstUpdate) {
  52744. effect.setArray("samplerOffsets", _this._samplerOffsets);
  52745. _this._firstUpdate = false;
  52746. }
  52747. };
  52748. };
  52749. SSAO2RenderingPipeline.prototype._rebuild = function () {
  52750. this._firstUpdate = true;
  52751. _super.prototype._rebuild.call(this);
  52752. };
  52753. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  52754. var numSamples = this.samples;
  52755. var result = [];
  52756. var vector, scale;
  52757. var rand = function (min, max) {
  52758. return Math.random() * (max - min) + min;
  52759. };
  52760. var lerp = function (start, end, percent) {
  52761. return (start + percent * (end - start));
  52762. };
  52763. var i = 0;
  52764. var normal = new BABYLON.Vector3(0, 0, 1);
  52765. while (i < numSamples) {
  52766. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  52767. vector.normalize();
  52768. scale = i / numSamples;
  52769. scale = lerp(0.1, 1.0, scale * scale);
  52770. vector.scaleInPlace(scale);
  52771. result.push(vector.x, vector.y, vector.z);
  52772. i++;
  52773. }
  52774. return result;
  52775. };
  52776. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  52777. var _this = this;
  52778. var numSamples = this.samples;
  52779. this._sampleSphere = this._generateHemisphere();
  52780. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  52781. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  52782. "base", "range", "projection", "near", "far", "texelSize",
  52783. "xViewport", "yViewport", "maxZ", "minZAspect"
  52784. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  52785. this._ssaoPostProcess.onApply = function (effect) {
  52786. if (_this._firstUpdate) {
  52787. effect.setArray3("sampleSphere", _this._sampleSphere);
  52788. effect.setFloat("randTextureTiles", 4.0);
  52789. }
  52790. effect.setFloat("samplesFactor", 1 / _this.samples);
  52791. effect.setFloat("totalStrength", _this.totalStrength);
  52792. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  52793. effect.setFloat("radius", _this.radius);
  52794. effect.setFloat("maxZ", _this.maxZ);
  52795. effect.setFloat("minZAspect", _this.minZAspect);
  52796. effect.setFloat("base", _this.base);
  52797. effect.setFloat("near", _this._scene.activeCamera.minZ);
  52798. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  52799. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  52800. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  52801. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  52802. effect.setTexture("textureSampler", _this._depthTexture);
  52803. effect.setTexture("normalSampler", _this._normalTexture);
  52804. effect.setTexture("randomSampler", _this._randomTexture);
  52805. };
  52806. };
  52807. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  52808. var _this = this;
  52809. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  52810. this._ssaoCombinePostProcess.onApply = function (effect) {
  52811. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  52812. };
  52813. };
  52814. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  52815. var size = 512;
  52816. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  52817. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52818. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52819. var context = this._randomTexture.getContext();
  52820. var rand = function (min, max) {
  52821. return Math.random() * (max - min) + min;
  52822. };
  52823. var randVector = BABYLON.Vector3.Zero();
  52824. for (var x = 0; x < size; x++) {
  52825. for (var y = 0; y < size; y++) {
  52826. randVector.x = rand(0.0, 1.0);
  52827. randVector.y = rand(0.0, 1.0);
  52828. randVector.z = 0.0;
  52829. randVector.normalize();
  52830. randVector.scaleInPlace(255);
  52831. randVector.x = Math.floor(randVector.x);
  52832. randVector.y = Math.floor(randVector.y);
  52833. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  52834. context.fillRect(x, y, 1, 1);
  52835. }
  52836. }
  52837. this._randomTexture.update(false);
  52838. };
  52839. __decorate([
  52840. BABYLON.serialize()
  52841. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  52842. __decorate([
  52843. BABYLON.serialize()
  52844. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  52845. __decorate([
  52846. BABYLON.serialize()
  52847. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  52848. __decorate([
  52849. BABYLON.serialize("samples")
  52850. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  52851. __decorate([
  52852. BABYLON.serialize("expensiveBlur")
  52853. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  52854. __decorate([
  52855. BABYLON.serialize()
  52856. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  52857. __decorate([
  52858. BABYLON.serialize()
  52859. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  52860. __decorate([
  52861. BABYLON.serialize()
  52862. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  52863. return SSAO2RenderingPipeline;
  52864. }(BABYLON.PostProcessRenderPipeline));
  52865. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  52866. })(BABYLON || (BABYLON = {}));
  52867. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  52868. // BABYLON.JS Chromatic Aberration GLSL Shader
  52869. // Author: Olivier Guyot
  52870. // Separates very slightly R, G and B colors on the edges of the screen
  52871. // Inspired by Francois Tarlier & Martins Upitis
  52872. var BABYLON;
  52873. (function (BABYLON) {
  52874. var LensRenderingPipeline = (function (_super) {
  52875. __extends(LensRenderingPipeline, _super);
  52876. /**
  52877. * @constructor
  52878. *
  52879. * Effect parameters are as follow:
  52880. * {
  52881. * chromatic_aberration: number; // from 0 to x (1 for realism)
  52882. * edge_blur: number; // from 0 to x (1 for realism)
  52883. * distortion: number; // from 0 to x (1 for realism)
  52884. * grain_amount: number; // from 0 to 1
  52885. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  52886. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  52887. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  52888. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  52889. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  52890. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  52891. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  52892. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  52893. * }
  52894. * Note: if an effect parameter is unset, effect is disabled
  52895. *
  52896. * @param {string} name - The rendering pipeline name
  52897. * @param {object} parameters - An object containing all parameters (see above)
  52898. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  52899. * @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)
  52900. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  52901. */
  52902. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  52903. if (ratio === void 0) { ratio = 1.0; }
  52904. var _this = _super.call(this, scene.getEngine(), name) || this;
  52905. // Lens effects can be of the following:
  52906. // - chromatic aberration (slight shift of RGB colors)
  52907. // - blur on the edge of the lens
  52908. // - lens distortion
  52909. // - depth-of-field blur & highlights enhancing
  52910. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  52911. // - grain effect (noise or custom texture)
  52912. // Two additional texture samplers are needed:
  52913. // - depth map (for depth-of-field)
  52914. // - grain texture
  52915. /**
  52916. * The chromatic aberration PostProcess id in the pipeline
  52917. * @type {string}
  52918. */
  52919. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  52920. /**
  52921. * The highlights enhancing PostProcess id in the pipeline
  52922. * @type {string}
  52923. */
  52924. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  52925. /**
  52926. * The depth-of-field PostProcess id in the pipeline
  52927. * @type {string}
  52928. */
  52929. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  52930. _this._scene = scene;
  52931. // Fetch texture samplers
  52932. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  52933. if (parameters.grain_texture) {
  52934. _this._grainTexture = parameters.grain_texture;
  52935. }
  52936. else {
  52937. _this._createGrainTexture();
  52938. }
  52939. // save parameters
  52940. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  52941. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  52942. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  52943. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  52944. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  52945. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  52946. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  52947. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  52948. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  52949. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  52950. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  52951. // Create effects
  52952. _this._createChromaticAberrationPostProcess(ratio);
  52953. _this._createHighlightsPostProcess(ratio);
  52954. _this._createDepthOfFieldPostProcess(ratio / 4);
  52955. // Set up pipeline
  52956. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  52957. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  52958. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  52959. if (_this._highlightsGain === -1) {
  52960. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  52961. }
  52962. // Finish
  52963. scene.postProcessRenderPipelineManager.addPipeline(_this);
  52964. if (cameras) {
  52965. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  52966. }
  52967. return _this;
  52968. }
  52969. // public methods (self explanatory)
  52970. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  52971. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  52972. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  52973. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  52974. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  52975. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  52976. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  52977. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  52978. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  52979. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  52980. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  52981. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  52982. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  52983. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  52984. };
  52985. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  52986. this._highlightsPostProcess.updateEffect();
  52987. };
  52988. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  52989. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  52990. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  52991. this._highlightsGain = amount;
  52992. };
  52993. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  52994. if (this._highlightsGain === -1) {
  52995. this._highlightsGain = 1.0;
  52996. }
  52997. this._highlightsThreshold = amount;
  52998. };
  52999. LensRenderingPipeline.prototype.disableHighlights = function () {
  53000. this._highlightsGain = -1;
  53001. };
  53002. /**
  53003. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  53004. */
  53005. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  53006. if (disableDepthRender === void 0) { disableDepthRender = false; }
  53007. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  53008. this._chromaticAberrationPostProcess = undefined;
  53009. this._highlightsPostProcess = undefined;
  53010. this._depthOfFieldPostProcess = undefined;
  53011. this._grainTexture.dispose();
  53012. if (disableDepthRender)
  53013. this._scene.disableDepthRenderer();
  53014. };
  53015. // colors shifting and distortion
  53016. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  53017. var _this = this;
  53018. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  53019. [], // samplers
  53020. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  53021. this._chromaticAberrationPostProcess.onApply = function (effect) {
  53022. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  53023. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  53024. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  53025. };
  53026. };
  53027. // highlights enhancing
  53028. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  53029. var _this = this;
  53030. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  53031. [], // samplers
  53032. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  53033. this._highlightsPostProcess.onApply = function (effect) {
  53034. effect.setFloat('gain', _this._highlightsGain);
  53035. effect.setFloat('threshold', _this._highlightsThreshold);
  53036. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  53037. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  53038. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  53039. };
  53040. };
  53041. // colors shifting and distortion
  53042. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  53043. var _this = this;
  53044. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  53045. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  53046. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  53047. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  53048. this._depthOfFieldPostProcess.onApply = function (effect) {
  53049. effect.setTexture("depthSampler", _this._depthTexture);
  53050. effect.setTexture("grainSampler", _this._grainTexture);
  53051. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  53052. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  53053. effect.setFloat('grain_amount', _this._grainAmount);
  53054. effect.setBool('blur_noise', _this._blurNoise);
  53055. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  53056. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  53057. effect.setFloat('distortion', _this._distortion);
  53058. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  53059. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  53060. effect.setFloat('aperture', _this._dofAperture);
  53061. effect.setFloat('darken', _this._dofDarken);
  53062. effect.setFloat('edge_blur', _this._edgeBlur);
  53063. effect.setBool('highlights', (_this._highlightsGain !== -1));
  53064. effect.setFloat('near', _this._scene.activeCamera.minZ);
  53065. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  53066. };
  53067. };
  53068. // creates a black and white random noise texture, 512x512
  53069. LensRenderingPipeline.prototype._createGrainTexture = function () {
  53070. var size = 512;
  53071. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  53072. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  53073. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  53074. var context = this._grainTexture.getContext();
  53075. var rand = function (min, max) {
  53076. return Math.random() * (max - min) + min;
  53077. };
  53078. var value;
  53079. for (var x = 0; x < size; x++) {
  53080. for (var y = 0; y < size; y++) {
  53081. value = Math.floor(rand(0.42, 0.58) * 255);
  53082. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  53083. context.fillRect(x, y, 1, 1);
  53084. }
  53085. }
  53086. this._grainTexture.update(false);
  53087. };
  53088. return LensRenderingPipeline;
  53089. }(BABYLON.PostProcessRenderPipeline));
  53090. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  53091. })(BABYLON || (BABYLON = {}));
  53092. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  53093. var BABYLON;
  53094. (function (BABYLON) {
  53095. var StandardRenderingPipeline = (function (_super) {
  53096. __extends(StandardRenderingPipeline, _super);
  53097. /**
  53098. * @constructor
  53099. * @param {string} name - The rendering pipeline name
  53100. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  53101. * @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)
  53102. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  53103. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  53104. */
  53105. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  53106. if (originalPostProcess === void 0) { originalPostProcess = null; }
  53107. var _this = _super.call(this, scene.getEngine(), name) || this;
  53108. _this.downSampleX4PostProcess = null;
  53109. _this.brightPassPostProcess = null;
  53110. _this.blurHPostProcesses = [];
  53111. _this.blurVPostProcesses = [];
  53112. _this.textureAdderPostProcess = null;
  53113. _this.volumetricLightPostProcess = null;
  53114. _this.volumetricLightSmoothXPostProcess = null;
  53115. _this.volumetricLightSmoothYPostProcess = null;
  53116. _this.volumetricLightMergePostProces = null;
  53117. _this.volumetricLightFinalPostProcess = null;
  53118. _this.luminancePostProcess = null;
  53119. _this.luminanceDownSamplePostProcesses = [];
  53120. _this.hdrPostProcess = null;
  53121. _this.textureAdderFinalPostProcess = null;
  53122. _this.lensFlareFinalPostProcess = null;
  53123. _this.hdrFinalPostProcess = null;
  53124. _this.lensFlarePostProcess = null;
  53125. _this.lensFlareComposePostProcess = null;
  53126. _this.motionBlurPostProcess = null;
  53127. _this.depthOfFieldPostProcess = null;
  53128. // Values
  53129. _this.brightThreshold = 1.0;
  53130. _this.blurWidth = 512.0;
  53131. _this.horizontalBlur = false;
  53132. _this.exposure = 1.0;
  53133. _this.lensTexture = null;
  53134. _this.volumetricLightCoefficient = 0.2;
  53135. _this.volumetricLightPower = 4.0;
  53136. _this.volumetricLightBlurScale = 64.0;
  53137. _this.sourceLight = null;
  53138. _this.hdrMinimumLuminance = 1.0;
  53139. _this.hdrDecreaseRate = 0.5;
  53140. _this.hdrIncreaseRate = 0.5;
  53141. _this.lensColorTexture = null;
  53142. _this.lensFlareStrength = 20.0;
  53143. _this.lensFlareGhostDispersal = 1.4;
  53144. _this.lensFlareHaloWidth = 0.7;
  53145. _this.lensFlareDistortionStrength = 16.0;
  53146. _this.lensStarTexture = null;
  53147. _this.lensFlareDirtTexture = null;
  53148. _this.depthOfFieldDistance = 10.0;
  53149. _this.depthOfFieldBlurWidth = 64.0;
  53150. _this.motionStrength = 1.0;
  53151. // IAnimatable
  53152. _this.animations = [];
  53153. _this._currentDepthOfFieldSource = null;
  53154. _this._hdrCurrentLuminance = 1.0;
  53155. // Getters and setters
  53156. _this._bloomEnabled = true;
  53157. _this._depthOfFieldEnabled = false;
  53158. _this._vlsEnabled = false;
  53159. _this._lensFlareEnabled = false;
  53160. _this._hdrEnabled = false;
  53161. _this._motionBlurEnabled = false;
  53162. _this._motionBlurSamples = 64.0;
  53163. _this._volumetricLightStepsCount = 50.0;
  53164. _this._cameras = cameras || [];
  53165. // Initialize
  53166. _this._scene = scene;
  53167. _this._basePostProcess = originalPostProcess;
  53168. _this._ratio = ratio;
  53169. // Misc
  53170. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  53171. // Finish
  53172. scene.postProcessRenderPipelineManager.addPipeline(_this);
  53173. _this._buildPipeline();
  53174. return _this;
  53175. }
  53176. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  53177. get: function () {
  53178. return this._bloomEnabled;
  53179. },
  53180. set: function (enabled) {
  53181. if (this._bloomEnabled === enabled) {
  53182. return;
  53183. }
  53184. this._bloomEnabled = enabled;
  53185. this._buildPipeline();
  53186. },
  53187. enumerable: true,
  53188. configurable: true
  53189. });
  53190. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  53191. get: function () {
  53192. return this._depthOfFieldEnabled;
  53193. },
  53194. set: function (enabled) {
  53195. if (this._depthOfFieldEnabled === enabled) {
  53196. return;
  53197. }
  53198. this._depthOfFieldEnabled = enabled;
  53199. this._buildPipeline();
  53200. },
  53201. enumerable: true,
  53202. configurable: true
  53203. });
  53204. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  53205. get: function () {
  53206. return this._lensFlareEnabled;
  53207. },
  53208. set: function (enabled) {
  53209. if (this._lensFlareEnabled === enabled) {
  53210. return;
  53211. }
  53212. this._lensFlareEnabled = enabled;
  53213. this._buildPipeline();
  53214. },
  53215. enumerable: true,
  53216. configurable: true
  53217. });
  53218. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  53219. get: function () {
  53220. return this._hdrEnabled;
  53221. },
  53222. set: function (enabled) {
  53223. if (this._hdrEnabled === enabled) {
  53224. return;
  53225. }
  53226. this._hdrEnabled = enabled;
  53227. this._buildPipeline();
  53228. },
  53229. enumerable: true,
  53230. configurable: true
  53231. });
  53232. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  53233. get: function () {
  53234. return this._vlsEnabled;
  53235. },
  53236. set: function (enabled) {
  53237. if (this._vlsEnabled === enabled) {
  53238. return;
  53239. }
  53240. if (enabled) {
  53241. var geometry = this._scene.enableGeometryBufferRenderer();
  53242. if (!geometry) {
  53243. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  53244. return;
  53245. }
  53246. }
  53247. this._vlsEnabled = enabled;
  53248. this._buildPipeline();
  53249. },
  53250. enumerable: true,
  53251. configurable: true
  53252. });
  53253. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  53254. get: function () {
  53255. return this._motionBlurEnabled;
  53256. },
  53257. set: function (enabled) {
  53258. if (this._motionBlurEnabled === enabled) {
  53259. return;
  53260. }
  53261. this._motionBlurEnabled = enabled;
  53262. this._buildPipeline();
  53263. },
  53264. enumerable: true,
  53265. configurable: true
  53266. });
  53267. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  53268. get: function () {
  53269. return this._volumetricLightStepsCount;
  53270. },
  53271. set: function (count) {
  53272. if (this.volumetricLightPostProcess) {
  53273. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  53274. }
  53275. this._volumetricLightStepsCount = count;
  53276. },
  53277. enumerable: true,
  53278. configurable: true
  53279. });
  53280. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  53281. get: function () {
  53282. return this._motionBlurSamples;
  53283. },
  53284. set: function (samples) {
  53285. if (this.motionBlurPostProcess) {
  53286. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  53287. }
  53288. this._motionBlurSamples = samples;
  53289. },
  53290. enumerable: true,
  53291. configurable: true
  53292. });
  53293. StandardRenderingPipeline.prototype._buildPipeline = function () {
  53294. var _this = this;
  53295. var ratio = this._ratio;
  53296. var scene = this._scene;
  53297. this._disposePostProcesses();
  53298. this._reset();
  53299. // Create pass post-process
  53300. if (!this._basePostProcess) {
  53301. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  53302. this.originalPostProcess.onApply = function (effect) {
  53303. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  53304. };
  53305. }
  53306. else {
  53307. this.originalPostProcess = this._basePostProcess;
  53308. }
  53309. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  53310. this._currentDepthOfFieldSource = this.originalPostProcess;
  53311. if (this._vlsEnabled) {
  53312. // Create volumetric light
  53313. this._createVolumetricLightPostProcess(scene, ratio);
  53314. // Create volumetric light final post-process
  53315. 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);
  53316. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  53317. }
  53318. if (this._bloomEnabled) {
  53319. // Create down sample X4 post-process
  53320. this._createDownSampleX4PostProcess(scene, ratio / 2);
  53321. // Create bright pass post-process
  53322. this._createBrightPassPostProcess(scene, ratio / 2);
  53323. // Create gaussian blur post-processes (down sampling blurs)
  53324. this._createBlurPostProcesses(scene, ratio / 4, 1);
  53325. // Create texture adder post-process
  53326. this._createTextureAdderPostProcess(scene, ratio);
  53327. // Create depth-of-field source post-process
  53328. 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);
  53329. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  53330. }
  53331. if (this._lensFlareEnabled) {
  53332. // Create lens flare post-process
  53333. this._createLensFlarePostProcess(scene, ratio);
  53334. // Create depth-of-field source post-process post lens-flare and disable it now
  53335. 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);
  53336. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  53337. }
  53338. if (this._hdrEnabled) {
  53339. // Create luminance
  53340. this._createLuminancePostProcesses(scene, this._floatTextureType);
  53341. // Create HDR
  53342. this._createHdrPostProcess(scene, ratio);
  53343. // Create depth-of-field source post-process post hdr and disable it now
  53344. 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);
  53345. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  53346. }
  53347. if (this._depthOfFieldEnabled) {
  53348. // Create gaussian blur used by depth-of-field
  53349. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  53350. // Create depth-of-field post-process
  53351. this._createDepthOfFieldPostProcess(scene, ratio);
  53352. }
  53353. if (this._motionBlurEnabled) {
  53354. // Create motion blur post-process
  53355. this._createMotionBlurPostProcess(scene, ratio);
  53356. }
  53357. if (this._cameras !== null) {
  53358. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  53359. }
  53360. };
  53361. // Down Sample X4 Post-Processs
  53362. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  53363. var _this = this;
  53364. var downSampleX4Offsets = new Array(32);
  53365. 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);
  53366. this.downSampleX4PostProcess.onApply = function (effect) {
  53367. var id = 0;
  53368. for (var i = -2; i < 2; i++) {
  53369. for (var j = -2; j < 2; j++) {
  53370. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  53371. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  53372. id += 2;
  53373. }
  53374. }
  53375. effect.setArray2("dsOffsets", downSampleX4Offsets);
  53376. };
  53377. // Add to pipeline
  53378. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  53379. };
  53380. // Brightpass Post-Process
  53381. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  53382. var _this = this;
  53383. var brightOffsets = new Array(8);
  53384. 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);
  53385. this.brightPassPostProcess.onApply = function (effect) {
  53386. var sU = (1.0 / _this.brightPassPostProcess.width);
  53387. var sV = (1.0 / _this.brightPassPostProcess.height);
  53388. brightOffsets[0] = -0.5 * sU;
  53389. brightOffsets[1] = 0.5 * sV;
  53390. brightOffsets[2] = 0.5 * sU;
  53391. brightOffsets[3] = 0.5 * sV;
  53392. brightOffsets[4] = -0.5 * sU;
  53393. brightOffsets[5] = -0.5 * sV;
  53394. brightOffsets[6] = 0.5 * sU;
  53395. brightOffsets[7] = -0.5 * sV;
  53396. effect.setArray2("dsOffsets", brightOffsets);
  53397. effect.setFloat("brightThreshold", _this.brightThreshold);
  53398. };
  53399. // Add to pipeline
  53400. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  53401. };
  53402. // Create blur H&V post-processes
  53403. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  53404. var _this = this;
  53405. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  53406. var engine = scene.getEngine();
  53407. 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);
  53408. 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);
  53409. blurX.onActivateObservable.add(function () {
  53410. var dw = blurX.width / engine.getRenderingCanvas().width;
  53411. blurX.kernel = _this[blurWidthKey] * dw;
  53412. });
  53413. blurY.onActivateObservable.add(function () {
  53414. var dw = blurY.height / engine.getRenderingCanvas().height;
  53415. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  53416. });
  53417. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  53418. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  53419. this.blurHPostProcesses.push(blurX);
  53420. this.blurVPostProcesses.push(blurY);
  53421. };
  53422. // Create texture adder post-process
  53423. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  53424. var _this = this;
  53425. 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);
  53426. this.textureAdderPostProcess.onApply = function (effect) {
  53427. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  53428. effect.setTexture("lensSampler", _this.lensTexture);
  53429. effect.setFloat("exposure", _this.exposure);
  53430. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  53431. };
  53432. // Add to pipeline
  53433. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  53434. };
  53435. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  53436. var _this = this;
  53437. var geometryRenderer = scene.enableGeometryBufferRenderer();
  53438. geometryRenderer.enablePosition = true;
  53439. var geometry = geometryRenderer.getGBuffer();
  53440. // Base post-process
  53441. 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));
  53442. var depthValues = BABYLON.Vector2.Zero();
  53443. this.volumetricLightPostProcess.onApply = function (effect) {
  53444. if (_this.sourceLight && _this.sourceLight.getShadowGenerator()) {
  53445. var generator = _this.sourceLight.getShadowGenerator();
  53446. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  53447. effect.setTexture("positionSampler", geometry.textures[2]);
  53448. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  53449. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  53450. effect.setVector3("cameraPosition", scene.activeCamera.globalPosition);
  53451. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  53452. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  53453. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  53454. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  53455. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  53456. effect.setVector2("depthValues", depthValues);
  53457. }
  53458. };
  53459. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  53460. // Smooth
  53461. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  53462. // Merge
  53463. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  53464. this.volumetricLightMergePostProces.onApply = function (effect) {
  53465. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  53466. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  53467. };
  53468. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  53469. };
  53470. // Create luminance
  53471. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  53472. var _this = this;
  53473. // Create luminance
  53474. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  53475. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  53476. var offsets = [];
  53477. this.luminancePostProcess.onApply = function (effect) {
  53478. var sU = (1.0 / _this.luminancePostProcess.width);
  53479. var sV = (1.0 / _this.luminancePostProcess.height);
  53480. offsets[0] = -0.5 * sU;
  53481. offsets[1] = 0.5 * sV;
  53482. offsets[2] = 0.5 * sU;
  53483. offsets[3] = 0.5 * sV;
  53484. offsets[4] = -0.5 * sU;
  53485. offsets[5] = -0.5 * sV;
  53486. offsets[6] = 0.5 * sU;
  53487. offsets[7] = -0.5 * sV;
  53488. effect.setArray2("lumOffsets", offsets);
  53489. };
  53490. // Add to pipeline
  53491. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  53492. // Create down sample luminance
  53493. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  53494. var size = Math.pow(3, i);
  53495. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  53496. if (i === 0) {
  53497. defines += "#define FINAL_DOWN_SAMPLER";
  53498. }
  53499. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  53500. this.luminanceDownSamplePostProcesses.push(postProcess);
  53501. }
  53502. // Create callbacks and add effects
  53503. var lastLuminance = this.luminancePostProcess;
  53504. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  53505. var downSampleOffsets = new Array(18);
  53506. pp.onApply = function (effect) {
  53507. var id = 0;
  53508. for (var x = -1; x < 2; x++) {
  53509. for (var y = -1; y < 2; y++) {
  53510. downSampleOffsets[id] = x / lastLuminance.width;
  53511. downSampleOffsets[id + 1] = y / lastLuminance.height;
  53512. id += 2;
  53513. }
  53514. }
  53515. effect.setArray2("dsOffsets", downSampleOffsets);
  53516. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  53517. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  53518. lastLuminance = _this.luminancePostProcess;
  53519. }
  53520. else {
  53521. lastLuminance = pp;
  53522. }
  53523. };
  53524. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  53525. pp.onAfterRender = function (effect) {
  53526. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  53527. 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);
  53528. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  53529. };
  53530. }
  53531. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  53532. });
  53533. };
  53534. // Create HDR post-process
  53535. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  53536. var _this = this;
  53537. 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);
  53538. var outputLiminance = 1;
  53539. var time = 0;
  53540. var lastTime = 0;
  53541. this.hdrPostProcess.onApply = function (effect) {
  53542. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  53543. time += scene.getEngine().getDeltaTime();
  53544. if (outputLiminance < 0) {
  53545. outputLiminance = _this._hdrCurrentLuminance;
  53546. }
  53547. else {
  53548. var dt = (lastTime - time) / 1000.0;
  53549. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  53550. outputLiminance += _this.hdrDecreaseRate * dt;
  53551. }
  53552. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  53553. outputLiminance -= _this.hdrIncreaseRate * dt;
  53554. }
  53555. else {
  53556. outputLiminance = _this._hdrCurrentLuminance;
  53557. }
  53558. }
  53559. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  53560. effect.setFloat("averageLuminance", outputLiminance);
  53561. lastTime = time;
  53562. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  53563. };
  53564. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  53565. };
  53566. // Create lens flare post-process
  53567. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  53568. var _this = this;
  53569. 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);
  53570. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  53571. this._createBlurPostProcesses(scene, ratio / 4, 2);
  53572. 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);
  53573. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  53574. var resolution = new BABYLON.Vector2(0, 0);
  53575. // Lens flare
  53576. this.lensFlarePostProcess.onApply = function (effect) {
  53577. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  53578. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  53579. effect.setFloat("strength", _this.lensFlareStrength);
  53580. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  53581. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  53582. // Shift
  53583. resolution.x = _this.lensFlarePostProcess.width;
  53584. resolution.y = _this.lensFlarePostProcess.height;
  53585. effect.setVector2("resolution", resolution);
  53586. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  53587. };
  53588. // Compose
  53589. 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);
  53590. 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);
  53591. this.lensFlareComposePostProcess.onApply = function (effect) {
  53592. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  53593. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  53594. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  53595. // Lens start rotation matrix
  53596. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  53597. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  53598. 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));
  53599. camRot *= 4.0;
  53600. 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);
  53601. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  53602. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  53603. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  53604. };
  53605. };
  53606. // Create depth-of-field post-process
  53607. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  53608. var _this = this;
  53609. 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);
  53610. this.depthOfFieldPostProcess.onApply = function (effect) {
  53611. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  53612. effect.setTexture("depthSampler", _this._getDepthTexture());
  53613. effect.setFloat("distance", _this.depthOfFieldDistance);
  53614. };
  53615. // Add to pipeline
  53616. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  53617. };
  53618. // Create motion blur post-process
  53619. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  53620. var _this = this;
  53621. 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);
  53622. var motionScale = 0;
  53623. var prevViewProjection = BABYLON.Matrix.Identity();
  53624. var invViewProjection = BABYLON.Matrix.Identity();
  53625. var viewProjection = BABYLON.Matrix.Identity();
  53626. var screenSize = BABYLON.Vector2.Zero();
  53627. this.motionBlurPostProcess.onApply = function (effect) {
  53628. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  53629. viewProjection.invertToRef(invViewProjection);
  53630. effect.setMatrix("inverseViewProjection", invViewProjection);
  53631. effect.setMatrix("prevViewProjection", prevViewProjection);
  53632. prevViewProjection = viewProjection;
  53633. screenSize.x = _this.motionBlurPostProcess.width;
  53634. screenSize.y = _this.motionBlurPostProcess.height;
  53635. effect.setVector2("screenSize", screenSize);
  53636. motionScale = scene.getEngine().getFps() / 60.0;
  53637. effect.setFloat("motionScale", motionScale);
  53638. effect.setFloat("motionStrength", _this.motionStrength);
  53639. effect.setTexture("depthSampler", _this._getDepthTexture());
  53640. };
  53641. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  53642. };
  53643. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  53644. var geometry = this._scene.enableGeometryBufferRenderer();
  53645. if (geometry) {
  53646. return geometry.getGBuffer().textures[0];
  53647. }
  53648. return this._scene.enableDepthRenderer().getDepthMap();
  53649. };
  53650. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  53651. for (var i = 0; i < this._cameras.length; i++) {
  53652. var camera = this._cameras[i];
  53653. if (this.originalPostProcess) {
  53654. this.originalPostProcess.dispose(camera);
  53655. }
  53656. if (this.downSampleX4PostProcess) {
  53657. this.downSampleX4PostProcess.dispose(camera);
  53658. }
  53659. if (this.brightPassPostProcess) {
  53660. this.brightPassPostProcess.dispose(camera);
  53661. }
  53662. if (this.textureAdderPostProcess) {
  53663. this.textureAdderPostProcess.dispose(camera);
  53664. }
  53665. if (this.textureAdderFinalPostProcess) {
  53666. this.textureAdderFinalPostProcess.dispose(camera);
  53667. }
  53668. if (this.volumetricLightPostProcess) {
  53669. this.volumetricLightPostProcess.dispose(camera);
  53670. }
  53671. if (this.volumetricLightSmoothXPostProcess) {
  53672. this.volumetricLightSmoothXPostProcess.dispose(camera);
  53673. }
  53674. if (this.volumetricLightSmoothYPostProcess) {
  53675. this.volumetricLightSmoothYPostProcess.dispose(camera);
  53676. }
  53677. if (this.volumetricLightMergePostProces) {
  53678. this.volumetricLightMergePostProces.dispose(camera);
  53679. }
  53680. if (this.volumetricLightFinalPostProcess) {
  53681. this.volumetricLightFinalPostProcess.dispose(camera);
  53682. }
  53683. if (this.lensFlarePostProcess) {
  53684. this.lensFlarePostProcess.dispose(camera);
  53685. }
  53686. if (this.lensFlareComposePostProcess) {
  53687. this.lensFlareComposePostProcess.dispose(camera);
  53688. }
  53689. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  53690. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  53691. }
  53692. if (this.luminancePostProcess) {
  53693. this.luminancePostProcess.dispose(camera);
  53694. }
  53695. if (this.hdrPostProcess) {
  53696. this.hdrPostProcess.dispose(camera);
  53697. }
  53698. if (this.hdrFinalPostProcess) {
  53699. this.hdrFinalPostProcess.dispose(camera);
  53700. }
  53701. if (this.depthOfFieldPostProcess) {
  53702. this.depthOfFieldPostProcess.dispose(camera);
  53703. }
  53704. if (this.motionBlurPostProcess) {
  53705. this.motionBlurPostProcess.dispose(camera);
  53706. }
  53707. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  53708. this.blurHPostProcesses[j].dispose(camera);
  53709. }
  53710. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  53711. this.blurVPostProcesses[j].dispose(camera);
  53712. }
  53713. }
  53714. this.originalPostProcess = null;
  53715. this.downSampleX4PostProcess = null;
  53716. this.brightPassPostProcess = null;
  53717. this.textureAdderPostProcess = null;
  53718. this.textureAdderFinalPostProcess = null;
  53719. this.volumetricLightPostProcess = null;
  53720. this.volumetricLightSmoothXPostProcess = null;
  53721. this.volumetricLightSmoothYPostProcess = null;
  53722. this.volumetricLightMergePostProces = null;
  53723. this.volumetricLightFinalPostProcess = null;
  53724. this.lensFlarePostProcess = null;
  53725. this.lensFlareComposePostProcess = null;
  53726. this.luminancePostProcess = null;
  53727. this.hdrPostProcess = null;
  53728. this.hdrFinalPostProcess = null;
  53729. this.depthOfFieldPostProcess = null;
  53730. this.motionBlurPostProcess = null;
  53731. this.luminanceDownSamplePostProcesses = [];
  53732. this.blurHPostProcesses = [];
  53733. this.blurVPostProcesses = [];
  53734. };
  53735. // Dispose
  53736. StandardRenderingPipeline.prototype.dispose = function () {
  53737. this._disposePostProcesses();
  53738. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  53739. _super.prototype.dispose.call(this);
  53740. };
  53741. // Serialize rendering pipeline
  53742. StandardRenderingPipeline.prototype.serialize = function () {
  53743. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  53744. serializationObject.customType = "StandardRenderingPipeline";
  53745. return serializationObject;
  53746. };
  53747. /**
  53748. * Static members
  53749. */
  53750. // Parse serialized pipeline
  53751. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  53752. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  53753. };
  53754. // Luminance steps
  53755. StandardRenderingPipeline.LuminanceSteps = 6;
  53756. __decorate([
  53757. BABYLON.serialize()
  53758. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  53759. __decorate([
  53760. BABYLON.serialize()
  53761. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  53762. __decorate([
  53763. BABYLON.serialize()
  53764. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  53765. __decorate([
  53766. BABYLON.serialize()
  53767. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  53768. __decorate([
  53769. BABYLON.serializeAsTexture("lensTexture")
  53770. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  53771. __decorate([
  53772. BABYLON.serialize()
  53773. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  53774. __decorate([
  53775. BABYLON.serialize()
  53776. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  53777. __decorate([
  53778. BABYLON.serialize()
  53779. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  53780. __decorate([
  53781. BABYLON.serialize()
  53782. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  53783. __decorate([
  53784. BABYLON.serialize()
  53785. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  53786. __decorate([
  53787. BABYLON.serialize()
  53788. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  53789. __decorate([
  53790. BABYLON.serializeAsTexture("lensColorTexture")
  53791. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  53792. __decorate([
  53793. BABYLON.serialize()
  53794. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  53795. __decorate([
  53796. BABYLON.serialize()
  53797. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  53798. __decorate([
  53799. BABYLON.serialize()
  53800. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  53801. __decorate([
  53802. BABYLON.serialize()
  53803. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  53804. __decorate([
  53805. BABYLON.serializeAsTexture("lensStarTexture")
  53806. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  53807. __decorate([
  53808. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  53809. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  53810. __decorate([
  53811. BABYLON.serialize()
  53812. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  53813. __decorate([
  53814. BABYLON.serialize()
  53815. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  53816. __decorate([
  53817. BABYLON.serialize()
  53818. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  53819. __decorate([
  53820. BABYLON.serialize()
  53821. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  53822. __decorate([
  53823. BABYLON.serialize()
  53824. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  53825. __decorate([
  53826. BABYLON.serialize()
  53827. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  53828. __decorate([
  53829. BABYLON.serialize()
  53830. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  53831. __decorate([
  53832. BABYLON.serialize()
  53833. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  53834. __decorate([
  53835. BABYLON.serialize()
  53836. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  53837. __decorate([
  53838. BABYLON.serialize()
  53839. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  53840. __decorate([
  53841. BABYLON.serialize()
  53842. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  53843. return StandardRenderingPipeline;
  53844. }(BABYLON.PostProcessRenderPipeline));
  53845. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  53846. })(BABYLON || (BABYLON = {}));
  53847. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  53848. var BABYLON;
  53849. (function (BABYLON) {
  53850. var FxaaPostProcess = (function (_super) {
  53851. __extends(FxaaPostProcess, _super);
  53852. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  53853. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53854. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  53855. _this.onApplyObservable.add(function (effect) {
  53856. var texelSize = _this.texelSize;
  53857. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  53858. });
  53859. return _this;
  53860. }
  53861. return FxaaPostProcess;
  53862. }(BABYLON.PostProcess));
  53863. BABYLON.FxaaPostProcess = FxaaPostProcess;
  53864. })(BABYLON || (BABYLON = {}));
  53865. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  53866. var BABYLON;
  53867. (function (BABYLON) {
  53868. var DefaultRenderingPipeline = (function (_super) {
  53869. __extends(DefaultRenderingPipeline, _super);
  53870. /**
  53871. * @constructor
  53872. * @param {string} name - The rendering pipeline name
  53873. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  53874. * @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)
  53875. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  53876. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  53877. */
  53878. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  53879. if (automaticBuild === void 0) { automaticBuild = true; }
  53880. var _this = _super.call(this, scene.getEngine(), name) || this;
  53881. _this.PassPostProcessId = "PassPostProcessEffect";
  53882. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  53883. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  53884. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  53885. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  53886. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  53887. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  53888. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  53889. // IAnimatable
  53890. _this.animations = [];
  53891. // Values
  53892. _this._bloomEnabled = false;
  53893. _this._fxaaEnabled = false;
  53894. _this._imageProcessingEnabled = true;
  53895. _this._bloomScale = 0.6;
  53896. _this._buildAllowed = true;
  53897. /**
  53898. * Specifies the size of the bloom blur kernel, relative to the final output size
  53899. */
  53900. _this.bloomKernel = 64;
  53901. /**
  53902. * Specifies the weight of the bloom in the final rendering
  53903. */
  53904. _this._bloomWeight = 0.15;
  53905. _this._cameras = cameras || [];
  53906. _this._buildAllowed = automaticBuild;
  53907. // Initialize
  53908. _this._scene = scene;
  53909. var caps = _this._scene.getEngine().getCaps();
  53910. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  53911. // Misc
  53912. if (_this._hdr) {
  53913. if (caps.textureHalfFloatRender) {
  53914. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  53915. }
  53916. else if (caps.textureFloatRender) {
  53917. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  53918. }
  53919. }
  53920. else {
  53921. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  53922. }
  53923. // Attach
  53924. scene.postProcessRenderPipelineManager.addPipeline(_this);
  53925. _this._buildPipeline();
  53926. return _this;
  53927. }
  53928. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  53929. get: function () {
  53930. return this._bloomWeight;
  53931. },
  53932. set: function (value) {
  53933. if (this._bloomWeight === value) {
  53934. return;
  53935. }
  53936. this._bloomWeight = value;
  53937. if (this._hdr && this.copyBack) {
  53938. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  53939. }
  53940. },
  53941. enumerable: true,
  53942. configurable: true
  53943. });
  53944. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  53945. get: function () {
  53946. return this._bloomScale;
  53947. },
  53948. set: function (value) {
  53949. if (this._bloomScale === value) {
  53950. return;
  53951. }
  53952. this._bloomScale = value;
  53953. this._buildPipeline();
  53954. },
  53955. enumerable: true,
  53956. configurable: true
  53957. });
  53958. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  53959. get: function () {
  53960. return this._bloomEnabled;
  53961. },
  53962. set: function (enabled) {
  53963. if (this._bloomEnabled === enabled) {
  53964. return;
  53965. }
  53966. this._bloomEnabled = enabled;
  53967. this._buildPipeline();
  53968. },
  53969. enumerable: true,
  53970. configurable: true
  53971. });
  53972. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  53973. get: function () {
  53974. return this._fxaaEnabled;
  53975. },
  53976. set: function (enabled) {
  53977. if (this._fxaaEnabled === enabled) {
  53978. return;
  53979. }
  53980. this._fxaaEnabled = enabled;
  53981. this._buildPipeline();
  53982. },
  53983. enumerable: true,
  53984. configurable: true
  53985. });
  53986. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  53987. get: function () {
  53988. return this._imageProcessingEnabled;
  53989. },
  53990. set: function (enabled) {
  53991. if (this._imageProcessingEnabled === enabled) {
  53992. return;
  53993. }
  53994. this._imageProcessingEnabled = enabled;
  53995. this._buildPipeline();
  53996. },
  53997. enumerable: true,
  53998. configurable: true
  53999. });
  54000. /**
  54001. * Force the compilation of the entire pipeline.
  54002. */
  54003. DefaultRenderingPipeline.prototype.prepare = function () {
  54004. var previousState = this._buildAllowed;
  54005. this._buildAllowed = true;
  54006. this._buildPipeline();
  54007. this._buildAllowed = previousState;
  54008. };
  54009. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  54010. var _this = this;
  54011. if (!this._buildAllowed) {
  54012. return;
  54013. }
  54014. var engine = this._scene.getEngine();
  54015. this._disposePostProcesses();
  54016. this._reset();
  54017. if (this.bloomEnabled) {
  54018. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  54019. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  54020. if (!this._hdr) {
  54021. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  54022. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  54023. this.highlights.autoClear = false;
  54024. this.highlights.alwaysForcePOT = true;
  54025. }
  54026. 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);
  54027. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  54028. this.blurX.alwaysForcePOT = true;
  54029. this.blurX.autoClear = false;
  54030. this.blurX.onActivateObservable.add(function () {
  54031. var dw = _this.blurX.width / engine.getRenderingCanvas().width;
  54032. _this.blurX.kernel = _this.bloomKernel * dw;
  54033. });
  54034. 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);
  54035. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  54036. this.blurY.alwaysForcePOT = true;
  54037. this.blurY.autoClear = false;
  54038. this.blurY.onActivateObservable.add(function () {
  54039. var dh = _this.blurY.height / engine.getRenderingCanvas().height;
  54040. _this.blurY.kernel = _this.bloomKernel * dh;
  54041. });
  54042. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  54043. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  54044. this.copyBack.alwaysForcePOT = true;
  54045. if (this._hdr) {
  54046. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  54047. var w = this.bloomWeight;
  54048. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  54049. }
  54050. else {
  54051. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  54052. }
  54053. this.copyBack.autoClear = false;
  54054. }
  54055. if (this._imageProcessingEnabled) {
  54056. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  54057. if (this._hdr) {
  54058. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  54059. }
  54060. }
  54061. if (this.fxaaEnabled) {
  54062. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  54063. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  54064. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  54065. }
  54066. else {
  54067. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  54068. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  54069. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  54070. }
  54071. if (this.bloomEnabled) {
  54072. if (this._hdr) {
  54073. this.copyBack.shareOutputWith(this.blurX);
  54074. if (this.imageProcessing) {
  54075. this.imageProcessing.shareOutputWith(this.pass);
  54076. this.imageProcessing.autoClear = false;
  54077. }
  54078. else if (this.fxaa) {
  54079. this.fxaa.shareOutputWith(this.pass);
  54080. }
  54081. else {
  54082. this.finalMerge.shareOutputWith(this.pass);
  54083. }
  54084. }
  54085. else {
  54086. if (this.fxaa) {
  54087. this.fxaa.shareOutputWith(this.pass);
  54088. }
  54089. else {
  54090. this.finalMerge.shareOutputWith(this.pass);
  54091. }
  54092. }
  54093. }
  54094. if (this._cameras !== null) {
  54095. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  54096. }
  54097. };
  54098. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  54099. for (var i = 0; i < this._cameras.length; i++) {
  54100. var camera = this._cameras[i];
  54101. if (this.pass) {
  54102. this.pass.dispose(camera);
  54103. }
  54104. if (this.highlights) {
  54105. this.highlights.dispose(camera);
  54106. }
  54107. if (this.blurX) {
  54108. this.blurX.dispose(camera);
  54109. }
  54110. if (this.blurY) {
  54111. this.blurY.dispose(camera);
  54112. }
  54113. if (this.copyBack) {
  54114. this.copyBack.dispose(camera);
  54115. }
  54116. if (this.imageProcessing) {
  54117. this.imageProcessing.dispose(camera);
  54118. }
  54119. if (this.fxaa) {
  54120. this.fxaa.dispose(camera);
  54121. }
  54122. if (this.finalMerge) {
  54123. this.finalMerge.dispose(camera);
  54124. }
  54125. }
  54126. this.pass = null;
  54127. this.highlights = null;
  54128. this.blurX = null;
  54129. this.blurY = null;
  54130. this.copyBack = null;
  54131. this.imageProcessing = null;
  54132. this.fxaa = null;
  54133. this.finalMerge = null;
  54134. };
  54135. // Dispose
  54136. DefaultRenderingPipeline.prototype.dispose = function () {
  54137. this._disposePostProcesses();
  54138. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  54139. _super.prototype.dispose.call(this);
  54140. };
  54141. // Serialize rendering pipeline
  54142. DefaultRenderingPipeline.prototype.serialize = function () {
  54143. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  54144. serializationObject.customType = "DefaultRenderingPipeline";
  54145. return serializationObject;
  54146. };
  54147. // Parse serialized pipeline
  54148. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  54149. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  54150. };
  54151. __decorate([
  54152. BABYLON.serialize()
  54153. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  54154. __decorate([
  54155. BABYLON.serialize()
  54156. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  54157. __decorate([
  54158. BABYLON.serialize()
  54159. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  54160. __decorate([
  54161. BABYLON.serialize()
  54162. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  54163. __decorate([
  54164. BABYLON.serialize()
  54165. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  54166. __decorate([
  54167. BABYLON.serialize()
  54168. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  54169. __decorate([
  54170. BABYLON.serialize()
  54171. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  54172. __decorate([
  54173. BABYLON.serialize()
  54174. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  54175. return DefaultRenderingPipeline;
  54176. }(BABYLON.PostProcessRenderPipeline));
  54177. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  54178. })(BABYLON || (BABYLON = {}));
  54179. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  54180. var BABYLON;
  54181. (function (BABYLON) {
  54182. var GeometryBufferRenderer = (function () {
  54183. function GeometryBufferRenderer(scene, ratio) {
  54184. if (ratio === void 0) { ratio = 1; }
  54185. this._viewMatrix = BABYLON.Matrix.Zero();
  54186. this._projectionMatrix = BABYLON.Matrix.Zero();
  54187. this._transformMatrix = BABYLON.Matrix.Zero();
  54188. this._worldViewProjection = BABYLON.Matrix.Zero();
  54189. this._enablePosition = false;
  54190. this._scene = scene;
  54191. this._ratio = ratio;
  54192. // Render target
  54193. this._createRenderTargets();
  54194. }
  54195. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  54196. set: function (meshes) {
  54197. this._multiRenderTarget.renderList = meshes;
  54198. },
  54199. enumerable: true,
  54200. configurable: true
  54201. });
  54202. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  54203. get: function () {
  54204. return this._multiRenderTarget.isSupported;
  54205. },
  54206. enumerable: true,
  54207. configurable: true
  54208. });
  54209. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  54210. get: function () {
  54211. return this._enablePosition;
  54212. },
  54213. set: function (enable) {
  54214. this._enablePosition = enable;
  54215. this.dispose();
  54216. this._createRenderTargets();
  54217. },
  54218. enumerable: true,
  54219. configurable: true
  54220. });
  54221. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  54222. var material = subMesh.getMaterial();
  54223. if (material && material.disableDepthWrite) {
  54224. return false;
  54225. }
  54226. var defines = [];
  54227. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  54228. var mesh = subMesh.getMesh();
  54229. var scene = mesh.getScene();
  54230. // Alpha test
  54231. if (material && material.needAlphaTesting()) {
  54232. defines.push("#define ALPHATEST");
  54233. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54234. attribs.push(BABYLON.VertexBuffer.UVKind);
  54235. defines.push("#define UV1");
  54236. }
  54237. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  54238. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  54239. defines.push("#define UV2");
  54240. }
  54241. }
  54242. // Buffers
  54243. if (this._enablePosition) {
  54244. defines.push("#define POSITION");
  54245. }
  54246. // Bones
  54247. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  54248. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  54249. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  54250. if (mesh.numBoneInfluencers > 4) {
  54251. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  54252. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  54253. }
  54254. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  54255. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  54256. }
  54257. else {
  54258. defines.push("#define NUM_BONE_INFLUENCERS 0");
  54259. }
  54260. // Instances
  54261. if (useInstances) {
  54262. defines.push("#define INSTANCES");
  54263. attribs.push("world0");
  54264. attribs.push("world1");
  54265. attribs.push("world2");
  54266. attribs.push("world3");
  54267. }
  54268. // Get correct effect
  54269. var join = defines.join("\n");
  54270. if (this._cachedDefines !== join) {
  54271. this._cachedDefines = join;
  54272. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join);
  54273. }
  54274. return this._effect.isReady();
  54275. };
  54276. GeometryBufferRenderer.prototype.getGBuffer = function () {
  54277. return this._multiRenderTarget;
  54278. };
  54279. // Methods
  54280. GeometryBufferRenderer.prototype.dispose = function () {
  54281. this.getGBuffer().dispose();
  54282. };
  54283. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  54284. var _this = this;
  54285. var engine = this._scene.getEngine();
  54286. var count = this._enablePosition ? 3 : 2;
  54287. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  54288. if (!this.isSupported) {
  54289. return null;
  54290. }
  54291. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54292. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54293. this._multiRenderTarget.refreshRate = 1;
  54294. this._multiRenderTarget.renderParticles = false;
  54295. this._multiRenderTarget.renderList = null;
  54296. // set default depth value to 1.0 (far away)
  54297. this._multiRenderTarget.onClearObservable.add(function (engine) {
  54298. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  54299. });
  54300. // Custom render function
  54301. var renderSubMesh = function (subMesh) {
  54302. var mesh = subMesh.getRenderingMesh();
  54303. var scene = _this._scene;
  54304. var engine = scene.getEngine();
  54305. // Culling
  54306. engine.setState(subMesh.getMaterial().backFaceCulling);
  54307. // Managing instances
  54308. var batch = mesh._getInstancesRenderList(subMesh._id);
  54309. if (batch.mustReturn) {
  54310. return;
  54311. }
  54312. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  54313. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  54314. engine.enableEffect(_this._effect);
  54315. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  54316. var material = subMesh.getMaterial();
  54317. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  54318. _this._effect.setMatrix("view", scene.getViewMatrix());
  54319. // Alpha test
  54320. if (material && material.needAlphaTesting()) {
  54321. var alphaTexture = material.getAlphaTestTexture();
  54322. _this._effect.setTexture("diffuseSampler", alphaTexture);
  54323. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  54324. }
  54325. // Bones
  54326. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  54327. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  54328. }
  54329. // Draw
  54330. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  54331. }
  54332. };
  54333. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  54334. var index;
  54335. for (index = 0; index < opaqueSubMeshes.length; index++) {
  54336. renderSubMesh(opaqueSubMeshes.data[index]);
  54337. }
  54338. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  54339. renderSubMesh(alphaTestSubMeshes.data[index]);
  54340. }
  54341. };
  54342. };
  54343. return GeometryBufferRenderer;
  54344. }());
  54345. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  54346. })(BABYLON || (BABYLON = {}));
  54347. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  54348. var BABYLON;
  54349. (function (BABYLON) {
  54350. var RefractionPostProcess = (function (_super) {
  54351. __extends(RefractionPostProcess, _super);
  54352. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  54353. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  54354. _this.color = color;
  54355. _this.depth = depth;
  54356. _this.colorLevel = colorLevel;
  54357. _this.onActivateObservable.add(function (cam) {
  54358. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  54359. });
  54360. _this.onApplyObservable.add(function (effect) {
  54361. effect.setColor3("baseColor", _this.color);
  54362. effect.setFloat("depth", _this.depth);
  54363. effect.setFloat("colorLevel", _this.colorLevel);
  54364. effect.setTexture("refractionSampler", _this._refRexture);
  54365. });
  54366. return _this;
  54367. }
  54368. // Methods
  54369. RefractionPostProcess.prototype.dispose = function (camera) {
  54370. if (this._refRexture) {
  54371. this._refRexture.dispose();
  54372. }
  54373. _super.prototype.dispose.call(this, camera);
  54374. };
  54375. return RefractionPostProcess;
  54376. }(BABYLON.PostProcess));
  54377. BABYLON.RefractionPostProcess = RefractionPostProcess;
  54378. })(BABYLON || (BABYLON = {}));
  54379. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  54380. var BABYLON;
  54381. (function (BABYLON) {
  54382. var BlackAndWhitePostProcess = (function (_super) {
  54383. __extends(BlackAndWhitePostProcess, _super);
  54384. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  54385. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  54386. _this.degree = 1;
  54387. _this.onApplyObservable.add(function (effect) {
  54388. effect.setFloat("degree", _this.degree);
  54389. });
  54390. return _this;
  54391. }
  54392. return BlackAndWhitePostProcess;
  54393. }(BABYLON.PostProcess));
  54394. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  54395. })(BABYLON || (BABYLON = {}));
  54396. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  54397. var BABYLON;
  54398. (function (BABYLON) {
  54399. var ConvolutionPostProcess = (function (_super) {
  54400. __extends(ConvolutionPostProcess, _super);
  54401. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  54402. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  54403. _this.kernel = kernel;
  54404. _this.onApply = function (effect) {
  54405. effect.setFloat2("screenSize", _this.width, _this.height);
  54406. effect.setArray("kernel", _this.kernel);
  54407. };
  54408. return _this;
  54409. }
  54410. // Statics
  54411. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  54412. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  54413. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  54414. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  54415. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  54416. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  54417. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  54418. return ConvolutionPostProcess;
  54419. }(BABYLON.PostProcess));
  54420. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  54421. })(BABYLON || (BABYLON = {}));
  54422. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  54423. var BABYLON;
  54424. (function (BABYLON) {
  54425. var FilterPostProcess = (function (_super) {
  54426. __extends(FilterPostProcess, _super);
  54427. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  54428. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  54429. _this.kernelMatrix = kernelMatrix;
  54430. _this.onApply = function (effect) {
  54431. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  54432. };
  54433. return _this;
  54434. }
  54435. return FilterPostProcess;
  54436. }(BABYLON.PostProcess));
  54437. BABYLON.FilterPostProcess = FilterPostProcess;
  54438. })(BABYLON || (BABYLON = {}));
  54439. //# sourceMappingURL=babylon.filterPostProcess.js.map
  54440. var BABYLON;
  54441. (function (BABYLON) {
  54442. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  54443. var VolumetricLightScatteringPostProcess = (function (_super) {
  54444. __extends(VolumetricLightScatteringPostProcess, _super);
  54445. /**
  54446. * @constructor
  54447. * @param {string} name - The post-process name
  54448. * @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)
  54449. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  54450. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  54451. * @param {number} samples - The post-process quality, default 100
  54452. * @param {number} samplingMode - The post-process filtering mode
  54453. * @param {BABYLON.Engine} engine - The babylon engine
  54454. * @param {boolean} reusable - If the post-process is reusable
  54455. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  54456. */
  54457. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  54458. if (samples === void 0) { samples = 100; }
  54459. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  54460. 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;
  54461. _this._screenCoordinates = BABYLON.Vector2.Zero();
  54462. /**
  54463. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  54464. * @type {Vector3}
  54465. */
  54466. _this.customMeshPosition = BABYLON.Vector3.Zero();
  54467. /**
  54468. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  54469. * @type {boolean}
  54470. */
  54471. _this.useCustomMeshPosition = false;
  54472. /**
  54473. * If the post-process should inverse the light scattering direction
  54474. * @type {boolean}
  54475. */
  54476. _this.invert = true;
  54477. /**
  54478. * Array containing the excluded meshes not rendered in the internal pass
  54479. */
  54480. _this.excludedMeshes = new Array();
  54481. /**
  54482. * Controls the overall intensity of the post-process
  54483. * @type {number}
  54484. */
  54485. _this.exposure = 0.3;
  54486. /**
  54487. * Dissipates each sample's contribution in range [0, 1]
  54488. * @type {number}
  54489. */
  54490. _this.decay = 0.96815;
  54491. /**
  54492. * Controls the overall intensity of each sample
  54493. * @type {number}
  54494. */
  54495. _this.weight = 0.58767;
  54496. /**
  54497. * Controls the density of each sample
  54498. * @type {number}
  54499. */
  54500. _this.density = 0.926;
  54501. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  54502. var engine = scene.getEngine();
  54503. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  54504. // Configure mesh
  54505. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  54506. // Configure
  54507. _this._createPass(scene, ratio.passRatio || ratio);
  54508. _this.onActivate = function (camera) {
  54509. if (!_this.isSupported) {
  54510. _this.dispose(camera);
  54511. }
  54512. _this.onActivate = null;
  54513. };
  54514. _this.onApplyObservable.add(function (effect) {
  54515. _this._updateMeshScreenCoordinates(scene);
  54516. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  54517. effect.setFloat("exposure", _this.exposure);
  54518. effect.setFloat("decay", _this.decay);
  54519. effect.setFloat("weight", _this.weight);
  54520. effect.setFloat("density", _this.density);
  54521. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  54522. });
  54523. return _this;
  54524. }
  54525. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  54526. get: function () {
  54527. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  54528. return false;
  54529. },
  54530. set: function (useDiffuseColor) {
  54531. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  54532. },
  54533. enumerable: true,
  54534. configurable: true
  54535. });
  54536. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  54537. return "VolumetricLightScatteringPostProcess";
  54538. };
  54539. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  54540. var mesh = subMesh.getMesh();
  54541. // Render this.mesh as default
  54542. if (mesh === this.mesh) {
  54543. return mesh.material.isReady(mesh);
  54544. }
  54545. var defines = [];
  54546. var attribs = [BABYLON.VertexBuffer.PositionKind];
  54547. var material = subMesh.getMaterial();
  54548. var needUV = false;
  54549. // Alpha test
  54550. if (material) {
  54551. if (material.needAlphaTesting()) {
  54552. defines.push("#define ALPHATEST");
  54553. }
  54554. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54555. attribs.push(BABYLON.VertexBuffer.UVKind);
  54556. defines.push("#define UV1");
  54557. }
  54558. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  54559. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  54560. defines.push("#define UV2");
  54561. }
  54562. }
  54563. // Bones
  54564. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  54565. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  54566. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  54567. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  54568. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  54569. }
  54570. else {
  54571. defines.push("#define NUM_BONE_INFLUENCERS 0");
  54572. }
  54573. // Instances
  54574. if (useInstances) {
  54575. defines.push("#define INSTANCES");
  54576. attribs.push("world0");
  54577. attribs.push("world1");
  54578. attribs.push("world2");
  54579. attribs.push("world3");
  54580. }
  54581. // Get correct effect
  54582. var join = defines.join("\n");
  54583. if (this._cachedDefines !== join) {
  54584. this._cachedDefines = join;
  54585. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  54586. }
  54587. return this._volumetricLightScatteringPass.isReady();
  54588. };
  54589. /**
  54590. * Sets the new light position for light scattering effect
  54591. * @param {BABYLON.Vector3} The new custom light position
  54592. */
  54593. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  54594. this.customMeshPosition = position;
  54595. };
  54596. /**
  54597. * Returns the light position for light scattering effect
  54598. * @return {BABYLON.Vector3} The custom light position
  54599. */
  54600. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  54601. return this.customMeshPosition;
  54602. };
  54603. /**
  54604. * Disposes the internal assets and detaches the post-process from the camera
  54605. */
  54606. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  54607. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  54608. if (rttIndex !== -1) {
  54609. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  54610. }
  54611. this._volumetricLightScatteringRTT.dispose();
  54612. _super.prototype.dispose.call(this, camera);
  54613. };
  54614. /**
  54615. * Returns the render target texture used by the post-process
  54616. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  54617. */
  54618. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  54619. return this._volumetricLightScatteringRTT;
  54620. };
  54621. // Private methods
  54622. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  54623. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  54624. return true;
  54625. }
  54626. return false;
  54627. };
  54628. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  54629. var _this = this;
  54630. var engine = scene.getEngine();
  54631. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  54632. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54633. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54634. this._volumetricLightScatteringRTT.renderList = null;
  54635. this._volumetricLightScatteringRTT.renderParticles = false;
  54636. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  54637. // Custom render function for submeshes
  54638. var renderSubMesh = function (subMesh) {
  54639. var mesh = subMesh.getRenderingMesh();
  54640. if (_this._meshExcluded(mesh)) {
  54641. return;
  54642. }
  54643. var scene = mesh.getScene();
  54644. var engine = scene.getEngine();
  54645. // Culling
  54646. engine.setState(subMesh.getMaterial().backFaceCulling);
  54647. // Managing instances
  54648. var batch = mesh._getInstancesRenderList(subMesh._id);
  54649. if (batch.mustReturn) {
  54650. return;
  54651. }
  54652. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  54653. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  54654. var effect = _this._volumetricLightScatteringPass;
  54655. if (mesh === _this.mesh) {
  54656. if (subMesh.effect) {
  54657. effect = subMesh.effect;
  54658. }
  54659. else {
  54660. effect = subMesh.getMaterial().getEffect();
  54661. }
  54662. }
  54663. engine.enableEffect(effect);
  54664. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  54665. if (mesh === _this.mesh) {
  54666. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  54667. }
  54668. else {
  54669. var material = subMesh.getMaterial();
  54670. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  54671. // Alpha test
  54672. if (material && material.needAlphaTesting()) {
  54673. var alphaTexture = material.getAlphaTestTexture();
  54674. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  54675. if (alphaTexture) {
  54676. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  54677. }
  54678. }
  54679. // Bones
  54680. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  54681. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  54682. }
  54683. }
  54684. // Draw
  54685. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  54686. }
  54687. };
  54688. // Render target texture callbacks
  54689. var savedSceneClearColor;
  54690. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  54691. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  54692. savedSceneClearColor = scene.clearColor;
  54693. scene.clearColor = sceneClearColor;
  54694. });
  54695. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  54696. scene.clearColor = savedSceneClearColor;
  54697. });
  54698. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  54699. var engine = scene.getEngine();
  54700. var index;
  54701. for (index = 0; index < opaqueSubMeshes.length; index++) {
  54702. renderSubMesh(opaqueSubMeshes.data[index]);
  54703. }
  54704. engine.setAlphaTesting(true);
  54705. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  54706. renderSubMesh(alphaTestSubMeshes.data[index]);
  54707. }
  54708. engine.setAlphaTesting(false);
  54709. if (transparentSubMeshes.length) {
  54710. // Sort sub meshes
  54711. for (index = 0; index < transparentSubMeshes.length; index++) {
  54712. var submesh = transparentSubMeshes.data[index];
  54713. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  54714. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  54715. }
  54716. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  54717. sortedArray.sort(function (a, b) {
  54718. // Alpha index first
  54719. if (a._alphaIndex > b._alphaIndex) {
  54720. return 1;
  54721. }
  54722. if (a._alphaIndex < b._alphaIndex) {
  54723. return -1;
  54724. }
  54725. // Then distance to camera
  54726. if (a._distanceToCamera < b._distanceToCamera) {
  54727. return 1;
  54728. }
  54729. if (a._distanceToCamera > b._distanceToCamera) {
  54730. return -1;
  54731. }
  54732. return 0;
  54733. });
  54734. // Render sub meshes
  54735. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54736. for (index = 0; index < sortedArray.length; index++) {
  54737. renderSubMesh(sortedArray[index]);
  54738. }
  54739. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54740. }
  54741. };
  54742. };
  54743. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  54744. var transform = scene.getTransformMatrix();
  54745. var meshPosition;
  54746. if (this.useCustomMeshPosition) {
  54747. meshPosition = this.customMeshPosition;
  54748. }
  54749. else if (this.attachedNode) {
  54750. meshPosition = this.attachedNode.position;
  54751. }
  54752. else {
  54753. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  54754. }
  54755. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  54756. this._screenCoordinates.x = pos.x / this._viewPort.width;
  54757. this._screenCoordinates.y = pos.y / this._viewPort.height;
  54758. if (this.invert)
  54759. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  54760. };
  54761. // Static methods
  54762. /**
  54763. * Creates a default mesh for the Volumeric Light Scattering post-process
  54764. * @param {string} The mesh name
  54765. * @param {BABYLON.Scene} The scene where to create the mesh
  54766. * @return {BABYLON.Mesh} the default mesh
  54767. */
  54768. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  54769. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  54770. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  54771. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  54772. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  54773. mesh.material = material;
  54774. return mesh;
  54775. };
  54776. __decorate([
  54777. BABYLON.serializeAsVector3()
  54778. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  54779. __decorate([
  54780. BABYLON.serialize()
  54781. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  54782. __decorate([
  54783. BABYLON.serialize()
  54784. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  54785. __decorate([
  54786. BABYLON.serializeAsMeshReference()
  54787. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  54788. __decorate([
  54789. BABYLON.serialize()
  54790. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  54791. __decorate([
  54792. BABYLON.serialize()
  54793. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  54794. __decorate([
  54795. BABYLON.serialize()
  54796. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  54797. __decorate([
  54798. BABYLON.serialize()
  54799. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  54800. __decorate([
  54801. BABYLON.serialize()
  54802. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  54803. return VolumetricLightScatteringPostProcess;
  54804. }(BABYLON.PostProcess));
  54805. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  54806. })(BABYLON || (BABYLON = {}));
  54807. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  54808. //
  54809. // This post-process allows the modification of rendered colors by using
  54810. // a 'look-up table' (LUT). This effect is also called Color Grading.
  54811. //
  54812. // The object needs to be provided an url to a texture containing the color
  54813. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  54814. // Use an image editing software to tweak the LUT to match your needs.
  54815. //
  54816. // For an example of a color LUT, see here:
  54817. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  54818. // For explanations on color grading, see here:
  54819. // http://udn.epicgames.com/Three/ColorGrading.html
  54820. //
  54821. var BABYLON;
  54822. (function (BABYLON) {
  54823. var ColorCorrectionPostProcess = (function (_super) {
  54824. __extends(ColorCorrectionPostProcess, _super);
  54825. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  54826. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  54827. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  54828. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  54829. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54830. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54831. _this.onApply = function (effect) {
  54832. effect.setTexture("colorTable", _this._colorTableTexture);
  54833. };
  54834. return _this;
  54835. }
  54836. return ColorCorrectionPostProcess;
  54837. }(BABYLON.PostProcess));
  54838. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  54839. })(BABYLON || (BABYLON = {}));
  54840. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  54841. var BABYLON;
  54842. (function (BABYLON) {
  54843. var TonemappingOperator;
  54844. (function (TonemappingOperator) {
  54845. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  54846. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  54847. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  54848. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  54849. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  54850. ;
  54851. var TonemapPostProcess = (function (_super) {
  54852. __extends(TonemapPostProcess, _super);
  54853. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  54854. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  54855. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54856. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  54857. _this._operator = _operator;
  54858. _this.exposureAdjustment = exposureAdjustment;
  54859. var defines = "#define ";
  54860. if (_this._operator === TonemappingOperator.Hable)
  54861. defines += "HABLE_TONEMAPPING";
  54862. else if (_this._operator === TonemappingOperator.Reinhard)
  54863. defines += "REINHARD_TONEMAPPING";
  54864. else if (_this._operator === TonemappingOperator.HejiDawson)
  54865. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  54866. else if (_this._operator === TonemappingOperator.Photographic)
  54867. defines += "PHOTOGRAPHIC_TONEMAPPING";
  54868. //sadly a second call to create the effect.
  54869. _this.updateEffect(defines);
  54870. _this.onApply = function (effect) {
  54871. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  54872. };
  54873. return _this;
  54874. }
  54875. return TonemapPostProcess;
  54876. }(BABYLON.PostProcess));
  54877. BABYLON.TonemapPostProcess = TonemapPostProcess;
  54878. })(BABYLON || (BABYLON = {}));
  54879. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  54880. var BABYLON;
  54881. (function (BABYLON) {
  54882. var DisplayPassPostProcess = (function (_super) {
  54883. __extends(DisplayPassPostProcess, _super);
  54884. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  54885. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  54886. }
  54887. return DisplayPassPostProcess;
  54888. }(BABYLON.PostProcess));
  54889. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  54890. })(BABYLON || (BABYLON = {}));
  54891. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  54892. var BABYLON;
  54893. (function (BABYLON) {
  54894. var HighlightsPostProcess = (function (_super) {
  54895. __extends(HighlightsPostProcess, _super);
  54896. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  54897. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54898. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  54899. }
  54900. return HighlightsPostProcess;
  54901. }(BABYLON.PostProcess));
  54902. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  54903. })(BABYLON || (BABYLON = {}));
  54904. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  54905. var BABYLON;
  54906. (function (BABYLON) {
  54907. var ImageProcessingPostProcess = (function (_super) {
  54908. __extends(ImageProcessingPostProcess, _super);
  54909. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  54910. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54911. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  54912. _this._fromLinearSpace = true;
  54913. /**
  54914. * Defines cache preventing GC.
  54915. */
  54916. _this._defines = {
  54917. IMAGEPROCESSING: false,
  54918. VIGNETTE: false,
  54919. VIGNETTEBLENDMODEMULTIPLY: false,
  54920. VIGNETTEBLENDMODEOPAQUE: false,
  54921. TONEMAPPING: false,
  54922. CONTRAST: false,
  54923. COLORCURVES: false,
  54924. COLORGRADING: false,
  54925. FROMLINEARSPACE: false,
  54926. SAMPLER3DGREENDEPTH: false,
  54927. SAMPLER3DBGRMAP: false,
  54928. IMAGEPROCESSINGPOSTPROCESS: false,
  54929. EXPOSURE: false,
  54930. };
  54931. // Setup the default processing configuration to the scene.
  54932. _this._attachImageProcessingConfiguration(null, true);
  54933. _this.imageProcessingConfiguration.applyByPostProcess = true;
  54934. _this.onApply = function (effect) {
  54935. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  54936. };
  54937. return _this;
  54938. }
  54939. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  54940. /**
  54941. * Gets the image processing configuration used either in this material.
  54942. */
  54943. get: function () {
  54944. return this._imageProcessingConfiguration;
  54945. },
  54946. /**
  54947. * Sets the Default image processing configuration used either in the this material.
  54948. *
  54949. * If sets to null, the scene one is in use.
  54950. */
  54951. set: function (value) {
  54952. this._attachImageProcessingConfiguration(value);
  54953. },
  54954. enumerable: true,
  54955. configurable: true
  54956. });
  54957. /**
  54958. * Attaches a new image processing configuration to the PBR Material.
  54959. * @param configuration
  54960. */
  54961. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  54962. var _this = this;
  54963. if (doNotBuild === void 0) { doNotBuild = false; }
  54964. if (configuration === this._imageProcessingConfiguration) {
  54965. return;
  54966. }
  54967. // Detaches observer.
  54968. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  54969. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  54970. }
  54971. // Pick the scene configuration if needed.
  54972. if (!configuration) {
  54973. var camera = this.getCamera();
  54974. var scene = camera ? camera.getScene() : BABYLON.Engine.LastCreatedScene;
  54975. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  54976. }
  54977. else {
  54978. this._imageProcessingConfiguration = configuration;
  54979. }
  54980. // Attaches observer.
  54981. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  54982. _this._updateParameters();
  54983. });
  54984. // Ensure the effect will be rebuilt.
  54985. if (!doNotBuild) {
  54986. this._updateParameters();
  54987. }
  54988. };
  54989. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  54990. /**
  54991. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  54992. */
  54993. get: function () {
  54994. return this.imageProcessingConfiguration.colorCurves;
  54995. },
  54996. /**
  54997. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  54998. */
  54999. set: function (value) {
  55000. this.imageProcessingConfiguration.colorCurves = value;
  55001. },
  55002. enumerable: true,
  55003. configurable: true
  55004. });
  55005. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  55006. /**
  55007. * Gets wether the color curves effect is enabled.
  55008. */
  55009. get: function () {
  55010. return this.imageProcessingConfiguration.colorCurvesEnabled;
  55011. },
  55012. /**
  55013. * Sets wether the color curves effect is enabled.
  55014. */
  55015. set: function (value) {
  55016. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  55017. },
  55018. enumerable: true,
  55019. configurable: true
  55020. });
  55021. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  55022. /**
  55023. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  55024. */
  55025. get: function () {
  55026. return this.imageProcessingConfiguration.colorGradingTexture;
  55027. },
  55028. /**
  55029. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  55030. */
  55031. set: function (value) {
  55032. this.imageProcessingConfiguration.colorGradingTexture = value;
  55033. },
  55034. enumerable: true,
  55035. configurable: true
  55036. });
  55037. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  55038. /**
  55039. * Gets wether the color grading effect is enabled.
  55040. */
  55041. get: function () {
  55042. return this.imageProcessingConfiguration.colorGradingEnabled;
  55043. },
  55044. /**
  55045. * Gets wether the color grading effect is enabled.
  55046. */
  55047. set: function (value) {
  55048. this.imageProcessingConfiguration.colorGradingEnabled = value;
  55049. },
  55050. enumerable: true,
  55051. configurable: true
  55052. });
  55053. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  55054. /**
  55055. * Gets exposure used in the effect.
  55056. */
  55057. get: function () {
  55058. return this.imageProcessingConfiguration.exposure;
  55059. },
  55060. /**
  55061. * Sets exposure used in the effect.
  55062. */
  55063. set: function (value) {
  55064. this.imageProcessingConfiguration.exposure = value;
  55065. },
  55066. enumerable: true,
  55067. configurable: true
  55068. });
  55069. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  55070. /**
  55071. * Gets wether tonemapping is enabled or not.
  55072. */
  55073. get: function () {
  55074. return this._imageProcessingConfiguration.toneMappingEnabled;
  55075. },
  55076. /**
  55077. * Sets wether tonemapping is enabled or not
  55078. */
  55079. set: function (value) {
  55080. this._imageProcessingConfiguration.toneMappingEnabled = value;
  55081. },
  55082. enumerable: true,
  55083. configurable: true
  55084. });
  55085. ;
  55086. ;
  55087. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  55088. /**
  55089. * Gets contrast used in the effect.
  55090. */
  55091. get: function () {
  55092. return this.imageProcessingConfiguration.contrast;
  55093. },
  55094. /**
  55095. * Sets contrast used in the effect.
  55096. */
  55097. set: function (value) {
  55098. this.imageProcessingConfiguration.contrast = value;
  55099. },
  55100. enumerable: true,
  55101. configurable: true
  55102. });
  55103. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  55104. /**
  55105. * Gets Vignette stretch size.
  55106. */
  55107. get: function () {
  55108. return this.imageProcessingConfiguration.vignetteStretch;
  55109. },
  55110. /**
  55111. * Sets Vignette stretch size.
  55112. */
  55113. set: function (value) {
  55114. this.imageProcessingConfiguration.vignetteStretch = value;
  55115. },
  55116. enumerable: true,
  55117. configurable: true
  55118. });
  55119. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  55120. /**
  55121. * Gets Vignette centre X Offset.
  55122. */
  55123. get: function () {
  55124. return this.imageProcessingConfiguration.vignetteCentreX;
  55125. },
  55126. /**
  55127. * Sets Vignette centre X Offset.
  55128. */
  55129. set: function (value) {
  55130. this.imageProcessingConfiguration.vignetteCentreX = value;
  55131. },
  55132. enumerable: true,
  55133. configurable: true
  55134. });
  55135. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  55136. /**
  55137. * Gets Vignette centre Y Offset.
  55138. */
  55139. get: function () {
  55140. return this.imageProcessingConfiguration.vignetteCentreY;
  55141. },
  55142. /**
  55143. * Sets Vignette centre Y Offset.
  55144. */
  55145. set: function (value) {
  55146. this.imageProcessingConfiguration.vignetteCentreY = value;
  55147. },
  55148. enumerable: true,
  55149. configurable: true
  55150. });
  55151. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  55152. /**
  55153. * Gets Vignette weight or intensity of the vignette effect.
  55154. */
  55155. get: function () {
  55156. return this.imageProcessingConfiguration.vignetteWeight;
  55157. },
  55158. /**
  55159. * Sets Vignette weight or intensity of the vignette effect.
  55160. */
  55161. set: function (value) {
  55162. this.imageProcessingConfiguration.vignetteWeight = value;
  55163. },
  55164. enumerable: true,
  55165. configurable: true
  55166. });
  55167. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  55168. /**
  55169. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  55170. * if vignetteEnabled is set to true.
  55171. */
  55172. get: function () {
  55173. return this.imageProcessingConfiguration.vignetteColor;
  55174. },
  55175. /**
  55176. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  55177. * if vignetteEnabled is set to true.
  55178. */
  55179. set: function (value) {
  55180. this.imageProcessingConfiguration.vignetteColor = value;
  55181. },
  55182. enumerable: true,
  55183. configurable: true
  55184. });
  55185. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  55186. /**
  55187. * Gets Camera field of view used by the Vignette effect.
  55188. */
  55189. get: function () {
  55190. return this.imageProcessingConfiguration.vignetteCameraFov;
  55191. },
  55192. /**
  55193. * Sets Camera field of view used by the Vignette effect.
  55194. */
  55195. set: function (value) {
  55196. this.imageProcessingConfiguration.vignetteCameraFov = value;
  55197. },
  55198. enumerable: true,
  55199. configurable: true
  55200. });
  55201. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  55202. /**
  55203. * Gets the vignette blend mode allowing different kind of effect.
  55204. */
  55205. get: function () {
  55206. return this.imageProcessingConfiguration.vignetteBlendMode;
  55207. },
  55208. /**
  55209. * Sets the vignette blend mode allowing different kind of effect.
  55210. */
  55211. set: function (value) {
  55212. this.imageProcessingConfiguration.vignetteBlendMode = value;
  55213. },
  55214. enumerable: true,
  55215. configurable: true
  55216. });
  55217. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  55218. /**
  55219. * Gets wether the vignette effect is enabled.
  55220. */
  55221. get: function () {
  55222. return this.imageProcessingConfiguration.vignetteEnabled;
  55223. },
  55224. /**
  55225. * Sets wether the vignette effect is enabled.
  55226. */
  55227. set: function (value) {
  55228. this.imageProcessingConfiguration.vignetteEnabled = value;
  55229. },
  55230. enumerable: true,
  55231. configurable: true
  55232. });
  55233. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  55234. /**
  55235. * Gets wether the input of the processing is in Gamma or Linear Space.
  55236. */
  55237. get: function () {
  55238. return this._fromLinearSpace;
  55239. },
  55240. /**
  55241. * Sets wether the input of the processing is in Gamma or Linear Space.
  55242. */
  55243. set: function (value) {
  55244. if (this._fromLinearSpace === value) {
  55245. return;
  55246. }
  55247. this._fromLinearSpace = value;
  55248. this._updateParameters();
  55249. },
  55250. enumerable: true,
  55251. configurable: true
  55252. });
  55253. ImageProcessingPostProcess.prototype.getClassName = function () {
  55254. return "ImageProcessingPostProcess";
  55255. };
  55256. ImageProcessingPostProcess.prototype._updateParameters = function () {
  55257. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  55258. this.imageProcessingConfiguration.prepareDefines(this._defines);
  55259. var defines = "";
  55260. for (var define in this._defines) {
  55261. if (this._defines[define]) {
  55262. defines += "#define " + define + ";\r\n";
  55263. }
  55264. }
  55265. var samplers = ["textureSampler"];
  55266. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  55267. var uniforms = ["scale"];
  55268. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  55269. this.updateEffect(defines, uniforms, samplers);
  55270. };
  55271. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  55272. _super.prototype.dispose.call(this, camera);
  55273. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  55274. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  55275. }
  55276. this.imageProcessingConfiguration.applyByPostProcess = false;
  55277. };
  55278. __decorate([
  55279. BABYLON.serialize()
  55280. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  55281. return ImageProcessingPostProcess;
  55282. }(BABYLON.PostProcess));
  55283. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  55284. })(BABYLON || (BABYLON = {}));
  55285. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  55286. var BABYLON;
  55287. (function (BABYLON) {
  55288. var BlurPostProcess = (function (_super) {
  55289. __extends(BlurPostProcess, _super);
  55290. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  55291. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  55292. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55293. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  55294. _this.direction = direction;
  55295. _this._packedFloat = false;
  55296. _this.onApplyObservable.add(function (effect) {
  55297. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  55298. });
  55299. _this.kernel = kernel;
  55300. return _this;
  55301. }
  55302. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  55303. /**
  55304. * Gets the length in pixels of the blur sample region
  55305. */
  55306. get: function () {
  55307. return this._idealKernel;
  55308. },
  55309. /**
  55310. * Sets the length in pixels of the blur sample region
  55311. */
  55312. set: function (v) {
  55313. if (this._idealKernel === v) {
  55314. return;
  55315. }
  55316. v = Math.max(v, 1);
  55317. this._idealKernel = v;
  55318. this._kernel = this._nearestBestKernel(v);
  55319. this._updateParameters();
  55320. },
  55321. enumerable: true,
  55322. configurable: true
  55323. });
  55324. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  55325. /**
  55326. * Gets wether or not the blur is unpacking/repacking floats
  55327. */
  55328. get: function () {
  55329. return this._packedFloat;
  55330. },
  55331. /**
  55332. * Sets wether or not the blur needs to unpack/repack floats
  55333. */
  55334. set: function (v) {
  55335. if (this._packedFloat === v) {
  55336. return;
  55337. }
  55338. this._packedFloat = v;
  55339. this._updateParameters();
  55340. },
  55341. enumerable: true,
  55342. configurable: true
  55343. });
  55344. BlurPostProcess.prototype._updateParameters = function () {
  55345. // Generate sampling offsets and weights
  55346. var N = this._kernel;
  55347. var centerIndex = (N - 1) / 2;
  55348. // Generate Gaussian sampling weights over kernel
  55349. var offsets = [];
  55350. var weights = [];
  55351. var totalWeight = 0;
  55352. for (var i = 0; i < N; i++) {
  55353. var u = i / (N - 1);
  55354. var w = this._gaussianWeight(u * 2.0 - 1);
  55355. offsets[i] = (i - centerIndex);
  55356. weights[i] = w;
  55357. totalWeight += w;
  55358. }
  55359. // Normalize weights
  55360. for (var i = 0; i < weights.length; i++) {
  55361. weights[i] /= totalWeight;
  55362. }
  55363. // Optimize: combine samples to take advantage of hardware linear sampling
  55364. // Walk from left to center, combining pairs (symmetrically)
  55365. var linearSamplingWeights = [];
  55366. var linearSamplingOffsets = [];
  55367. var linearSamplingMap = [];
  55368. for (var i = 0; i <= centerIndex; i += 2) {
  55369. var j = Math.min(i + 1, Math.floor(centerIndex));
  55370. var singleCenterSample = i === j;
  55371. if (singleCenterSample) {
  55372. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  55373. }
  55374. else {
  55375. var sharedCell = j === centerIndex;
  55376. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  55377. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  55378. if (offsetLinear === 0) {
  55379. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  55380. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  55381. }
  55382. else {
  55383. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  55384. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  55385. }
  55386. }
  55387. }
  55388. for (var i = 0; i < linearSamplingMap.length; i++) {
  55389. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  55390. linearSamplingWeights[i] = linearSamplingMap[i].w;
  55391. }
  55392. // Replace with optimized
  55393. offsets = linearSamplingOffsets;
  55394. weights = linearSamplingWeights;
  55395. // Generate shaders
  55396. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  55397. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  55398. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  55399. var defines = "";
  55400. for (var i = 0; i < varyingCount; i++) {
  55401. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  55402. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  55403. }
  55404. var depCount = 0;
  55405. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  55406. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  55407. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  55408. depCount++;
  55409. }
  55410. if (this.packedFloat) {
  55411. defines += "#define PACKEDFLOAT 1";
  55412. }
  55413. this.updateEffect(defines, null, null, {
  55414. varyingCount: varyingCount,
  55415. depCount: depCount
  55416. });
  55417. };
  55418. /**
  55419. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  55420. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  55421. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  55422. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  55423. * The gaps between physical kernels are compensated for in the weighting of the samples
  55424. * @param idealKernel Ideal blur kernel.
  55425. * @return Nearest best kernel.
  55426. */
  55427. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  55428. var v = Math.round(idealKernel);
  55429. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  55430. var k = _a[_i];
  55431. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  55432. return Math.max(k, 3);
  55433. }
  55434. }
  55435. return Math.max(v, 3);
  55436. };
  55437. /**
  55438. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  55439. * @param x The point on the Gaussian distribution to sample.
  55440. * @return the value of the Gaussian function at x.
  55441. */
  55442. BlurPostProcess.prototype._gaussianWeight = function (x) {
  55443. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  55444. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  55445. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  55446. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  55447. // truncated at around 1.3% of peak strength.
  55448. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  55449. var sigma = (1 / 3);
  55450. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  55451. var exponent = -((x * x) / (2.0 * sigma * sigma));
  55452. var weight = (1.0 / denominator) * Math.exp(exponent);
  55453. return weight;
  55454. };
  55455. /**
  55456. * Generates a string that can be used as a floating point number in GLSL.
  55457. * @param x Value to print.
  55458. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  55459. * @return GLSL float string.
  55460. */
  55461. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  55462. if (decimalFigures === void 0) { decimalFigures = 8; }
  55463. return x.toFixed(decimalFigures).replace(/0+$/, '');
  55464. };
  55465. return BlurPostProcess;
  55466. }(BABYLON.PostProcess));
  55467. BABYLON.BlurPostProcess = BlurPostProcess;
  55468. })(BABYLON || (BABYLON = {}));
  55469. //# sourceMappingURL=babylon.blurPostProcess.js.map
  55470. /// <reference path="..\babylon.node.ts" />
  55471. var BABYLON;
  55472. (function (BABYLON) {
  55473. var Bone = (function (_super) {
  55474. __extends(Bone, _super);
  55475. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  55476. if (parentBone === void 0) { parentBone = null; }
  55477. var _this = _super.call(this, name, skeleton.getScene()) || this;
  55478. _this.name = name;
  55479. _this.children = new Array();
  55480. _this.animations = new Array();
  55481. _this._worldTransform = new BABYLON.Matrix();
  55482. _this._absoluteTransform = new BABYLON.Matrix();
  55483. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  55484. _this._scaleMatrix = BABYLON.Matrix.Identity();
  55485. _this._scaleVector = BABYLON.Vector3.One();
  55486. _this._negateScaleChildren = BABYLON.Vector3.One();
  55487. _this._scalingDeterminant = 1;
  55488. _this._skeleton = skeleton;
  55489. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  55490. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  55491. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  55492. _this._index = index;
  55493. skeleton.bones.push(_this);
  55494. _this.setParent(parentBone, false);
  55495. _this._updateDifferenceMatrix();
  55496. return _this;
  55497. }
  55498. Object.defineProperty(Bone.prototype, "_matrix", {
  55499. get: function () {
  55500. return this._localMatrix;
  55501. },
  55502. set: function (val) {
  55503. if (this._localMatrix) {
  55504. this._localMatrix.copyFrom(val);
  55505. }
  55506. else {
  55507. this._localMatrix = val;
  55508. }
  55509. },
  55510. enumerable: true,
  55511. configurable: true
  55512. });
  55513. // Members
  55514. Bone.prototype.getSkeleton = function () {
  55515. return this._skeleton;
  55516. };
  55517. Bone.prototype.getParent = function () {
  55518. return this._parent;
  55519. };
  55520. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  55521. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  55522. if (this._parent === parent) {
  55523. return;
  55524. }
  55525. if (this._parent) {
  55526. var index = this._parent.children.indexOf(this);
  55527. if (index !== -1) {
  55528. this._parent.children.splice(index);
  55529. }
  55530. }
  55531. this._parent = parent;
  55532. if (this._parent) {
  55533. this._parent.children.push(this);
  55534. }
  55535. if (updateDifferenceMatrix) {
  55536. this._updateDifferenceMatrix();
  55537. }
  55538. };
  55539. Bone.prototype.getLocalMatrix = function () {
  55540. return this._localMatrix;
  55541. };
  55542. Bone.prototype.getBaseMatrix = function () {
  55543. return this._baseMatrix;
  55544. };
  55545. Bone.prototype.getRestPose = function () {
  55546. return this._restPose;
  55547. };
  55548. Bone.prototype.returnToRest = function () {
  55549. this.updateMatrix(this._restPose.clone());
  55550. };
  55551. Bone.prototype.getWorldMatrix = function () {
  55552. return this._worldTransform;
  55553. };
  55554. Bone.prototype.getInvertedAbsoluteTransform = function () {
  55555. return this._invertedAbsoluteTransform;
  55556. };
  55557. Bone.prototype.getAbsoluteTransform = function () {
  55558. return this._absoluteTransform;
  55559. };
  55560. Object.defineProperty(Bone.prototype, "position", {
  55561. // Properties (matches AbstractMesh properties)
  55562. get: function () {
  55563. return this.getPosition();
  55564. },
  55565. set: function (newPosition) {
  55566. this.setPosition(newPosition);
  55567. },
  55568. enumerable: true,
  55569. configurable: true
  55570. });
  55571. Object.defineProperty(Bone.prototype, "rotation", {
  55572. get: function () {
  55573. return this.getRotation();
  55574. },
  55575. set: function (newRotation) {
  55576. this.setRotation(newRotation);
  55577. },
  55578. enumerable: true,
  55579. configurable: true
  55580. });
  55581. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  55582. get: function () {
  55583. return this.getRotationQuaternion();
  55584. },
  55585. set: function (newRotation) {
  55586. this.setRotationQuaternion(newRotation);
  55587. },
  55588. enumerable: true,
  55589. configurable: true
  55590. });
  55591. Object.defineProperty(Bone.prototype, "scaling", {
  55592. get: function () {
  55593. return this.getScale();
  55594. },
  55595. set: function (newScaling) {
  55596. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  55597. },
  55598. enumerable: true,
  55599. configurable: true
  55600. });
  55601. // Methods
  55602. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  55603. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  55604. this._baseMatrix = matrix.clone();
  55605. this._localMatrix = matrix.clone();
  55606. this._skeleton._markAsDirty();
  55607. if (updateDifferenceMatrix) {
  55608. this._updateDifferenceMatrix();
  55609. }
  55610. };
  55611. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  55612. if (!rootMatrix) {
  55613. rootMatrix = this._baseMatrix;
  55614. }
  55615. if (this._parent) {
  55616. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  55617. }
  55618. else {
  55619. this._absoluteTransform.copyFrom(rootMatrix);
  55620. }
  55621. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  55622. for (var index = 0; index < this.children.length; index++) {
  55623. this.children[index]._updateDifferenceMatrix();
  55624. }
  55625. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  55626. };
  55627. Bone.prototype.markAsDirty = function () {
  55628. this._currentRenderId++;
  55629. this._skeleton._markAsDirty();
  55630. };
  55631. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  55632. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  55633. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  55634. // all animation may be coming from a library skeleton, so may need to create animation
  55635. if (this.animations.length === 0) {
  55636. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  55637. this.animations[0].setKeys([]);
  55638. }
  55639. // get animation info / verify there is such a range from the source bone
  55640. var sourceRange = source.animations[0].getRange(rangeName);
  55641. if (!sourceRange) {
  55642. return false;
  55643. }
  55644. var from = sourceRange.from;
  55645. var to = sourceRange.to;
  55646. var sourceKeys = source.animations[0].getKeys();
  55647. // rescaling prep
  55648. var sourceBoneLength = source.length;
  55649. var sourceParent = source.getParent();
  55650. var parent = this.getParent();
  55651. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  55652. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  55653. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  55654. var destKeys = this.animations[0].getKeys();
  55655. // loop vars declaration
  55656. var orig;
  55657. var origTranslation;
  55658. var mat;
  55659. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  55660. orig = sourceKeys[key];
  55661. if (orig.frame >= from && orig.frame <= to) {
  55662. if (rescaleAsRequired) {
  55663. mat = orig.value.clone();
  55664. // scale based on parent ratio, when bone has parent
  55665. if (parentScalingReqd) {
  55666. origTranslation = mat.getTranslation();
  55667. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  55668. // scale based on skeleton dimension ratio when root bone, and value is passed
  55669. }
  55670. else if (dimensionsScalingReqd) {
  55671. origTranslation = mat.getTranslation();
  55672. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  55673. // use original when root bone, and no data for skelDimensionsRatio
  55674. }
  55675. else {
  55676. mat = orig.value;
  55677. }
  55678. }
  55679. else {
  55680. mat = orig.value;
  55681. }
  55682. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  55683. }
  55684. }
  55685. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  55686. return true;
  55687. };
  55688. /**
  55689. * Translate the bone in local or world space.
  55690. * @param vec The amount to translate the bone.
  55691. * @param space The space that the translation is in.
  55692. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55693. */
  55694. Bone.prototype.translate = function (vec, space, mesh) {
  55695. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55696. var lm = this.getLocalMatrix();
  55697. if (space == BABYLON.Space.LOCAL) {
  55698. lm.m[12] += vec.x;
  55699. lm.m[13] += vec.y;
  55700. lm.m[14] += vec.z;
  55701. }
  55702. else {
  55703. var wm;
  55704. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  55705. if (mesh) {
  55706. wm = mesh.getWorldMatrix();
  55707. }
  55708. this._skeleton.computeAbsoluteTransforms();
  55709. var tmat = Bone._tmpMats[0];
  55710. var tvec = Bone._tmpVecs[0];
  55711. if (mesh) {
  55712. tmat.copyFrom(this._parent.getAbsoluteTransform());
  55713. tmat.multiplyToRef(wm, tmat);
  55714. }
  55715. else {
  55716. tmat.copyFrom(this._parent.getAbsoluteTransform());
  55717. }
  55718. tmat.m[12] = 0;
  55719. tmat.m[13] = 0;
  55720. tmat.m[14] = 0;
  55721. tmat.invert();
  55722. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  55723. lm.m[12] += tvec.x;
  55724. lm.m[13] += tvec.y;
  55725. lm.m[14] += tvec.z;
  55726. }
  55727. this.markAsDirty();
  55728. };
  55729. /**
  55730. * Set the postion of the bone in local or world space.
  55731. * @param position The position to set the bone.
  55732. * @param space The space that the position is in.
  55733. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55734. */
  55735. Bone.prototype.setPosition = function (position, space, mesh) {
  55736. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55737. var lm = this.getLocalMatrix();
  55738. if (space == BABYLON.Space.LOCAL) {
  55739. lm.m[12] = position.x;
  55740. lm.m[13] = position.y;
  55741. lm.m[14] = position.z;
  55742. }
  55743. else {
  55744. var wm;
  55745. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  55746. if (mesh) {
  55747. wm = mesh.getWorldMatrix();
  55748. }
  55749. this._skeleton.computeAbsoluteTransforms();
  55750. var tmat = Bone._tmpMats[0];
  55751. var vec = Bone._tmpVecs[0];
  55752. if (mesh) {
  55753. tmat.copyFrom(this._parent.getAbsoluteTransform());
  55754. tmat.multiplyToRef(wm, tmat);
  55755. }
  55756. else {
  55757. tmat.copyFrom(this._parent.getAbsoluteTransform());
  55758. }
  55759. tmat.invert();
  55760. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  55761. lm.m[12] = vec.x;
  55762. lm.m[13] = vec.y;
  55763. lm.m[14] = vec.z;
  55764. }
  55765. this.markAsDirty();
  55766. };
  55767. /**
  55768. * Set the absolute postion of the bone (world space).
  55769. * @param position The position to set the bone.
  55770. * @param mesh The mesh that this bone is attached to.
  55771. */
  55772. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  55773. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  55774. };
  55775. /**
  55776. * Set the scale of the bone on the x, y and z axes.
  55777. * @param x The scale of the bone on the x axis.
  55778. * @param x The scale of the bone on the y axis.
  55779. * @param z The scale of the bone on the z axis.
  55780. * @param scaleChildren Set this to true if children of the bone should be scaled.
  55781. */
  55782. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  55783. if (scaleChildren === void 0) { scaleChildren = false; }
  55784. if (this.animations[0] && !this.animations[0].isStopped()) {
  55785. if (!scaleChildren) {
  55786. this._negateScaleChildren.x = 1 / x;
  55787. this._negateScaleChildren.y = 1 / y;
  55788. this._negateScaleChildren.z = 1 / z;
  55789. }
  55790. this._syncScaleVector();
  55791. }
  55792. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  55793. };
  55794. /**
  55795. * Scale the bone on the x, y and z axes.
  55796. * @param x The amount to scale the bone on the x axis.
  55797. * @param x The amount to scale the bone on the y axis.
  55798. * @param z The amount to scale the bone on the z axis.
  55799. * @param scaleChildren Set this to true if children of the bone should be scaled.
  55800. */
  55801. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  55802. if (scaleChildren === void 0) { scaleChildren = false; }
  55803. var locMat = this.getLocalMatrix();
  55804. var origLocMat = Bone._tmpMats[0];
  55805. origLocMat.copyFrom(locMat);
  55806. var origLocMatInv = Bone._tmpMats[1];
  55807. origLocMatInv.copyFrom(origLocMat);
  55808. origLocMatInv.invert();
  55809. var scaleMat = Bone._tmpMats[2];
  55810. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  55811. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  55812. this._scaleVector.x *= x;
  55813. this._scaleVector.y *= y;
  55814. this._scaleVector.z *= z;
  55815. locMat.multiplyToRef(origLocMatInv, locMat);
  55816. locMat.multiplyToRef(scaleMat, locMat);
  55817. locMat.multiplyToRef(origLocMat, locMat);
  55818. var parent = this.getParent();
  55819. if (parent) {
  55820. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  55821. }
  55822. else {
  55823. this.getAbsoluteTransform().copyFrom(locMat);
  55824. }
  55825. var len = this.children.length;
  55826. scaleMat.invert();
  55827. for (var i = 0; i < len; i++) {
  55828. var child = this.children[i];
  55829. var cm = child.getLocalMatrix();
  55830. cm.multiplyToRef(scaleMat, cm);
  55831. var lm = child.getLocalMatrix();
  55832. lm.m[12] *= x;
  55833. lm.m[13] *= y;
  55834. lm.m[14] *= z;
  55835. }
  55836. this.computeAbsoluteTransforms();
  55837. if (scaleChildren) {
  55838. for (var i = 0; i < len; i++) {
  55839. this.children[i].scale(x, y, z, scaleChildren);
  55840. }
  55841. }
  55842. this.markAsDirty();
  55843. };
  55844. /**
  55845. * Set the yaw, pitch, and roll of the bone in local or world space.
  55846. * @param yaw The rotation of the bone on the y axis.
  55847. * @param pitch The rotation of the bone on the x axis.
  55848. * @param roll The rotation of the bone on the z axis.
  55849. * @param space The space that the axes of rotation are in.
  55850. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55851. */
  55852. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  55853. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55854. var rotMat = Bone._tmpMats[0];
  55855. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  55856. var rotMatInv = Bone._tmpMats[1];
  55857. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  55858. rotMatInv.multiplyToRef(rotMat, rotMat);
  55859. this._rotateWithMatrix(rotMat, space, mesh);
  55860. };
  55861. /**
  55862. * Rotate the bone on an axis in local or world space.
  55863. * @param axis The axis to rotate the bone on.
  55864. * @param amount The amount to rotate the bone.
  55865. * @param space The space that the axis is in.
  55866. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55867. */
  55868. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  55869. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55870. var rmat = Bone._tmpMats[0];
  55871. rmat.m[12] = 0;
  55872. rmat.m[13] = 0;
  55873. rmat.m[14] = 0;
  55874. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  55875. this._rotateWithMatrix(rmat, space, mesh);
  55876. };
  55877. /**
  55878. * Set the rotation of the bone to a particular axis angle in local or world space.
  55879. * @param axis The axis to rotate the bone on.
  55880. * @param angle The angle that the bone should be rotated to.
  55881. * @param space The space that the axis is in.
  55882. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55883. */
  55884. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  55885. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55886. var rotMat = Bone._tmpMats[0];
  55887. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  55888. var rotMatInv = Bone._tmpMats[1];
  55889. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  55890. rotMatInv.multiplyToRef(rotMat, rotMat);
  55891. this._rotateWithMatrix(rotMat, space, mesh);
  55892. };
  55893. /**
  55894. * Set the euler rotation of the bone in local of world space.
  55895. * @param rotation The euler rotation that the bone should be set to.
  55896. * @param space The space that the rotation is in.
  55897. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55898. */
  55899. Bone.prototype.setRotation = function (rotation, space, mesh) {
  55900. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55901. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  55902. };
  55903. /**
  55904. * Set the quaternion rotation of the bone in local of world space.
  55905. * @param quat The quaternion rotation that the bone should be set to.
  55906. * @param space The space that the rotation is in.
  55907. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55908. */
  55909. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  55910. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55911. var rotMatInv = Bone._tmpMats[0];
  55912. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  55913. var rotMat = Bone._tmpMats[1];
  55914. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  55915. rotMatInv.multiplyToRef(rotMat, rotMat);
  55916. this._rotateWithMatrix(rotMat, space, mesh);
  55917. };
  55918. /**
  55919. * Set the rotation matrix of the bone in local of world space.
  55920. * @param rotMat The rotation matrix that the bone should be set to.
  55921. * @param space The space that the rotation is in.
  55922. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55923. */
  55924. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  55925. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55926. var rotMatInv = Bone._tmpMats[0];
  55927. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  55928. var rotMat2 = Bone._tmpMats[1];
  55929. rotMat2.copyFrom(rotMat);
  55930. rotMatInv.multiplyToRef(rotMat, rotMat2);
  55931. this._rotateWithMatrix(rotMat2, space, mesh);
  55932. };
  55933. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  55934. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55935. var lmat = this.getLocalMatrix();
  55936. var lx = lmat.m[12];
  55937. var ly = lmat.m[13];
  55938. var lz = lmat.m[14];
  55939. var parent = this.getParent();
  55940. var parentScale = Bone._tmpMats[3];
  55941. var parentScaleInv = Bone._tmpMats[4];
  55942. if (parent) {
  55943. if (space == BABYLON.Space.WORLD) {
  55944. if (mesh) {
  55945. parentScale.copyFrom(mesh.getWorldMatrix());
  55946. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  55947. }
  55948. else {
  55949. parentScale.copyFrom(parent.getAbsoluteTransform());
  55950. }
  55951. }
  55952. else {
  55953. parentScale = parent._scaleMatrix;
  55954. }
  55955. parentScaleInv.copyFrom(parentScale);
  55956. parentScaleInv.invert();
  55957. lmat.multiplyToRef(parentScale, lmat);
  55958. lmat.multiplyToRef(rmat, lmat);
  55959. lmat.multiplyToRef(parentScaleInv, lmat);
  55960. }
  55961. else {
  55962. if (space == BABYLON.Space.WORLD && mesh) {
  55963. parentScale.copyFrom(mesh.getWorldMatrix());
  55964. parentScaleInv.copyFrom(parentScale);
  55965. parentScaleInv.invert();
  55966. lmat.multiplyToRef(parentScale, lmat);
  55967. lmat.multiplyToRef(rmat, lmat);
  55968. lmat.multiplyToRef(parentScaleInv, lmat);
  55969. }
  55970. else {
  55971. lmat.multiplyToRef(rmat, lmat);
  55972. }
  55973. }
  55974. lmat.m[12] = lx;
  55975. lmat.m[13] = ly;
  55976. lmat.m[14] = lz;
  55977. this.computeAbsoluteTransforms();
  55978. this.markAsDirty();
  55979. };
  55980. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  55981. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55982. if (space == BABYLON.Space.WORLD) {
  55983. var scaleMatrix = Bone._tmpMats[2];
  55984. scaleMatrix.copyFrom(this._scaleMatrix);
  55985. rotMatInv.copyFrom(this.getAbsoluteTransform());
  55986. if (mesh) {
  55987. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  55988. var meshScale = Bone._tmpMats[3];
  55989. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  55990. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  55991. }
  55992. rotMatInv.invert();
  55993. scaleMatrix.m[0] *= this._scalingDeterminant;
  55994. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  55995. }
  55996. else {
  55997. rotMatInv.copyFrom(this.getLocalMatrix());
  55998. rotMatInv.invert();
  55999. var scaleMatrix = Bone._tmpMats[2];
  56000. scaleMatrix.copyFrom(this._scaleMatrix);
  56001. if (this._parent) {
  56002. var pscaleMatrix = Bone._tmpMats[3];
  56003. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  56004. pscaleMatrix.invert();
  56005. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  56006. }
  56007. else {
  56008. scaleMatrix.m[0] *= this._scalingDeterminant;
  56009. }
  56010. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  56011. }
  56012. };
  56013. /**
  56014. * Get the scale of the bone
  56015. * @returns the scale of the bone
  56016. */
  56017. Bone.prototype.getScale = function () {
  56018. return this._scaleVector.clone();
  56019. };
  56020. /**
  56021. * Copy the scale of the bone to a vector3.
  56022. * @param result The vector3 to copy the scale to
  56023. */
  56024. Bone.prototype.getScaleToRef = function (result) {
  56025. result.copyFrom(this._scaleVector);
  56026. };
  56027. /**
  56028. * Get the position of the bone in local or world space.
  56029. * @param space The space that the returned position is in.
  56030. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56031. * @returns The position of the bone
  56032. */
  56033. Bone.prototype.getPosition = function (space, mesh) {
  56034. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56035. var pos = BABYLON.Vector3.Zero();
  56036. this.getPositionToRef(space, mesh, pos);
  56037. return pos;
  56038. };
  56039. /**
  56040. * Copy the position of the bone to a vector3 in local or world space.
  56041. * @param space The space that the returned position is in.
  56042. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56043. * @param result The vector3 to copy the position to.
  56044. */
  56045. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  56046. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56047. if (space == BABYLON.Space.LOCAL) {
  56048. var lm = this.getLocalMatrix();
  56049. result.x = lm.m[12];
  56050. result.y = lm.m[13];
  56051. result.z = lm.m[14];
  56052. }
  56053. else {
  56054. var wm;
  56055. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  56056. if (mesh) {
  56057. wm = mesh.getWorldMatrix();
  56058. }
  56059. this._skeleton.computeAbsoluteTransforms();
  56060. var tmat = Bone._tmpMats[0];
  56061. if (mesh) {
  56062. tmat.copyFrom(this.getAbsoluteTransform());
  56063. tmat.multiplyToRef(wm, tmat);
  56064. }
  56065. else {
  56066. tmat = this.getAbsoluteTransform();
  56067. }
  56068. result.x = tmat.m[12];
  56069. result.y = tmat.m[13];
  56070. result.z = tmat.m[14];
  56071. }
  56072. };
  56073. /**
  56074. * Get the absolute position of the bone (world space).
  56075. * @param mesh The mesh that this bone is attached to.
  56076. * @returns The absolute position of the bone
  56077. */
  56078. Bone.prototype.getAbsolutePosition = function (mesh) {
  56079. var pos = BABYLON.Vector3.Zero();
  56080. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  56081. return pos;
  56082. };
  56083. /**
  56084. * Copy the absolute position of the bone (world space) to the result param.
  56085. * @param mesh The mesh that this bone is attached to.
  56086. * @param result The vector3 to copy the absolute position to.
  56087. */
  56088. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  56089. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  56090. };
  56091. /**
  56092. * Compute the absolute transforms of this bone and its children.
  56093. */
  56094. Bone.prototype.computeAbsoluteTransforms = function () {
  56095. if (this._parent) {
  56096. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  56097. }
  56098. else {
  56099. this._absoluteTransform.copyFrom(this._localMatrix);
  56100. var poseMatrix = this._skeleton.getPoseMatrix();
  56101. if (poseMatrix) {
  56102. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  56103. }
  56104. }
  56105. var children = this.children;
  56106. var len = children.length;
  56107. for (var i = 0; i < len; i++) {
  56108. children[i].computeAbsoluteTransforms();
  56109. }
  56110. };
  56111. Bone.prototype._syncScaleVector = function () {
  56112. var lm = this.getLocalMatrix();
  56113. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  56114. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  56115. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  56116. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  56117. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  56118. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  56119. this._scaleVector.x = xs * Math.sqrt(xsq);
  56120. this._scaleVector.y = ys * Math.sqrt(ysq);
  56121. this._scaleVector.z = zs * Math.sqrt(zsq);
  56122. if (this._parent) {
  56123. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  56124. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  56125. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  56126. }
  56127. 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);
  56128. };
  56129. /**
  56130. * Get the world direction from an axis that is in the local space of the bone.
  56131. * @param localAxis The local direction that is used to compute the world direction.
  56132. * @param mesh The mesh that this bone is attached to.
  56133. * @returns The world direction
  56134. */
  56135. Bone.prototype.getDirection = function (localAxis, mesh) {
  56136. var result = BABYLON.Vector3.Zero();
  56137. this.getDirectionToRef(localAxis, mesh, result);
  56138. return result;
  56139. };
  56140. /**
  56141. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  56142. * @param localAxis The local direction that is used to compute the world direction.
  56143. * @param mesh The mesh that this bone is attached to.
  56144. * @param result The vector3 that the world direction will be copied to.
  56145. */
  56146. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  56147. var wm;
  56148. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  56149. if (mesh) {
  56150. wm = mesh.getWorldMatrix();
  56151. }
  56152. this._skeleton.computeAbsoluteTransforms();
  56153. var mat = Bone._tmpMats[0];
  56154. mat.copyFrom(this.getAbsoluteTransform());
  56155. if (mesh) {
  56156. mat.multiplyToRef(wm, mat);
  56157. }
  56158. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  56159. result.normalize();
  56160. };
  56161. /**
  56162. * Get the euler rotation of the bone in local or world space.
  56163. * @param space The space that the rotation should be in.
  56164. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56165. * @returns The euler rotation
  56166. */
  56167. Bone.prototype.getRotation = function (space, mesh) {
  56168. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56169. var result = BABYLON.Vector3.Zero();
  56170. this.getRotationToRef(space, mesh, result);
  56171. return result;
  56172. };
  56173. /**
  56174. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  56175. * @param space The space that the rotation should be in.
  56176. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56177. * @param result The vector3 that the rotation should be copied to.
  56178. */
  56179. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  56180. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56181. var quat = Bone._tmpQuat;
  56182. this.getRotationQuaternionToRef(space, mesh, quat);
  56183. quat.toEulerAnglesToRef(result);
  56184. };
  56185. /**
  56186. * Get the quaternion rotation of the bone in either local or world space.
  56187. * @param space The space that the rotation should be in.
  56188. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56189. * @returns The quaternion rotation
  56190. */
  56191. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  56192. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56193. var result = BABYLON.Quaternion.Identity();
  56194. this.getRotationQuaternionToRef(space, mesh, result);
  56195. return result;
  56196. };
  56197. /**
  56198. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  56199. * @param space The space that the rotation should be in.
  56200. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56201. * @param result The quaternion that the rotation should be copied to.
  56202. */
  56203. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  56204. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56205. if (space == BABYLON.Space.LOCAL) {
  56206. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  56207. }
  56208. else {
  56209. var mat = Bone._tmpMats[0];
  56210. var amat = this.getAbsoluteTransform();
  56211. if (mesh) {
  56212. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  56213. }
  56214. else {
  56215. mat.copyFrom(amat);
  56216. }
  56217. mat.m[0] *= this._scalingDeterminant;
  56218. mat.m[1] *= this._scalingDeterminant;
  56219. mat.m[2] *= this._scalingDeterminant;
  56220. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  56221. }
  56222. };
  56223. /**
  56224. * Get the rotation matrix of the bone in local or world space.
  56225. * @param space The space that the rotation should be in.
  56226. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56227. * @returns The rotation matrix
  56228. */
  56229. Bone.prototype.getRotationMatrix = function (space, mesh) {
  56230. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56231. var result = BABYLON.Matrix.Identity();
  56232. this.getRotationMatrixToRef(space, mesh, result);
  56233. return result;
  56234. };
  56235. /**
  56236. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  56237. * @param space The space that the rotation should be in.
  56238. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56239. * @param result The quaternion that the rotation should be copied to.
  56240. */
  56241. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  56242. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56243. if (space == BABYLON.Space.LOCAL) {
  56244. this.getLocalMatrix().getRotationMatrixToRef(result);
  56245. }
  56246. else {
  56247. var mat = Bone._tmpMats[0];
  56248. var amat = this.getAbsoluteTransform();
  56249. if (mesh) {
  56250. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  56251. }
  56252. else {
  56253. mat.copyFrom(amat);
  56254. }
  56255. mat.m[0] *= this._scalingDeterminant;
  56256. mat.m[1] *= this._scalingDeterminant;
  56257. mat.m[2] *= this._scalingDeterminant;
  56258. mat.getRotationMatrixToRef(result);
  56259. }
  56260. };
  56261. /**
  56262. * Get the world position of a point that is in the local space of the bone.
  56263. * @param position The local position
  56264. * @param mesh The mesh that this bone is attached to.
  56265. * @returns The world position
  56266. */
  56267. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  56268. var result = BABYLON.Vector3.Zero();
  56269. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  56270. return result;
  56271. };
  56272. /**
  56273. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  56274. * @param position The local position
  56275. * @param mesh The mesh that this bone is attached to.
  56276. * @param result The vector3 that the world position should be copied to.
  56277. */
  56278. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  56279. var wm;
  56280. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  56281. if (mesh) {
  56282. wm = mesh.getWorldMatrix();
  56283. }
  56284. this._skeleton.computeAbsoluteTransforms();
  56285. var tmat = Bone._tmpMats[0];
  56286. if (mesh) {
  56287. tmat.copyFrom(this.getAbsoluteTransform());
  56288. tmat.multiplyToRef(wm, tmat);
  56289. }
  56290. else {
  56291. tmat = this.getAbsoluteTransform();
  56292. }
  56293. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  56294. };
  56295. /**
  56296. * Get the local position of a point that is in world space.
  56297. * @param position The world position
  56298. * @param mesh The mesh that this bone is attached to.
  56299. * @returns The local position
  56300. */
  56301. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  56302. var result = BABYLON.Vector3.Zero();
  56303. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  56304. return result;
  56305. };
  56306. /**
  56307. * Get the local position of a point that is in world space and copy it to the result param.
  56308. * @param position The world position
  56309. * @param mesh The mesh that this bone is attached to.
  56310. * @param result The vector3 that the local position should be copied to.
  56311. */
  56312. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  56313. var wm;
  56314. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  56315. if (mesh) {
  56316. wm = mesh.getWorldMatrix();
  56317. }
  56318. this._skeleton.computeAbsoluteTransforms();
  56319. var tmat = Bone._tmpMats[0];
  56320. tmat.copyFrom(this.getAbsoluteTransform());
  56321. if (mesh) {
  56322. tmat.multiplyToRef(wm, tmat);
  56323. }
  56324. tmat.invert();
  56325. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  56326. };
  56327. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56328. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  56329. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  56330. return Bone;
  56331. }(BABYLON.Node));
  56332. BABYLON.Bone = Bone;
  56333. })(BABYLON || (BABYLON = {}));
  56334. //# sourceMappingURL=babylon.bone.js.map
  56335. var BABYLON;
  56336. (function (BABYLON) {
  56337. var BoneIKController = (function () {
  56338. function BoneIKController(mesh, bone, options) {
  56339. this.targetPosition = BABYLON.Vector3.Zero();
  56340. this.poleTargetPosition = BABYLON.Vector3.Zero();
  56341. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  56342. this.poleAngle = 0;
  56343. this.slerpAmount = 1;
  56344. this._bone1Quat = BABYLON.Quaternion.Identity();
  56345. this._bone1Mat = BABYLON.Matrix.Identity();
  56346. this._bone2Ang = Math.PI;
  56347. this._maxAngle = Math.PI;
  56348. this._rightHandedSystem = false;
  56349. this._bendAxis = BABYLON.Vector3.Right();
  56350. this._slerping = false;
  56351. this._adjustRoll = 0;
  56352. this._bone2 = bone;
  56353. this._bone1 = bone.getParent();
  56354. this.mesh = mesh;
  56355. var bonePos = bone.getPosition();
  56356. if (bone.getAbsoluteTransform().determinant() > 0) {
  56357. this._rightHandedSystem = true;
  56358. this._bendAxis.x = 0;
  56359. this._bendAxis.y = 0;
  56360. this._bendAxis.z = -1;
  56361. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  56362. this._adjustRoll = Math.PI * .5;
  56363. this._bendAxis.z = 1;
  56364. }
  56365. }
  56366. if (this._bone1.length) {
  56367. var boneScale1 = this._bone1.getScale();
  56368. var boneScale2 = this._bone2.getScale();
  56369. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  56370. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  56371. }
  56372. else if (this._bone1.children[0]) {
  56373. mesh.computeWorldMatrix(true);
  56374. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  56375. var pos2 = this._bone2.getAbsolutePosition(mesh);
  56376. var pos3 = this._bone1.getAbsolutePosition(mesh);
  56377. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  56378. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  56379. }
  56380. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  56381. this.maxAngle = Math.PI;
  56382. if (options) {
  56383. if (options.targetMesh) {
  56384. this.targetMesh = options.targetMesh;
  56385. this.targetMesh.computeWorldMatrix(true);
  56386. }
  56387. if (options.poleTargetMesh) {
  56388. this.poleTargetMesh = options.poleTargetMesh;
  56389. this.poleTargetMesh.computeWorldMatrix(true);
  56390. }
  56391. else if (options.poleTargetBone) {
  56392. this.poleTargetBone = options.poleTargetBone;
  56393. }
  56394. else if (this._bone1.getParent()) {
  56395. this.poleTargetBone = this._bone1.getParent();
  56396. }
  56397. if (options.poleTargetLocalOffset) {
  56398. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  56399. }
  56400. if (options.poleAngle) {
  56401. this.poleAngle = options.poleAngle;
  56402. }
  56403. if (options.bendAxis) {
  56404. this._bendAxis.copyFrom(options.bendAxis);
  56405. }
  56406. if (options.maxAngle) {
  56407. this.maxAngle = options.maxAngle;
  56408. }
  56409. if (options.slerpAmount) {
  56410. this.slerpAmount = options.slerpAmount;
  56411. }
  56412. }
  56413. }
  56414. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  56415. get: function () {
  56416. return this._maxAngle;
  56417. },
  56418. set: function (value) {
  56419. this._setMaxAngle(value);
  56420. },
  56421. enumerable: true,
  56422. configurable: true
  56423. });
  56424. BoneIKController.prototype._setMaxAngle = function (ang) {
  56425. if (ang < 0) {
  56426. ang = 0;
  56427. }
  56428. if (ang > Math.PI || ang == undefined) {
  56429. ang = Math.PI;
  56430. }
  56431. this._maxAngle = ang;
  56432. var a = this._bone1Length;
  56433. var b = this._bone2Length;
  56434. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  56435. };
  56436. BoneIKController.prototype.update = function () {
  56437. var bone1 = this._bone1;
  56438. var target = this.targetPosition;
  56439. var poleTarget = this.poleTargetPosition;
  56440. var mat1 = BoneIKController._tmpMats[0];
  56441. var mat2 = BoneIKController._tmpMats[1];
  56442. if (this.targetMesh) {
  56443. target.copyFrom(this.targetMesh.getAbsolutePosition());
  56444. }
  56445. if (this.poleTargetBone) {
  56446. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  56447. }
  56448. else if (this.poleTargetMesh) {
  56449. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  56450. }
  56451. var bonePos = BoneIKController._tmpVecs[0];
  56452. var zaxis = BoneIKController._tmpVecs[1];
  56453. var xaxis = BoneIKController._tmpVecs[2];
  56454. var yaxis = BoneIKController._tmpVecs[3];
  56455. var upAxis = BoneIKController._tmpVecs[4];
  56456. var _tmpQuat = BoneIKController._tmpQuat;
  56457. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  56458. poleTarget.subtractToRef(bonePos, upAxis);
  56459. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  56460. upAxis.y = 1;
  56461. }
  56462. else {
  56463. upAxis.normalize();
  56464. }
  56465. target.subtractToRef(bonePos, yaxis);
  56466. yaxis.normalize();
  56467. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  56468. zaxis.normalize();
  56469. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  56470. xaxis.normalize();
  56471. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  56472. var a = this._bone1Length;
  56473. var b = this._bone2Length;
  56474. var c = BABYLON.Vector3.Distance(bonePos, target);
  56475. if (this._maxReach > 0) {
  56476. c = Math.min(this._maxReach, c);
  56477. }
  56478. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  56479. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  56480. if (acosa > 1) {
  56481. acosa = 1;
  56482. }
  56483. if (acosb > 1) {
  56484. acosb = 1;
  56485. }
  56486. if (acosa < -1) {
  56487. acosa = -1;
  56488. }
  56489. if (acosb < -1) {
  56490. acosb = -1;
  56491. }
  56492. var angA = Math.acos(acosa);
  56493. var angB = Math.acos(acosb);
  56494. var angC = -angA - angB;
  56495. if (this._rightHandedSystem) {
  56496. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  56497. mat2.multiplyToRef(mat1, mat1);
  56498. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  56499. mat2.multiplyToRef(mat1, mat1);
  56500. }
  56501. else {
  56502. var _tmpVec = BoneIKController._tmpVecs[5];
  56503. _tmpVec.copyFrom(this._bendAxis);
  56504. _tmpVec.x *= -1;
  56505. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  56506. mat2.multiplyToRef(mat1, mat1);
  56507. }
  56508. if (this.poleAngle) {
  56509. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  56510. mat1.multiplyToRef(mat2, mat1);
  56511. }
  56512. if (this.slerpAmount < 1) {
  56513. if (!this._slerping) {
  56514. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  56515. }
  56516. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  56517. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  56518. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  56519. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  56520. this._slerping = true;
  56521. }
  56522. else {
  56523. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  56524. this._bone1Mat.copyFrom(mat1);
  56525. this._slerping = false;
  56526. }
  56527. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  56528. this._bone2Ang = angC;
  56529. };
  56530. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56531. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  56532. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  56533. return BoneIKController;
  56534. }());
  56535. BABYLON.BoneIKController = BoneIKController;
  56536. })(BABYLON || (BABYLON = {}));
  56537. //# sourceMappingURL=babylon.boneIKController.js.map
  56538. var BABYLON;
  56539. (function (BABYLON) {
  56540. var BoneLookController = (function () {
  56541. /**
  56542. * Create a BoneLookController
  56543. * @param mesh the mesh that the bone belongs to
  56544. * @param bone the bone that will be looking to the target
  56545. * @param target the target Vector3 to look at
  56546. * @param settings optional settings:
  56547. * - maxYaw: the maximum angle the bone will yaw to
  56548. * - minYaw: the minimum angle the bone will yaw to
  56549. * - maxPitch: the maximum angle the bone will pitch to
  56550. * - minPitch: the minimum angle the bone will yaw to
  56551. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  56552. * - upAxis: the up axis of the coordinate system
  56553. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  56554. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  56555. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  56556. * - adjustYaw: used to make an adjustment to the yaw of the bone
  56557. * - adjustPitch: used to make an adjustment to the pitch of the bone
  56558. * - adjustRoll: used to make an adjustment to the roll of the bone
  56559. **/
  56560. function BoneLookController(mesh, bone, target, options) {
  56561. /**
  56562. * The up axis of the coordinate system that is used when the bone is rotated.
  56563. */
  56564. this.upAxis = BABYLON.Vector3.Up();
  56565. /**
  56566. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  56567. */
  56568. this.upAxisSpace = BABYLON.Space.LOCAL;
  56569. /**
  56570. * Used to make an adjustment to the yaw of the bone.
  56571. */
  56572. this.adjustYaw = 0;
  56573. /**
  56574. * Used to make an adjustment to the pitch of the bone.
  56575. */
  56576. this.adjustPitch = 0;
  56577. /**
  56578. * Used to make an adjustment to the roll of the bone.
  56579. */
  56580. this.adjustRoll = 0;
  56581. /**
  56582. * 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).
  56583. */
  56584. this.slerpAmount = 1;
  56585. this._boneQuat = BABYLON.Quaternion.Identity();
  56586. this._slerping = false;
  56587. this._firstFrameSkipped = false;
  56588. this._fowardAxis = BABYLON.Vector3.Forward();
  56589. this.mesh = mesh;
  56590. this.bone = bone;
  56591. this.target = target;
  56592. if (options) {
  56593. if (options.adjustYaw) {
  56594. this.adjustYaw = options.adjustYaw;
  56595. }
  56596. if (options.adjustPitch) {
  56597. this.adjustPitch = options.adjustPitch;
  56598. }
  56599. if (options.adjustRoll) {
  56600. this.adjustRoll = options.adjustRoll;
  56601. }
  56602. if (options.maxYaw != null) {
  56603. this.maxYaw = options.maxYaw;
  56604. }
  56605. else {
  56606. this.maxYaw = Math.PI;
  56607. }
  56608. if (options.minYaw != null) {
  56609. this.minYaw = options.minYaw;
  56610. }
  56611. else {
  56612. this.minYaw = -Math.PI;
  56613. }
  56614. if (options.maxPitch != null) {
  56615. this.maxPitch = options.maxPitch;
  56616. }
  56617. else {
  56618. this.maxPitch = Math.PI;
  56619. }
  56620. if (options.minPitch != null) {
  56621. this.minPitch = options.minPitch;
  56622. }
  56623. else {
  56624. this.minPitch = -Math.PI;
  56625. }
  56626. if (options.slerpAmount != null) {
  56627. this.slerpAmount = options.slerpAmount;
  56628. }
  56629. if (options.upAxis != null) {
  56630. this.upAxis = options.upAxis;
  56631. }
  56632. if (options.upAxisSpace != null) {
  56633. this.upAxisSpace = options.upAxisSpace;
  56634. }
  56635. if (options.yawAxis != null || options.pitchAxis != null) {
  56636. var newYawAxis = BABYLON.Axis.Y;
  56637. var newPitchAxis = BABYLON.Axis.X;
  56638. if (options.yawAxis != null) {
  56639. newYawAxis = options.yawAxis.clone();
  56640. newYawAxis.normalize();
  56641. }
  56642. if (options.pitchAxis != null) {
  56643. newPitchAxis = options.pitchAxis.clone();
  56644. newPitchAxis.normalize();
  56645. }
  56646. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  56647. this._transformYawPitch = BABYLON.Matrix.Identity();
  56648. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  56649. this._transformYawPitchInv = this._transformYawPitch.clone();
  56650. this._transformYawPitch.invert();
  56651. }
  56652. }
  56653. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  56654. this.upAxisSpace = BABYLON.Space.LOCAL;
  56655. }
  56656. }
  56657. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  56658. /**
  56659. * Get/set the minimum yaw angle that the bone can look to.
  56660. */
  56661. get: function () {
  56662. return this._minYaw;
  56663. },
  56664. set: function (value) {
  56665. this._minYaw = value;
  56666. this._minYawSin = Math.sin(value);
  56667. this._minYawCos = Math.cos(value);
  56668. if (this._maxYaw != null) {
  56669. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  56670. this._yawRange = this._maxYaw - this._minYaw;
  56671. }
  56672. },
  56673. enumerable: true,
  56674. configurable: true
  56675. });
  56676. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  56677. /**
  56678. * Get/set the maximum yaw angle that the bone can look to.
  56679. */
  56680. get: function () {
  56681. return this._maxYaw;
  56682. },
  56683. set: function (value) {
  56684. this._maxYaw = value;
  56685. this._maxYawSin = Math.sin(value);
  56686. this._maxYawCos = Math.cos(value);
  56687. if (this._minYaw != null) {
  56688. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  56689. this._yawRange = this._maxYaw - this._minYaw;
  56690. }
  56691. },
  56692. enumerable: true,
  56693. configurable: true
  56694. });
  56695. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  56696. /**
  56697. * Get/set the minimum pitch angle that the bone can look to.
  56698. */
  56699. get: function () {
  56700. return this._minPitch;
  56701. },
  56702. set: function (value) {
  56703. this._minPitch = value;
  56704. this._minPitchTan = Math.tan(value);
  56705. },
  56706. enumerable: true,
  56707. configurable: true
  56708. });
  56709. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  56710. /**
  56711. * Get/set the maximum pitch angle that the bone can look to.
  56712. */
  56713. get: function () {
  56714. return this._maxPitch;
  56715. },
  56716. set: function (value) {
  56717. this._maxPitch = value;
  56718. this._maxPitchTan = Math.tan(value);
  56719. },
  56720. enumerable: true,
  56721. configurable: true
  56722. });
  56723. /**
  56724. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  56725. */
  56726. BoneLookController.prototype.update = function () {
  56727. //skip the first frame when slerping so that the mesh rotation is correct
  56728. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  56729. this._firstFrameSkipped = true;
  56730. return;
  56731. }
  56732. var bone = this.bone;
  56733. var bonePos = BoneLookController._tmpVecs[0];
  56734. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  56735. var target = this.target;
  56736. var _tmpMat1 = BoneLookController._tmpMats[0];
  56737. var _tmpMat2 = BoneLookController._tmpMats[1];
  56738. var mesh = this.mesh;
  56739. var parentBone = bone.getParent();
  56740. var upAxis = BoneLookController._tmpVecs[1];
  56741. upAxis.copyFrom(this.upAxis);
  56742. if (this.upAxisSpace == BABYLON.Space.BONE) {
  56743. if (this._transformYawPitch) {
  56744. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  56745. }
  56746. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  56747. }
  56748. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  56749. mesh.getDirectionToRef(upAxis, upAxis);
  56750. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  56751. upAxis.normalize();
  56752. }
  56753. }
  56754. var checkYaw = false;
  56755. var checkPitch = false;
  56756. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  56757. checkYaw = true;
  56758. }
  56759. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  56760. checkPitch = true;
  56761. }
  56762. if (checkYaw || checkPitch) {
  56763. var spaceMat = BoneLookController._tmpMats[2];
  56764. var spaceMatInv = BoneLookController._tmpMats[3];
  56765. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1) {
  56766. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  56767. }
  56768. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  56769. spaceMat.copyFrom(mesh.getWorldMatrix());
  56770. }
  56771. else {
  56772. var forwardAxis = BoneLookController._tmpVecs[2];
  56773. forwardAxis.copyFrom(this._fowardAxis);
  56774. if (this._transformYawPitch) {
  56775. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  56776. }
  56777. if (parentBone) {
  56778. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  56779. }
  56780. else {
  56781. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  56782. }
  56783. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  56784. rightAxis.normalize();
  56785. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  56786. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  56787. }
  56788. spaceMat.invertToRef(spaceMatInv);
  56789. var xzlen;
  56790. if (checkPitch) {
  56791. var localTarget = BoneLookController._tmpVecs[3];
  56792. target.subtractToRef(bonePos, localTarget);
  56793. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  56794. var xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  56795. var pitch = Math.atan2(localTarget.y, xzlen);
  56796. var newPitch = pitch;
  56797. if (pitch > this._maxPitch) {
  56798. localTarget.y = this._maxPitchTan * xzlen;
  56799. newPitch = this._maxPitch;
  56800. }
  56801. else if (pitch < this._minPitch) {
  56802. localTarget.y = this._minPitchTan * xzlen;
  56803. newPitch = this._minPitch;
  56804. }
  56805. if (pitch != newPitch) {
  56806. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  56807. localTarget.addInPlace(bonePos);
  56808. target = localTarget;
  56809. }
  56810. }
  56811. if (checkYaw) {
  56812. var localTarget = BoneLookController._tmpVecs[4];
  56813. target.subtractToRef(bonePos, localTarget);
  56814. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  56815. var yaw = Math.atan2(localTarget.x, localTarget.z);
  56816. var newYaw = yaw;
  56817. if (yaw > this._maxYaw || yaw < this._minYaw) {
  56818. if (xzlen == null) {
  56819. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  56820. }
  56821. if (this._yawRange > Math.PI) {
  56822. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  56823. localTarget.z = this._maxYawCos * xzlen;
  56824. localTarget.x = this._maxYawSin * xzlen;
  56825. newYaw = this._maxYaw;
  56826. }
  56827. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  56828. localTarget.z = this._minYawCos * xzlen;
  56829. localTarget.x = this._minYawSin * xzlen;
  56830. newYaw = this._minYaw;
  56831. }
  56832. }
  56833. else {
  56834. if (yaw > this._maxYaw) {
  56835. localTarget.z = this._maxYawCos * xzlen;
  56836. localTarget.x = this._maxYawSin * xzlen;
  56837. newYaw = this._maxYaw;
  56838. }
  56839. else if (yaw < this._minYaw) {
  56840. localTarget.z = this._minYawCos * xzlen;
  56841. localTarget.x = this._minYawSin * xzlen;
  56842. newYaw = this._minYaw;
  56843. }
  56844. }
  56845. }
  56846. if (this._slerping && this._yawRange > Math.PI) {
  56847. //are we going to be crossing into the min/max region?
  56848. var boneFwd = BoneLookController._tmpVecs[8];
  56849. boneFwd.copyFrom(BABYLON.Axis.Z);
  56850. if (this._transformYawPitch) {
  56851. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  56852. }
  56853. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  56854. this._boneQuat.toRotationMatrix(boneRotMat);
  56855. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  56856. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  56857. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  56858. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  56859. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  56860. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  56861. if (angBtwTar > angBtwMidYaw) {
  56862. if (xzlen == null) {
  56863. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  56864. }
  56865. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  56866. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  56867. if (angBtwMin < angBtwMax) {
  56868. newYaw = boneYaw + Math.PI * .75;
  56869. localTarget.z = Math.cos(newYaw) * xzlen;
  56870. localTarget.x = Math.sin(newYaw) * xzlen;
  56871. }
  56872. else {
  56873. newYaw = boneYaw - Math.PI * .75;
  56874. localTarget.z = Math.cos(newYaw) * xzlen;
  56875. localTarget.x = Math.sin(newYaw) * xzlen;
  56876. }
  56877. }
  56878. }
  56879. if (yaw != newYaw) {
  56880. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  56881. localTarget.addInPlace(bonePos);
  56882. target = localTarget;
  56883. }
  56884. }
  56885. }
  56886. var zaxis = BoneLookController._tmpVecs[5];
  56887. var xaxis = BoneLookController._tmpVecs[6];
  56888. var yaxis = BoneLookController._tmpVecs[7];
  56889. var _tmpQuat = BoneLookController._tmpQuat;
  56890. target.subtractToRef(bonePos, zaxis);
  56891. zaxis.normalize();
  56892. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  56893. xaxis.normalize();
  56894. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  56895. yaxis.normalize();
  56896. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  56897. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  56898. return;
  56899. }
  56900. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  56901. return;
  56902. }
  56903. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  56904. return;
  56905. }
  56906. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  56907. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  56908. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  56909. }
  56910. if (this.slerpAmount < 1) {
  56911. if (!this._slerping) {
  56912. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  56913. }
  56914. if (this._transformYawPitch) {
  56915. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  56916. }
  56917. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  56918. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  56919. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  56920. this._slerping = true;
  56921. }
  56922. else {
  56923. if (this._transformYawPitch) {
  56924. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  56925. }
  56926. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  56927. this._slerping = false;
  56928. }
  56929. };
  56930. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  56931. var angDiff = ang2 - ang1;
  56932. angDiff %= Math.PI * 2;
  56933. if (angDiff > Math.PI) {
  56934. angDiff -= Math.PI * 2;
  56935. }
  56936. else if (angDiff < -Math.PI) {
  56937. angDiff += Math.PI * 2;
  56938. }
  56939. return angDiff;
  56940. };
  56941. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  56942. ang1 %= (2 * Math.PI);
  56943. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  56944. ang2 %= (2 * Math.PI);
  56945. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  56946. var ab = 0;
  56947. if (ang1 < ang2) {
  56948. ab = ang2 - ang1;
  56949. }
  56950. else {
  56951. ab = ang1 - ang2;
  56952. }
  56953. if (ab > Math.PI) {
  56954. ab = Math.PI * 2 - ab;
  56955. }
  56956. return ab;
  56957. };
  56958. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  56959. ang %= (2 * Math.PI);
  56960. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  56961. ang1 %= (2 * Math.PI);
  56962. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  56963. ang2 %= (2 * Math.PI);
  56964. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  56965. if (ang1 < ang2) {
  56966. if (ang > ang1 && ang < ang2) {
  56967. return true;
  56968. }
  56969. }
  56970. else {
  56971. if (ang > ang2 && ang < ang1) {
  56972. return true;
  56973. }
  56974. }
  56975. return false;
  56976. };
  56977. 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()];
  56978. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  56979. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  56980. return BoneLookController;
  56981. }());
  56982. BABYLON.BoneLookController = BoneLookController;
  56983. })(BABYLON || (BABYLON = {}));
  56984. //# sourceMappingURL=babylon.boneLookController.js.map
  56985. var BABYLON;
  56986. (function (BABYLON) {
  56987. var Skeleton = (function () {
  56988. function Skeleton(name, id, scene) {
  56989. this.name = name;
  56990. this.id = id;
  56991. this.bones = new Array();
  56992. this.needInitialSkinMatrix = false;
  56993. this._isDirty = true;
  56994. this._meshesWithPoseMatrix = new Array();
  56995. this._identity = BABYLON.Matrix.Identity();
  56996. this._ranges = {};
  56997. this._lastAbsoluteTransformsUpdateId = -1;
  56998. // Events
  56999. /**
  57000. * An event triggered before computing the skeleton's matrices
  57001. * @type {BABYLON.Observable}
  57002. */
  57003. this.onBeforeComputeObservable = new BABYLON.Observable();
  57004. this.bones = [];
  57005. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57006. scene.skeletons.push(this);
  57007. //make sure it will recalculate the matrix next time prepare is called.
  57008. this._isDirty = true;
  57009. }
  57010. // Members
  57011. Skeleton.prototype.getTransformMatrices = function (mesh) {
  57012. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  57013. return mesh._bonesTransformMatrices;
  57014. }
  57015. if (!this._transformMatrices) {
  57016. this.prepare();
  57017. }
  57018. return this._transformMatrices;
  57019. };
  57020. Skeleton.prototype.getScene = function () {
  57021. return this._scene;
  57022. };
  57023. // Methods
  57024. /**
  57025. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  57026. */
  57027. Skeleton.prototype.toString = function (fullDetails) {
  57028. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  57029. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  57030. if (fullDetails) {
  57031. ret += ", Ranges: {";
  57032. var first = true;
  57033. for (var name_1 in this._ranges) {
  57034. if (first) {
  57035. ret += ", ";
  57036. first = false;
  57037. }
  57038. ret += name_1;
  57039. }
  57040. ret += "}";
  57041. }
  57042. return ret;
  57043. };
  57044. /**
  57045. * Get bone's index searching by name
  57046. * @param {string} name is bone's name to search for
  57047. * @return {number} Indice of the bone. Returns -1 if not found
  57048. */
  57049. Skeleton.prototype.getBoneIndexByName = function (name) {
  57050. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  57051. if (this.bones[boneIndex].name === name) {
  57052. return boneIndex;
  57053. }
  57054. }
  57055. return -1;
  57056. };
  57057. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  57058. // check name not already in use
  57059. if (!this._ranges[name]) {
  57060. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  57061. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  57062. if (this.bones[i].animations[0]) {
  57063. this.bones[i].animations[0].createRange(name, from, to);
  57064. }
  57065. }
  57066. }
  57067. };
  57068. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  57069. if (deleteFrames === void 0) { deleteFrames = true; }
  57070. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  57071. if (this.bones[i].animations[0]) {
  57072. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  57073. }
  57074. }
  57075. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  57076. };
  57077. Skeleton.prototype.getAnimationRange = function (name) {
  57078. return this._ranges[name];
  57079. };
  57080. /**
  57081. * Returns as an Array, all AnimationRanges defined on this skeleton
  57082. */
  57083. Skeleton.prototype.getAnimationRanges = function () {
  57084. var animationRanges = [];
  57085. var name;
  57086. var i = 0;
  57087. for (name in this._ranges) {
  57088. animationRanges[i] = this._ranges[name];
  57089. i++;
  57090. }
  57091. return animationRanges;
  57092. };
  57093. /**
  57094. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  57095. */
  57096. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  57097. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  57098. if (this._ranges[name] || !source.getAnimationRange(name)) {
  57099. return false;
  57100. }
  57101. var ret = true;
  57102. var frameOffset = this._getHighestAnimationFrame() + 1;
  57103. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  57104. var boneDict = {};
  57105. var sourceBones = source.bones;
  57106. var nBones;
  57107. var i;
  57108. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  57109. boneDict[sourceBones[i].name] = sourceBones[i];
  57110. }
  57111. if (this.bones.length !== sourceBones.length) {
  57112. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  57113. ret = false;
  57114. }
  57115. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  57116. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  57117. var boneName = this.bones[i].name;
  57118. var sourceBone = boneDict[boneName];
  57119. if (sourceBone) {
  57120. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  57121. }
  57122. else {
  57123. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  57124. ret = false;
  57125. }
  57126. }
  57127. // do not call createAnimationRange(), since it also is done to bones, which was already done
  57128. var range = source.getAnimationRange(name);
  57129. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  57130. return ret;
  57131. };
  57132. Skeleton.prototype.returnToRest = function () {
  57133. for (var index = 0; index < this.bones.length; index++) {
  57134. this.bones[index].returnToRest();
  57135. }
  57136. };
  57137. Skeleton.prototype._getHighestAnimationFrame = function () {
  57138. var ret = 0;
  57139. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  57140. if (this.bones[i].animations[0]) {
  57141. var highest = this.bones[i].animations[0].getHighestFrame();
  57142. if (ret < highest) {
  57143. ret = highest;
  57144. }
  57145. }
  57146. }
  57147. return ret;
  57148. };
  57149. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  57150. var range = this.getAnimationRange(name);
  57151. if (!range) {
  57152. return null;
  57153. }
  57154. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  57155. };
  57156. Skeleton.prototype._markAsDirty = function () {
  57157. this._isDirty = true;
  57158. };
  57159. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  57160. this._meshesWithPoseMatrix.push(mesh);
  57161. };
  57162. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  57163. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  57164. if (index > -1) {
  57165. this._meshesWithPoseMatrix.splice(index, 1);
  57166. }
  57167. };
  57168. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  57169. this.onBeforeComputeObservable.notifyObservers(this);
  57170. for (var index = 0; index < this.bones.length; index++) {
  57171. var bone = this.bones[index];
  57172. var parentBone = bone.getParent();
  57173. if (parentBone) {
  57174. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  57175. }
  57176. else {
  57177. if (initialSkinMatrix) {
  57178. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  57179. }
  57180. else {
  57181. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  57182. }
  57183. }
  57184. if (bone._index !== -1) {
  57185. var mappedIndex = bone._index === undefined ? index : bone._index;
  57186. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  57187. }
  57188. }
  57189. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  57190. };
  57191. Skeleton.prototype.prepare = function () {
  57192. if (!this._isDirty) {
  57193. return;
  57194. }
  57195. if (this.needInitialSkinMatrix) {
  57196. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  57197. var mesh = this._meshesWithPoseMatrix[index];
  57198. var poseMatrix = mesh.getPoseMatrix();
  57199. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  57200. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  57201. }
  57202. if (this._synchronizedWithMesh !== mesh) {
  57203. this._synchronizedWithMesh = mesh;
  57204. // Prepare bones
  57205. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  57206. var bone = this.bones[boneIndex];
  57207. if (!bone.getParent()) {
  57208. var matrix = bone.getBaseMatrix();
  57209. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  57210. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  57211. }
  57212. }
  57213. }
  57214. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  57215. }
  57216. }
  57217. else {
  57218. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  57219. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  57220. }
  57221. this._computeTransformMatrices(this._transformMatrices, null);
  57222. }
  57223. this._isDirty = false;
  57224. this._scene._activeBones.addCount(this.bones.length, false);
  57225. };
  57226. Skeleton.prototype.getAnimatables = function () {
  57227. if (!this._animatables || this._animatables.length !== this.bones.length) {
  57228. this._animatables = [];
  57229. for (var index = 0; index < this.bones.length; index++) {
  57230. this._animatables.push(this.bones[index]);
  57231. }
  57232. }
  57233. return this._animatables;
  57234. };
  57235. Skeleton.prototype.clone = function (name, id) {
  57236. var result = new Skeleton(name, id || name, this._scene);
  57237. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  57238. for (var index = 0; index < this.bones.length; index++) {
  57239. var source = this.bones[index];
  57240. var parentBone = null;
  57241. if (source.getParent()) {
  57242. var parentIndex = this.bones.indexOf(source.getParent());
  57243. parentBone = result.bones[parentIndex];
  57244. }
  57245. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  57246. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  57247. }
  57248. if (this._ranges) {
  57249. result._ranges = {};
  57250. for (var rangeName in this._ranges) {
  57251. result._ranges[rangeName] = this._ranges[rangeName].clone();
  57252. }
  57253. }
  57254. this._isDirty = true;
  57255. return result;
  57256. };
  57257. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  57258. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  57259. this.bones.forEach(function (bone) {
  57260. bone.animations.forEach(function (animation) {
  57261. animation.enableBlending = true;
  57262. animation.blendingSpeed = blendingSpeed;
  57263. });
  57264. });
  57265. };
  57266. Skeleton.prototype.dispose = function () {
  57267. this._meshesWithPoseMatrix = [];
  57268. // Animations
  57269. this.getScene().stopAnimation(this);
  57270. // Remove from scene
  57271. this.getScene().removeSkeleton(this);
  57272. };
  57273. Skeleton.prototype.serialize = function () {
  57274. var serializationObject = {};
  57275. serializationObject.name = this.name;
  57276. serializationObject.id = this.id;
  57277. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  57278. serializationObject.bones = [];
  57279. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  57280. for (var index = 0; index < this.bones.length; index++) {
  57281. var bone = this.bones[index];
  57282. var serializedBone = {
  57283. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  57284. name: bone.name,
  57285. matrix: bone.getBaseMatrix().toArray(),
  57286. rest: bone.getRestPose().toArray()
  57287. };
  57288. serializationObject.bones.push(serializedBone);
  57289. if (bone.length) {
  57290. serializedBone.length = bone.length;
  57291. }
  57292. if (bone.animations && bone.animations.length > 0) {
  57293. serializedBone.animation = bone.animations[0].serialize();
  57294. }
  57295. serializationObject.ranges = [];
  57296. for (var name in this._ranges) {
  57297. var range = {};
  57298. range.name = name;
  57299. range.from = this._ranges[name].from;
  57300. range.to = this._ranges[name].to;
  57301. serializationObject.ranges.push(range);
  57302. }
  57303. }
  57304. return serializationObject;
  57305. };
  57306. Skeleton.Parse = function (parsedSkeleton, scene) {
  57307. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  57308. if (parsedSkeleton.dimensionsAtRest) {
  57309. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  57310. }
  57311. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  57312. var index;
  57313. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  57314. var parsedBone = parsedSkeleton.bones[index];
  57315. var parentBone = null;
  57316. if (parsedBone.parentBoneIndex > -1) {
  57317. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  57318. }
  57319. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  57320. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  57321. if (parsedBone.length) {
  57322. bone.length = parsedBone.length;
  57323. }
  57324. if (parsedBone.animation) {
  57325. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  57326. }
  57327. }
  57328. // placed after bones, so createAnimationRange can cascade down
  57329. if (parsedSkeleton.ranges) {
  57330. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  57331. var data = parsedSkeleton.ranges[index];
  57332. skeleton.createAnimationRange(data.name, data.from, data.to);
  57333. }
  57334. }
  57335. return skeleton;
  57336. };
  57337. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  57338. if (forceUpdate === void 0) { forceUpdate = false; }
  57339. var renderId = this._scene.getRenderId();
  57340. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  57341. this.bones[0].computeAbsoluteTransforms();
  57342. this._lastAbsoluteTransformsUpdateId = renderId;
  57343. }
  57344. };
  57345. Skeleton.prototype.getPoseMatrix = function () {
  57346. var poseMatrix;
  57347. if (this._meshesWithPoseMatrix.length > 0) {
  57348. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  57349. }
  57350. return poseMatrix;
  57351. };
  57352. Skeleton.prototype.sortBones = function () {
  57353. var bones = new Array();
  57354. var visited = new Array(this.bones.length);
  57355. for (var index = 0; index < this.bones.length; index++) {
  57356. this._sortBones(index, bones, visited);
  57357. }
  57358. this.bones = bones;
  57359. };
  57360. Skeleton.prototype._sortBones = function (index, bones, visited) {
  57361. if (visited[index]) {
  57362. return;
  57363. }
  57364. visited[index] = true;
  57365. var bone = this.bones[index];
  57366. if (bone._index === undefined) {
  57367. bone._index = index;
  57368. }
  57369. var parentBone = bone.getParent();
  57370. if (parentBone) {
  57371. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  57372. }
  57373. bones.push(bone);
  57374. };
  57375. return Skeleton;
  57376. }());
  57377. BABYLON.Skeleton = Skeleton;
  57378. })(BABYLON || (BABYLON = {}));
  57379. //# sourceMappingURL=babylon.skeleton.js.map
  57380. var BABYLON;
  57381. (function (BABYLON) {
  57382. var SphericalPolynomial = (function () {
  57383. function SphericalPolynomial() {
  57384. this.x = BABYLON.Vector3.Zero();
  57385. this.y = BABYLON.Vector3.Zero();
  57386. this.z = BABYLON.Vector3.Zero();
  57387. this.xx = BABYLON.Vector3.Zero();
  57388. this.yy = BABYLON.Vector3.Zero();
  57389. this.zz = BABYLON.Vector3.Zero();
  57390. this.xy = BABYLON.Vector3.Zero();
  57391. this.yz = BABYLON.Vector3.Zero();
  57392. this.zx = BABYLON.Vector3.Zero();
  57393. }
  57394. SphericalPolynomial.prototype.addAmbient = function (color) {
  57395. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  57396. this.xx = this.xx.add(colorVector);
  57397. this.yy = this.yy.add(colorVector);
  57398. this.zz = this.zz.add(colorVector);
  57399. };
  57400. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  57401. var result = new SphericalPolynomial();
  57402. result.x = harmonics.L11.scale(1.02333);
  57403. result.y = harmonics.L1_1.scale(1.02333);
  57404. result.z = harmonics.L10.scale(1.02333);
  57405. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  57406. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  57407. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  57408. result.yz = harmonics.L2_1.scale(0.858086);
  57409. result.zx = harmonics.L21.scale(0.858086);
  57410. result.xy = harmonics.L2_2.scale(0.858086);
  57411. result.scale(1.0 / Math.PI);
  57412. return result;
  57413. };
  57414. SphericalPolynomial.prototype.scale = function (scale) {
  57415. this.x = this.x.scale(scale);
  57416. this.y = this.y.scale(scale);
  57417. this.z = this.z.scale(scale);
  57418. this.xx = this.xx.scale(scale);
  57419. this.yy = this.yy.scale(scale);
  57420. this.zz = this.zz.scale(scale);
  57421. this.yz = this.yz.scale(scale);
  57422. this.zx = this.zx.scale(scale);
  57423. this.xy = this.xy.scale(scale);
  57424. };
  57425. return SphericalPolynomial;
  57426. }());
  57427. BABYLON.SphericalPolynomial = SphericalPolynomial;
  57428. var SphericalHarmonics = (function () {
  57429. function SphericalHarmonics() {
  57430. this.L00 = BABYLON.Vector3.Zero();
  57431. this.L1_1 = BABYLON.Vector3.Zero();
  57432. this.L10 = BABYLON.Vector3.Zero();
  57433. this.L11 = BABYLON.Vector3.Zero();
  57434. this.L2_2 = BABYLON.Vector3.Zero();
  57435. this.L2_1 = BABYLON.Vector3.Zero();
  57436. this.L20 = BABYLON.Vector3.Zero();
  57437. this.L21 = BABYLON.Vector3.Zero();
  57438. this.L22 = BABYLON.Vector3.Zero();
  57439. }
  57440. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  57441. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  57442. var c = colorVector.scale(deltaSolidAngle);
  57443. this.L00 = this.L00.add(c.scale(0.282095));
  57444. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  57445. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  57446. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  57447. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  57448. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  57449. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  57450. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  57451. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  57452. };
  57453. SphericalHarmonics.prototype.scale = function (scale) {
  57454. this.L00 = this.L00.scale(scale);
  57455. this.L1_1 = this.L1_1.scale(scale);
  57456. this.L10 = this.L10.scale(scale);
  57457. this.L11 = this.L11.scale(scale);
  57458. this.L2_2 = this.L2_2.scale(scale);
  57459. this.L2_1 = this.L2_1.scale(scale);
  57460. this.L20 = this.L20.scale(scale);
  57461. this.L21 = this.L21.scale(scale);
  57462. this.L22 = this.L22.scale(scale);
  57463. };
  57464. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  57465. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  57466. //
  57467. // E_lm = A_l * L_lm
  57468. //
  57469. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  57470. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  57471. // the scaling factors are given in equation 9.
  57472. // Constant (Band 0)
  57473. this.L00 = this.L00.scale(3.141593);
  57474. // Linear (Band 1)
  57475. this.L1_1 = this.L1_1.scale(2.094395);
  57476. this.L10 = this.L10.scale(2.094395);
  57477. this.L11 = this.L11.scale(2.094395);
  57478. // Quadratic (Band 2)
  57479. this.L2_2 = this.L2_2.scale(0.785398);
  57480. this.L2_1 = this.L2_1.scale(0.785398);
  57481. this.L20 = this.L20.scale(0.785398);
  57482. this.L21 = this.L21.scale(0.785398);
  57483. this.L22 = this.L22.scale(0.785398);
  57484. };
  57485. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  57486. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  57487. // L = (1/pi) * E * rho
  57488. //
  57489. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  57490. this.scale(1.0 / Math.PI);
  57491. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  57492. // (The pixel shader must apply albedo after texture fetches, etc).
  57493. };
  57494. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  57495. var result = new SphericalHarmonics();
  57496. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  57497. result.L1_1 = polynomial.y.scale(0.977204);
  57498. result.L10 = polynomial.z.scale(0.977204);
  57499. result.L11 = polynomial.x.scale(0.977204);
  57500. result.L2_2 = polynomial.xy.scale(1.16538);
  57501. result.L2_1 = polynomial.yz.scale(1.16538);
  57502. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  57503. result.L21 = polynomial.zx.scale(1.16538);
  57504. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  57505. result.scale(Math.PI);
  57506. return result;
  57507. };
  57508. return SphericalHarmonics;
  57509. }());
  57510. BABYLON.SphericalHarmonics = SphericalHarmonics;
  57511. })(BABYLON || (BABYLON = {}));
  57512. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  57513. var BABYLON;
  57514. (function (BABYLON) {
  57515. var Internals;
  57516. (function (Internals) {
  57517. var FileFaceOrientation = (function () {
  57518. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  57519. this.name = name;
  57520. this.worldAxisForNormal = worldAxisForNormal;
  57521. this.worldAxisForFileX = worldAxisForFileX;
  57522. this.worldAxisForFileY = worldAxisForFileY;
  57523. }
  57524. return FileFaceOrientation;
  57525. }());
  57526. ;
  57527. /**
  57528. * Helper class dealing with the extraction of spherical polynomial dataArray
  57529. * from a cube map.
  57530. */
  57531. var CubeMapToSphericalPolynomialTools = (function () {
  57532. function CubeMapToSphericalPolynomialTools() {
  57533. }
  57534. /**
  57535. * Converts a texture to the according Spherical Polynomial data.
  57536. * This extracts the first 3 orders only as they are the only one used in the lighting.
  57537. *
  57538. * @param texture The texture to extract the information from.
  57539. * @return The Spherical Polynomial data.
  57540. */
  57541. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  57542. if (!texture.isCube) {
  57543. // Only supports cube Textures currently.
  57544. return null;
  57545. }
  57546. var size = texture.getSize().width;
  57547. var right = texture.readPixels(0);
  57548. var left = texture.readPixels(1);
  57549. var up;
  57550. var down;
  57551. if (texture.isRenderTarget) {
  57552. up = texture.readPixels(3);
  57553. down = texture.readPixels(2);
  57554. }
  57555. else {
  57556. up = texture.readPixels(2);
  57557. down = texture.readPixels(3);
  57558. }
  57559. var front = texture.readPixels(4);
  57560. var back = texture.readPixels(5);
  57561. var gammaSpace = texture.gammaSpace;
  57562. // Always read as RGBA.
  57563. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  57564. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  57565. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  57566. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  57567. }
  57568. var cubeInfo = {
  57569. size: size,
  57570. right: right,
  57571. left: left,
  57572. up: up,
  57573. down: down,
  57574. front: front,
  57575. back: back,
  57576. format: format,
  57577. type: type,
  57578. gammaSpace: gammaSpace,
  57579. };
  57580. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  57581. };
  57582. /**
  57583. * Converts a cubemap to the according Spherical Polynomial data.
  57584. * This extracts the first 3 orders only as they are the only one used in the lighting.
  57585. *
  57586. * @param cubeInfo The Cube map to extract the information from.
  57587. * @return The Spherical Polynomial data.
  57588. */
  57589. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  57590. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  57591. var totalSolidAngle = 0.0;
  57592. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  57593. var du = 2.0 / cubeInfo.size;
  57594. var dv = du;
  57595. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  57596. var minUV = du * 0.5 - 1.0;
  57597. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  57598. var fileFace = this.FileFaces[faceIndex];
  57599. var dataArray = cubeInfo[fileFace.name];
  57600. var v = minUV;
  57601. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  57602. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  57603. // Because SP is still linear, so summation is fine in that basis.
  57604. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  57605. for (var y = 0; y < cubeInfo.size; y++) {
  57606. var u = minUV;
  57607. for (var x = 0; x < cubeInfo.size; x++) {
  57608. // World direction (not normalised)
  57609. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  57610. worldDirection.normalize();
  57611. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  57612. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  57613. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  57614. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  57615. // Handle Integer types.
  57616. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  57617. r /= 255;
  57618. g /= 255;
  57619. b /= 255;
  57620. }
  57621. // Handle Gamma space textures.
  57622. if (cubeInfo.gammaSpace) {
  57623. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  57624. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  57625. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  57626. }
  57627. var color = new BABYLON.Color3(r, g, b);
  57628. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  57629. totalSolidAngle += deltaSolidAngle;
  57630. u += du;
  57631. }
  57632. v += dv;
  57633. }
  57634. }
  57635. // Solid angle for entire sphere is 4*pi
  57636. var sphereSolidAngle = 4.0 * Math.PI;
  57637. // Adjust the solid angle to allow for how many faces we processed.
  57638. var facesProcessed = 6.0;
  57639. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  57640. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  57641. // This is needed because the numerical integration over the cube uses a
  57642. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  57643. // and also to compensate for accumulative error due to float precision in the summation.
  57644. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  57645. sphericalHarmonics.scale(correctionFactor);
  57646. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  57647. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  57648. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  57649. };
  57650. CubeMapToSphericalPolynomialTools.FileFaces = [
  57651. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  57652. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  57653. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  57654. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  57655. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  57656. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  57657. ];
  57658. return CubeMapToSphericalPolynomialTools;
  57659. }());
  57660. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  57661. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  57662. })(BABYLON || (BABYLON = {}));
  57663. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  57664. var BABYLON;
  57665. (function (BABYLON) {
  57666. var Internals;
  57667. (function (Internals) {
  57668. /**
  57669. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  57670. */
  57671. var PanoramaToCubeMapTools = (function () {
  57672. function PanoramaToCubeMapTools() {
  57673. }
  57674. /**
  57675. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  57676. *
  57677. * @param float32Array The source data.
  57678. * @param inputWidth The width of the input panorama.
  57679. * @param inputhHeight The height of the input panorama.
  57680. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  57681. * @return The cubemap data
  57682. */
  57683. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  57684. if (!float32Array) {
  57685. throw "ConvertPanoramaToCubemap: input cannot be null";
  57686. }
  57687. if (float32Array.length != inputWidth * inputHeight * 3) {
  57688. throw "ConvertPanoramaToCubemap: input size is wrong";
  57689. }
  57690. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  57691. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  57692. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  57693. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  57694. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  57695. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  57696. return {
  57697. front: textureFront,
  57698. back: textureBack,
  57699. left: textureLeft,
  57700. right: textureRight,
  57701. up: textureUp,
  57702. down: textureDown,
  57703. size: size,
  57704. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  57705. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  57706. gammaSpace: false,
  57707. };
  57708. };
  57709. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  57710. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  57711. var textureArray = new Float32Array(buffer);
  57712. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  57713. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  57714. var dy = 1 / texSize;
  57715. var fy = 0;
  57716. for (var y = 0; y < texSize; y++) {
  57717. var xv1 = faceData[0];
  57718. var xv2 = faceData[2];
  57719. for (var x = 0; x < texSize; x++) {
  57720. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  57721. v.normalize();
  57722. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  57723. // 3 channels per pixels
  57724. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  57725. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  57726. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  57727. xv1 = xv1.add(rotDX1);
  57728. xv2 = xv2.add(rotDX2);
  57729. }
  57730. fy += dy;
  57731. }
  57732. return textureArray;
  57733. };
  57734. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  57735. var theta = Math.atan2(vDir.z, vDir.x);
  57736. var phi = Math.acos(vDir.y);
  57737. while (theta < -Math.PI)
  57738. theta += 2 * Math.PI;
  57739. while (theta > Math.PI)
  57740. theta -= 2 * Math.PI;
  57741. var dx = theta / Math.PI;
  57742. var dy = phi / Math.PI;
  57743. // recenter.
  57744. dx = dx * 0.5 + 0.5;
  57745. var px = Math.round(dx * inputWidth);
  57746. if (px < 0)
  57747. px = 0;
  57748. else if (px >= inputWidth)
  57749. px = inputWidth - 1;
  57750. var py = Math.round(dy * inputHeight);
  57751. if (py < 0)
  57752. py = 0;
  57753. else if (py >= inputHeight)
  57754. py = inputHeight - 1;
  57755. var inputY = (inputHeight - py - 1);
  57756. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  57757. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  57758. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  57759. return {
  57760. r: r,
  57761. g: g,
  57762. b: b
  57763. };
  57764. };
  57765. PanoramaToCubeMapTools.FACE_FRONT = [
  57766. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  57767. new BABYLON.Vector3(1.0, -1.0, -1.0),
  57768. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  57769. new BABYLON.Vector3(1.0, 1.0, -1.0)
  57770. ];
  57771. PanoramaToCubeMapTools.FACE_BACK = [
  57772. new BABYLON.Vector3(1.0, -1.0, 1.0),
  57773. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  57774. new BABYLON.Vector3(1.0, 1.0, 1.0),
  57775. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  57776. ];
  57777. PanoramaToCubeMapTools.FACE_RIGHT = [
  57778. new BABYLON.Vector3(1.0, -1.0, -1.0),
  57779. new BABYLON.Vector3(1.0, -1.0, 1.0),
  57780. new BABYLON.Vector3(1.0, 1.0, -1.0),
  57781. new BABYLON.Vector3(1.0, 1.0, 1.0)
  57782. ];
  57783. PanoramaToCubeMapTools.FACE_LEFT = [
  57784. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  57785. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  57786. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  57787. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  57788. ];
  57789. PanoramaToCubeMapTools.FACE_DOWN = [
  57790. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  57791. new BABYLON.Vector3(1.0, 1.0, -1.0),
  57792. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  57793. new BABYLON.Vector3(1.0, 1.0, 1.0)
  57794. ];
  57795. PanoramaToCubeMapTools.FACE_UP = [
  57796. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  57797. new BABYLON.Vector3(1.0, -1.0, 1.0),
  57798. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  57799. new BABYLON.Vector3(1.0, -1.0, -1.0)
  57800. ];
  57801. return PanoramaToCubeMapTools;
  57802. }());
  57803. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  57804. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  57805. })(BABYLON || (BABYLON = {}));
  57806. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  57807. var BABYLON;
  57808. (function (BABYLON) {
  57809. var Internals;
  57810. (function (Internals) {
  57811. ;
  57812. /**
  57813. * This groups tools to convert HDR texture to native colors array.
  57814. */
  57815. var HDRTools = (function () {
  57816. function HDRTools() {
  57817. }
  57818. HDRTools.Ldexp = function (mantissa, exponent) {
  57819. if (exponent > 1023) {
  57820. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  57821. }
  57822. if (exponent < -1074) {
  57823. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  57824. }
  57825. return mantissa * Math.pow(2, exponent);
  57826. };
  57827. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  57828. if (exponent > 0) {
  57829. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  57830. float32array[index + 0] = red * exponent;
  57831. float32array[index + 1] = green * exponent;
  57832. float32array[index + 2] = blue * exponent;
  57833. }
  57834. else {
  57835. float32array[index + 0] = 0;
  57836. float32array[index + 1] = 0;
  57837. float32array[index + 2] = 0;
  57838. }
  57839. };
  57840. HDRTools.readStringLine = function (uint8array, startIndex) {
  57841. var line = "";
  57842. var character = "";
  57843. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  57844. character = String.fromCharCode(uint8array[i]);
  57845. if (character == "\n") {
  57846. break;
  57847. }
  57848. line += character;
  57849. }
  57850. return line;
  57851. };
  57852. /**
  57853. * Reads header information from an RGBE texture stored in a native array.
  57854. * More information on this format are available here:
  57855. * https://en.wikipedia.org/wiki/RGBE_image_format
  57856. *
  57857. * @param uint8array The binary file stored in native array.
  57858. * @return The header information.
  57859. */
  57860. HDRTools.RGBE_ReadHeader = function (uint8array) {
  57861. var height = 0;
  57862. var width = 0;
  57863. var line = this.readStringLine(uint8array, 0);
  57864. if (line[0] != '#' || line[1] != '?') {
  57865. throw "Bad HDR Format.";
  57866. }
  57867. var endOfHeader = false;
  57868. var findFormat = false;
  57869. var lineIndex = 0;
  57870. do {
  57871. lineIndex += (line.length + 1);
  57872. line = this.readStringLine(uint8array, lineIndex);
  57873. if (line == "FORMAT=32-bit_rle_rgbe") {
  57874. findFormat = true;
  57875. }
  57876. else if (line.length == 0) {
  57877. endOfHeader = true;
  57878. }
  57879. } while (!endOfHeader);
  57880. if (!findFormat) {
  57881. throw "HDR Bad header format, unsupported FORMAT";
  57882. }
  57883. lineIndex += (line.length + 1);
  57884. line = this.readStringLine(uint8array, lineIndex);
  57885. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  57886. var match = sizeRegexp.exec(line);
  57887. // TODO. Support +Y and -X if needed.
  57888. if (match.length < 3) {
  57889. throw "HDR Bad header format, no size";
  57890. }
  57891. width = parseInt(match[2]);
  57892. height = parseInt(match[1]);
  57893. if (width < 8 || width > 0x7fff) {
  57894. throw "HDR Bad header format, unsupported size";
  57895. }
  57896. lineIndex += (line.length + 1);
  57897. return {
  57898. height: height,
  57899. width: width,
  57900. dataPosition: lineIndex
  57901. };
  57902. };
  57903. /**
  57904. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  57905. * This RGBE texture needs to store the information as a panorama.
  57906. *
  57907. * More information on this format are available here:
  57908. * https://en.wikipedia.org/wiki/RGBE_image_format
  57909. *
  57910. * @param buffer The binary file stored in an array buffer.
  57911. * @param size The expected size of the extracted cubemap.
  57912. * @return The Cube Map information.
  57913. */
  57914. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  57915. var uint8array = new Uint8Array(buffer);
  57916. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  57917. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  57918. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  57919. return cubeMapData;
  57920. };
  57921. /**
  57922. * Returns the pixels data extracted from an RGBE texture.
  57923. * This pixels will be stored left to right up to down in the R G B order in one array.
  57924. *
  57925. * More information on this format are available here:
  57926. * https://en.wikipedia.org/wiki/RGBE_image_format
  57927. *
  57928. * @param uint8array The binary file stored in an array buffer.
  57929. * @param hdrInfo The header information of the file.
  57930. * @return The pixels data in RGB right to left up to down order.
  57931. */
  57932. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  57933. // Keep for multi format supports.
  57934. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  57935. };
  57936. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  57937. var num_scanlines = hdrInfo.height;
  57938. var scanline_width = hdrInfo.width;
  57939. var a, b, c, d, count;
  57940. var dataIndex = hdrInfo.dataPosition;
  57941. var index = 0, endIndex = 0, i = 0;
  57942. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  57943. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  57944. // 3 channels of 4 bytes per pixel in float.
  57945. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  57946. var resultArray = new Float32Array(resultBuffer);
  57947. // read in each successive scanline
  57948. while (num_scanlines > 0) {
  57949. a = uint8array[dataIndex++];
  57950. b = uint8array[dataIndex++];
  57951. c = uint8array[dataIndex++];
  57952. d = uint8array[dataIndex++];
  57953. if (a != 2 || b != 2 || (c & 0x80)) {
  57954. // this file is not run length encoded
  57955. throw "HDR Bad header format, not RLE";
  57956. }
  57957. if (((c << 8) | d) != scanline_width) {
  57958. throw "HDR Bad header format, wrong scan line width";
  57959. }
  57960. index = 0;
  57961. // read each of the four channels for the scanline into the buffer
  57962. for (i = 0; i < 4; i++) {
  57963. endIndex = (i + 1) * scanline_width;
  57964. while (index < endIndex) {
  57965. a = uint8array[dataIndex++];
  57966. b = uint8array[dataIndex++];
  57967. if (a > 128) {
  57968. // a run of the same value
  57969. count = a - 128;
  57970. if ((count == 0) || (count > endIndex - index)) {
  57971. throw "HDR Bad Format, bad scanline data (run)";
  57972. }
  57973. while (count-- > 0) {
  57974. scanLineArray[index++] = b;
  57975. }
  57976. }
  57977. else {
  57978. // a non-run
  57979. count = a;
  57980. if ((count == 0) || (count > endIndex - index)) {
  57981. throw "HDR Bad Format, bad scanline data (non-run)";
  57982. }
  57983. scanLineArray[index++] = b;
  57984. if (--count > 0) {
  57985. for (var j = 0; j < count; j++) {
  57986. scanLineArray[index++] = uint8array[dataIndex++];
  57987. }
  57988. }
  57989. }
  57990. }
  57991. }
  57992. // now convert data from buffer into floats
  57993. for (i = 0; i < scanline_width; i++) {
  57994. a = scanLineArray[i];
  57995. b = scanLineArray[i + scanline_width];
  57996. c = scanLineArray[i + 2 * scanline_width];
  57997. d = scanLineArray[i + 3 * scanline_width];
  57998. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  57999. }
  58000. num_scanlines--;
  58001. }
  58002. return resultArray;
  58003. };
  58004. return HDRTools;
  58005. }());
  58006. Internals.HDRTools = HDRTools;
  58007. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  58008. })(BABYLON || (BABYLON = {}));
  58009. //# sourceMappingURL=babylon.hdr.js.map
  58010. var BABYLON;
  58011. (function (BABYLON) {
  58012. /**
  58013. * This represents a texture coming from an HDR input.
  58014. *
  58015. * The only supported format is currently panorama picture stored in RGBE format.
  58016. * Example of such files can be found on HDRLib: http://hdrlib.com/
  58017. */
  58018. var HDRCubeTexture = (function (_super) {
  58019. __extends(HDRCubeTexture, _super);
  58020. /**
  58021. * Instantiates an HDRTexture from the following parameters.
  58022. *
  58023. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  58024. * @param scene The scene the texture will be used in
  58025. * @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.
  58026. * @param noMipmap Forces to not generate the mipmap if true
  58027. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  58028. * @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)
  58029. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  58030. */
  58031. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  58032. if (noMipmap === void 0) { noMipmap = false; }
  58033. if (generateHarmonics === void 0) { generateHarmonics = true; }
  58034. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  58035. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  58036. if (onLoad === void 0) { onLoad = null; }
  58037. if (onError === void 0) { onError = null; }
  58038. var _this = _super.call(this, scene) || this;
  58039. _this._useInGammaSpace = false;
  58040. _this._generateHarmonics = true;
  58041. _this._isBABYLONPreprocessed = false;
  58042. _this._onLoad = null;
  58043. _this._onError = null;
  58044. /**
  58045. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  58046. */
  58047. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  58048. /**
  58049. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  58050. * This is usefull at run time to apply the good shader.
  58051. */
  58052. _this.isPMREM = false;
  58053. _this._isBlocking = true;
  58054. if (!url) {
  58055. return _this;
  58056. }
  58057. _this.name = url;
  58058. _this.url = url;
  58059. _this.hasAlpha = false;
  58060. _this.isCube = true;
  58061. _this._textureMatrix = BABYLON.Matrix.Identity();
  58062. _this._onLoad = onLoad;
  58063. _this._onError = onError;
  58064. _this.gammaSpace = false;
  58065. if (size) {
  58066. _this._isBABYLONPreprocessed = false;
  58067. _this._noMipmap = noMipmap;
  58068. _this._size = size;
  58069. _this._useInGammaSpace = useInGammaSpace;
  58070. _this._usePMREMGenerator = usePMREMGenerator &&
  58071. scene.getEngine().getCaps().textureLOD &&
  58072. _this.getScene().getEngine().getCaps().textureFloat &&
  58073. !_this._useInGammaSpace;
  58074. }
  58075. else {
  58076. _this._isBABYLONPreprocessed = true;
  58077. _this._noMipmap = false;
  58078. _this._useInGammaSpace = false;
  58079. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  58080. _this.getScene().getEngine().getCaps().textureFloat &&
  58081. !_this._useInGammaSpace;
  58082. }
  58083. _this.isPMREM = _this._usePMREMGenerator;
  58084. _this._texture = _this._getFromCache(url, _this._noMipmap);
  58085. if (!_this._texture) {
  58086. if (!scene.useDelayedTextureLoading) {
  58087. _this.loadTexture();
  58088. }
  58089. else {
  58090. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  58091. }
  58092. }
  58093. return _this;
  58094. }
  58095. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  58096. /**
  58097. * Gets wether or not the texture is blocking during loading.
  58098. */
  58099. get: function () {
  58100. return this._isBlocking;
  58101. },
  58102. /**
  58103. * Sets wether or not the texture is blocking during loading.
  58104. */
  58105. set: function (value) {
  58106. this._isBlocking = value;
  58107. },
  58108. enumerable: true,
  58109. configurable: true
  58110. });
  58111. /**
  58112. * Occurs when the file is a preprocessed .babylon.hdr file.
  58113. */
  58114. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  58115. var _this = this;
  58116. var mipLevels = 0;
  58117. var floatArrayView = null;
  58118. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  58119. var mips = [];
  58120. var startIndex = 30;
  58121. for (var level = 0; level < mipLevels; level++) {
  58122. mips.push([]);
  58123. // Fill each pixel of the mip level.
  58124. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  58125. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  58126. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  58127. mips[level].push(faceData);
  58128. startIndex += faceSize;
  58129. }
  58130. }
  58131. return mips;
  58132. } : null;
  58133. var callback = function (buffer) {
  58134. // Create Native Array Views
  58135. var intArrayView = new Int32Array(buffer);
  58136. floatArrayView = new Float32Array(buffer);
  58137. // Fill header.
  58138. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  58139. _this._size = intArrayView[1]; // CubeMap max mip face size.
  58140. // Update Texture Information.
  58141. _this._texture.updateSize(_this._size, _this._size);
  58142. // Fill polynomial information.
  58143. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  58144. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  58145. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  58146. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  58147. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  58148. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  58149. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  58150. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  58151. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  58152. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  58153. _this.sphericalPolynomial = sphericalPolynomial;
  58154. // Fill pixel data.
  58155. mipLevels = intArrayView[29]; // Number of mip levels.
  58156. var startIndex = 30;
  58157. var data = [];
  58158. var faceSize = Math.pow(_this._size, 2) * 3;
  58159. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  58160. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  58161. startIndex += faceSize;
  58162. }
  58163. var results = [];
  58164. var byteArray = null;
  58165. // Push each faces.
  58166. for (var k = 0; k < 6; k++) {
  58167. var dataFace = null;
  58168. // To be deprecated.
  58169. if (version === 1) {
  58170. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  58171. dataFace = data[j];
  58172. }
  58173. // If special cases.
  58174. if (!mipmapGenerator) {
  58175. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  58176. // 3 channels of 1 bytes per pixel in bytes.
  58177. var byteBuffer = new ArrayBuffer(faceSize);
  58178. byteArray = new Uint8Array(byteBuffer);
  58179. }
  58180. for (var i = 0; i < _this._size * _this._size; i++) {
  58181. // Put in gamma space if requested.
  58182. if (_this._useInGammaSpace) {
  58183. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  58184. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  58185. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  58186. }
  58187. // Convert to int texture for fallback.
  58188. if (byteArray) {
  58189. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  58190. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  58191. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  58192. // May use luminance instead if the result is not accurate.
  58193. var max = Math.max(Math.max(r, g), b);
  58194. if (max > 255) {
  58195. var scale = 255 / max;
  58196. r *= scale;
  58197. g *= scale;
  58198. b *= scale;
  58199. }
  58200. byteArray[(i * 3) + 0] = r;
  58201. byteArray[(i * 3) + 1] = g;
  58202. byteArray[(i * 3) + 2] = b;
  58203. }
  58204. }
  58205. }
  58206. // Fill the array accordingly.
  58207. if (byteArray) {
  58208. results.push(byteArray);
  58209. }
  58210. else {
  58211. results.push(dataFace);
  58212. }
  58213. }
  58214. return results;
  58215. };
  58216. 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);
  58217. };
  58218. /**
  58219. * Occurs when the file is raw .hdr file.
  58220. */
  58221. HDRCubeTexture.prototype.loadHDRTexture = function () {
  58222. var _this = this;
  58223. var callback = function (buffer) {
  58224. // Extract the raw linear data.
  58225. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  58226. // Generate harmonics if needed.
  58227. if (_this._generateHarmonics) {
  58228. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  58229. _this.sphericalPolynomial = sphericalPolynomial;
  58230. }
  58231. var results = [];
  58232. var byteArray = null;
  58233. // Push each faces.
  58234. for (var j = 0; j < 6; j++) {
  58235. // Create uintarray fallback.
  58236. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  58237. // 3 channels of 1 bytes per pixel in bytes.
  58238. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  58239. byteArray = new Uint8Array(byteBuffer);
  58240. }
  58241. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  58242. // If special cases.
  58243. if (_this._useInGammaSpace || byteArray) {
  58244. for (var i = 0; i < _this._size * _this._size; i++) {
  58245. // Put in gamma space if requested.
  58246. if (_this._useInGammaSpace) {
  58247. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  58248. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  58249. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  58250. }
  58251. // Convert to int texture for fallback.
  58252. if (byteArray) {
  58253. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  58254. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  58255. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  58256. // May use luminance instead if the result is not accurate.
  58257. var max = Math.max(Math.max(r, g), b);
  58258. if (max > 255) {
  58259. var scale = 255 / max;
  58260. r *= scale;
  58261. g *= scale;
  58262. b *= scale;
  58263. }
  58264. byteArray[(i * 3) + 0] = r;
  58265. byteArray[(i * 3) + 1] = g;
  58266. byteArray[(i * 3) + 2] = b;
  58267. }
  58268. }
  58269. }
  58270. if (byteArray) {
  58271. results.push(byteArray);
  58272. }
  58273. else {
  58274. results.push(dataFace);
  58275. }
  58276. }
  58277. return results;
  58278. };
  58279. var mipmapGenerator = null;
  58280. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  58281. // if (!this._noMipmap &&
  58282. // this._usePMREMGenerator) {
  58283. // mipmapGenerator = (data: ArrayBufferView[]) => {
  58284. // // Custom setup of the generator matching with the PBR shader values.
  58285. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  58286. // this._size,
  58287. // this._size,
  58288. // 0,
  58289. // 3,
  58290. // this.getScene().getEngine().getCaps().textureFloat,
  58291. // 2048,
  58292. // 0.25,
  58293. // false,
  58294. // true);
  58295. // return generator.filterCubeMap();
  58296. // };
  58297. // }
  58298. 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);
  58299. };
  58300. /**
  58301. * Starts the loading process of the texture.
  58302. */
  58303. HDRCubeTexture.prototype.loadTexture = function () {
  58304. if (this._isBABYLONPreprocessed) {
  58305. this.loadBabylonTexture();
  58306. }
  58307. else {
  58308. this.loadHDRTexture();
  58309. }
  58310. };
  58311. HDRCubeTexture.prototype.clone = function () {
  58312. var size = this._isBABYLONPreprocessed ? null : this._size;
  58313. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  58314. // Base texture
  58315. newTexture.level = this.level;
  58316. newTexture.wrapU = this.wrapU;
  58317. newTexture.wrapV = this.wrapV;
  58318. newTexture.coordinatesIndex = this.coordinatesIndex;
  58319. newTexture.coordinatesMode = this.coordinatesMode;
  58320. return newTexture;
  58321. };
  58322. // Methods
  58323. HDRCubeTexture.prototype.delayLoad = function () {
  58324. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  58325. return;
  58326. }
  58327. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  58328. this._texture = this._getFromCache(this.url, this._noMipmap);
  58329. if (!this._texture) {
  58330. this.loadTexture();
  58331. }
  58332. };
  58333. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  58334. return this._textureMatrix;
  58335. };
  58336. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  58337. this._textureMatrix = value;
  58338. };
  58339. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  58340. var texture = null;
  58341. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  58342. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  58343. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  58344. texture.name = parsedTexture.name;
  58345. texture.hasAlpha = parsedTexture.hasAlpha;
  58346. texture.level = parsedTexture.level;
  58347. texture.coordinatesMode = parsedTexture.coordinatesMode;
  58348. texture.isBlocking = parsedTexture.isBlocking;
  58349. }
  58350. return texture;
  58351. };
  58352. HDRCubeTexture.prototype.serialize = function () {
  58353. if (!this.name) {
  58354. return null;
  58355. }
  58356. var serializationObject = {};
  58357. serializationObject.name = this.name;
  58358. serializationObject.hasAlpha = this.hasAlpha;
  58359. serializationObject.isCube = true;
  58360. serializationObject.level = this.level;
  58361. serializationObject.size = this._size;
  58362. serializationObject.coordinatesMode = this.coordinatesMode;
  58363. serializationObject.useInGammaSpace = this._useInGammaSpace;
  58364. serializationObject.generateHarmonics = this._generateHarmonics;
  58365. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  58366. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  58367. serializationObject.customType = "BABYLON.HDRCubeTexture";
  58368. serializationObject.noMipmap = this._noMipmap;
  58369. serializationObject.isBlocking = this._isBlocking;
  58370. return serializationObject;
  58371. };
  58372. /**
  58373. * Saves as a file the data contained in the texture in a binary format.
  58374. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  58375. * as the spherical used in the lighting.
  58376. * @param url The HDR file url.
  58377. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  58378. * @param onError Method called if any error happens during download.
  58379. * @return The packed binary data.
  58380. */
  58381. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  58382. if (onError === void 0) { onError = null; }
  58383. var callback = function (buffer) {
  58384. var data = new Blob([buffer], { type: 'application/octet-stream' });
  58385. // Returns a URL you can use as a href.
  58386. var objUrl = window.URL.createObjectURL(data);
  58387. // Simulates a link to it and click to dowload.
  58388. var a = document.createElement("a");
  58389. document.body.appendChild(a);
  58390. a.style.display = "none";
  58391. a.href = objUrl;
  58392. a.download = "envmap.babylon.hdr";
  58393. a.click();
  58394. };
  58395. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  58396. };
  58397. /**
  58398. * Serializes the data contained in the texture in a binary format.
  58399. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  58400. * as the spherical used in the lighting.
  58401. * @param url The HDR file url.
  58402. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  58403. * @param onError Method called if any error happens during download.
  58404. * @return The packed binary data.
  58405. */
  58406. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  58407. if (onError === void 0) { onError = null; }
  58408. // Needs the url tho create the texture.
  58409. if (!url) {
  58410. return null;
  58411. }
  58412. // Check Power of two size.
  58413. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  58414. return null;
  58415. }
  58416. // Coming Back in 3.1.
  58417. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  58418. return null;
  58419. };
  58420. HDRCubeTexture._facesMapping = [
  58421. "right",
  58422. "left",
  58423. "up",
  58424. "down",
  58425. "front",
  58426. "back"
  58427. ];
  58428. return HDRCubeTexture;
  58429. }(BABYLON.BaseTexture));
  58430. BABYLON.HDRCubeTexture = HDRCubeTexture;
  58431. })(BABYLON || (BABYLON = {}));
  58432. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  58433. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  58434. // Huge respect for a such great lib.
  58435. // Earcut license:
  58436. // Copyright (c) 2016, Mapbox
  58437. //
  58438. // Permission to use, copy, modify, and/or distribute this software for any purpose
  58439. // with or without fee is hereby granted, provided that the above copyright notice
  58440. // and this permission notice appear in all copies.
  58441. //
  58442. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  58443. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  58444. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  58445. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  58446. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  58447. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  58448. // THIS SOFTWARE.
  58449. var Earcut;
  58450. (function (Earcut) {
  58451. /**
  58452. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  58453. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  58454. * @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).
  58455. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  58456. */
  58457. function earcut(data, holeIndices, dim) {
  58458. dim = dim || 2;
  58459. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  58460. if (!outerNode)
  58461. return triangles;
  58462. var minX, minY, maxX, maxY, x, y, size;
  58463. if (hasHoles)
  58464. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  58465. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  58466. if (data.length > 80 * dim) {
  58467. minX = maxX = data[0];
  58468. minY = maxY = data[1];
  58469. for (var i = dim; i < outerLen; i += dim) {
  58470. x = data[i];
  58471. y = data[i + 1];
  58472. if (x < minX)
  58473. minX = x;
  58474. if (y < minY)
  58475. minY = y;
  58476. if (x > maxX)
  58477. maxX = x;
  58478. if (y > maxY)
  58479. maxY = y;
  58480. }
  58481. // minX, minY and size are later used to transform coords into integers for z-order calculation
  58482. size = Math.max(maxX - minX, maxY - minY);
  58483. }
  58484. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  58485. return triangles;
  58486. }
  58487. Earcut.earcut = earcut;
  58488. // create a circular doubly linked list from polygon points in the specified winding order
  58489. function linkedList(data, start, end, dim, clockwise) {
  58490. var i, last;
  58491. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  58492. for (i = start; i < end; i += dim)
  58493. last = insertNode(i, data[i], data[i + 1], last);
  58494. }
  58495. else {
  58496. for (i = end - dim; i >= start; i -= dim)
  58497. last = insertNode(i, data[i], data[i + 1], last);
  58498. }
  58499. if (last && equals(last, last.next)) {
  58500. removeNode(last);
  58501. last = last.next;
  58502. }
  58503. return last;
  58504. }
  58505. // eliminate colinear or duplicate points
  58506. function filterPoints(start, end) {
  58507. if (!start)
  58508. return start;
  58509. if (!end)
  58510. end = start;
  58511. var p = start, again;
  58512. do {
  58513. again = false;
  58514. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  58515. removeNode(p);
  58516. p = end = p.prev;
  58517. if (p === p.next)
  58518. return null;
  58519. again = true;
  58520. }
  58521. else {
  58522. p = p.next;
  58523. }
  58524. } while (again || p !== end);
  58525. return end;
  58526. }
  58527. // main ear slicing loop which triangulates a polygon (given as a linked list)
  58528. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  58529. if (!ear)
  58530. return;
  58531. // interlink polygon nodes in z-order
  58532. if (!pass && size)
  58533. indexCurve(ear, minX, minY, size);
  58534. var stop = ear, prev, next;
  58535. // iterate through ears, slicing them one by one
  58536. while (ear.prev !== ear.next) {
  58537. prev = ear.prev;
  58538. next = ear.next;
  58539. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  58540. // cut off the triangle
  58541. triangles.push(prev.i / dim);
  58542. triangles.push(ear.i / dim);
  58543. triangles.push(next.i / dim);
  58544. removeNode(ear);
  58545. // skipping the next vertice leads to less sliver triangles
  58546. ear = next.next;
  58547. stop = next.next;
  58548. continue;
  58549. }
  58550. ear = next;
  58551. // if we looped through the whole remaining polygon and can't find any more ears
  58552. if (ear === stop) {
  58553. // try filtering points and slicing again
  58554. if (!pass) {
  58555. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  58556. // if this didn't work, try curing all small self-intersections locally
  58557. }
  58558. else if (pass === 1) {
  58559. ear = cureLocalIntersections(ear, triangles, dim);
  58560. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  58561. // as a last resort, try splitting the remaining polygon into two
  58562. }
  58563. else if (pass === 2) {
  58564. splitEarcut(ear, triangles, dim, minX, minY, size);
  58565. }
  58566. break;
  58567. }
  58568. }
  58569. }
  58570. // check whether a polygon node forms a valid ear with adjacent nodes
  58571. function isEar(ear) {
  58572. var a = ear.prev, b = ear, c = ear.next;
  58573. if (area(a, b, c) >= 0)
  58574. return false; // reflex, can't be an ear
  58575. // now make sure we don't have other points inside the potential ear
  58576. var p = ear.next.next;
  58577. while (p !== ear.prev) {
  58578. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  58579. area(p.prev, p, p.next) >= 0)
  58580. return false;
  58581. p = p.next;
  58582. }
  58583. return true;
  58584. }
  58585. function isEarHashed(ear, minX, minY, size) {
  58586. var a = ear.prev, b = ear, c = ear.next;
  58587. if (area(a, b, c) >= 0)
  58588. return false; // reflex, can't be an ear
  58589. // triangle bbox; min & max are calculated like this for speed
  58590. 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);
  58591. // z-order range for the current triangle bbox;
  58592. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  58593. // first look for points inside the triangle in increasing z-order
  58594. var p = ear.nextZ;
  58595. while (p && p.z <= maxZ) {
  58596. if (p !== ear.prev &&
  58597. p !== ear.next &&
  58598. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  58599. area(p.prev, p, p.next) >= 0)
  58600. return false;
  58601. p = p.nextZ;
  58602. }
  58603. // then look for points in decreasing z-order
  58604. p = ear.prevZ;
  58605. while (p && p.z >= minZ) {
  58606. if (p !== ear.prev &&
  58607. p !== ear.next &&
  58608. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  58609. area(p.prev, p, p.next) >= 0)
  58610. return false;
  58611. p = p.prevZ;
  58612. }
  58613. return true;
  58614. }
  58615. // go through all polygon nodes and cure small local self-intersections
  58616. function cureLocalIntersections(start, triangles, dim) {
  58617. var p = start;
  58618. do {
  58619. var a = p.prev, b = p.next.next;
  58620. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  58621. triangles.push(a.i / dim);
  58622. triangles.push(p.i / dim);
  58623. triangles.push(b.i / dim);
  58624. // remove two nodes involved
  58625. removeNode(p);
  58626. removeNode(p.next);
  58627. p = start = b;
  58628. }
  58629. p = p.next;
  58630. } while (p !== start);
  58631. return p;
  58632. }
  58633. // try splitting polygon into two and triangulate them independently
  58634. function splitEarcut(start, triangles, dim, minX, minY, size) {
  58635. // look for a valid diagonal that divides the polygon into two
  58636. var a = start;
  58637. do {
  58638. var b = a.next.next;
  58639. while (b !== a.prev) {
  58640. if (a.i !== b.i && isValidDiagonal(a, b)) {
  58641. // split the polygon in two by the diagonal
  58642. var c = splitPolygon(a, b);
  58643. // filter colinear points around the cuts
  58644. a = filterPoints(a, a.next);
  58645. c = filterPoints(c, c.next);
  58646. // run earcut on each half
  58647. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  58648. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  58649. return;
  58650. }
  58651. b = b.next;
  58652. }
  58653. a = a.next;
  58654. } while (a !== start);
  58655. }
  58656. // link every hole into the outer loop, producing a single-ring polygon without holes
  58657. function eliminateHoles(data, holeIndices, outerNode, dim) {
  58658. var queue = [], i, len, start, end, list;
  58659. for (i = 0, len = holeIndices.length; i < len; i++) {
  58660. start = holeIndices[i] * dim;
  58661. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  58662. list = linkedList(data, start, end, dim, false);
  58663. if (list === list.next)
  58664. list.steiner = true;
  58665. queue.push(getLeftmost(list));
  58666. }
  58667. queue.sort(compareX);
  58668. // process holes from left to right
  58669. for (i = 0; i < queue.length; i++) {
  58670. eliminateHole(queue[i], outerNode);
  58671. outerNode = filterPoints(outerNode, outerNode.next);
  58672. }
  58673. return outerNode;
  58674. }
  58675. function compareX(a, b) {
  58676. return a.x - b.x;
  58677. }
  58678. // find a bridge between vertices that connects hole with an outer ring and and link it
  58679. function eliminateHole(hole, outerNode) {
  58680. outerNode = findHoleBridge(hole, outerNode);
  58681. if (outerNode) {
  58682. var b = splitPolygon(outerNode, hole);
  58683. filterPoints(b, b.next);
  58684. }
  58685. }
  58686. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  58687. function findHoleBridge(hole, outerNode) {
  58688. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  58689. // find a segment intersected by a ray from the hole's leftmost point to the left;
  58690. // segment's endpoint with lesser x will be potential connection point
  58691. do {
  58692. if (hy <= p.y && hy >= p.next.y) {
  58693. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  58694. if (x <= hx && x > qx) {
  58695. qx = x;
  58696. if (x === hx) {
  58697. if (hy === p.y)
  58698. return p;
  58699. if (hy === p.next.y)
  58700. return p.next;
  58701. }
  58702. m = p.x < p.next.x ? p : p.next;
  58703. }
  58704. }
  58705. p = p.next;
  58706. } while (p !== outerNode);
  58707. if (!m)
  58708. return null;
  58709. if (hx === qx)
  58710. return m.prev; // hole touches outer segment; pick lower endpoint
  58711. // look for points inside the triangle of hole point, segment intersection and endpoint;
  58712. // if there are no points found, we have a valid connection;
  58713. // otherwise choose the point of the minimum angle with the ray as connection point
  58714. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  58715. p = m.next;
  58716. while (p !== stop) {
  58717. if (hx >= p.x &&
  58718. p.x >= mx &&
  58719. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  58720. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  58721. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  58722. m = p;
  58723. tanMin = tan;
  58724. }
  58725. }
  58726. p = p.next;
  58727. }
  58728. return m;
  58729. }
  58730. // interlink polygon nodes in z-order
  58731. function indexCurve(start, minX, minY, size) {
  58732. var p = start;
  58733. do {
  58734. if (p.z === null)
  58735. p.z = zOrder(p.x, p.y, minX, minY, size);
  58736. p.prevZ = p.prev;
  58737. p.nextZ = p.next;
  58738. p = p.next;
  58739. } while (p !== start);
  58740. p.prevZ.nextZ = null;
  58741. p.prevZ = null;
  58742. sortLinked(p);
  58743. }
  58744. // Simon Tatham's linked list merge sort algorithm
  58745. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  58746. function sortLinked(list) {
  58747. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  58748. do {
  58749. p = list;
  58750. list = null;
  58751. tail = null;
  58752. numMerges = 0;
  58753. while (p) {
  58754. numMerges++;
  58755. q = p;
  58756. pSize = 0;
  58757. for (i = 0; i < inSize; i++) {
  58758. pSize++;
  58759. q = q.nextZ;
  58760. if (!q)
  58761. break;
  58762. }
  58763. qSize = inSize;
  58764. while (pSize > 0 || (qSize > 0 && q)) {
  58765. if (pSize === 0) {
  58766. e = q;
  58767. q = q.nextZ;
  58768. qSize--;
  58769. }
  58770. else if (qSize === 0 || !q) {
  58771. e = p;
  58772. p = p.nextZ;
  58773. pSize--;
  58774. }
  58775. else if (p.z <= q.z) {
  58776. e = p;
  58777. p = p.nextZ;
  58778. pSize--;
  58779. }
  58780. else {
  58781. e = q;
  58782. q = q.nextZ;
  58783. qSize--;
  58784. }
  58785. if (tail)
  58786. tail.nextZ = e;
  58787. else
  58788. list = e;
  58789. e.prevZ = tail;
  58790. tail = e;
  58791. }
  58792. p = q;
  58793. }
  58794. tail.nextZ = null;
  58795. inSize *= 2;
  58796. } while (numMerges > 1);
  58797. return list;
  58798. }
  58799. // z-order of a point given coords and size of the data bounding box
  58800. function zOrder(x, y, minX, minY, size) {
  58801. // coords are transformed into non-negative 15-bit integer range
  58802. x = 32767 * (x - minX) / size;
  58803. y = 32767 * (y - minY) / size;
  58804. x = (x | (x << 8)) & 0x00FF00FF;
  58805. x = (x | (x << 4)) & 0x0F0F0F0F;
  58806. x = (x | (x << 2)) & 0x33333333;
  58807. x = (x | (x << 1)) & 0x55555555;
  58808. y = (y | (y << 8)) & 0x00FF00FF;
  58809. y = (y | (y << 4)) & 0x0F0F0F0F;
  58810. y = (y | (y << 2)) & 0x33333333;
  58811. y = (y | (y << 1)) & 0x55555555;
  58812. return x | (y << 1);
  58813. }
  58814. // find the leftmost node of a polygon ring
  58815. function getLeftmost(start) {
  58816. var p = start, leftmost = start;
  58817. do {
  58818. if (p.x < leftmost.x)
  58819. leftmost = p;
  58820. p = p.next;
  58821. } while (p !== start);
  58822. return leftmost;
  58823. }
  58824. // check if a point lies within a convex triangle
  58825. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  58826. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  58827. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  58828. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  58829. }
  58830. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  58831. function isValidDiagonal(a, b) {
  58832. return a.next.i !== b.i &&
  58833. a.prev.i !== b.i &&
  58834. !intersectsPolygon(a, b) &&
  58835. locallyInside(a, b) &&
  58836. locallyInside(b, a) &&
  58837. middleInside(a, b);
  58838. }
  58839. // signed area of a triangle
  58840. function area(p, q, r) {
  58841. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  58842. }
  58843. // check if two points are equal
  58844. function equals(p1, p2) {
  58845. return p1.x === p2.x && p1.y === p2.y;
  58846. }
  58847. // check if two segments intersect
  58848. function intersects(p1, q1, p2, q2) {
  58849. if ((equals(p1, q1) && equals(p2, q2)) ||
  58850. (equals(p1, q2) && equals(p2, q1)))
  58851. return true;
  58852. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  58853. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  58854. }
  58855. // check if a polygon diagonal intersects any polygon segments
  58856. function intersectsPolygon(a, b) {
  58857. var p = a;
  58858. do {
  58859. if (p.i !== a.i &&
  58860. p.next.i !== a.i &&
  58861. p.i !== b.i &&
  58862. p.next.i !== b.i &&
  58863. intersects(p, p.next, a, b))
  58864. return true;
  58865. p = p.next;
  58866. } while (p !== a);
  58867. return false;
  58868. }
  58869. // check if a polygon diagonal is locally inside the polygon
  58870. function locallyInside(a, b) {
  58871. return area(a.prev, a, a.next) < 0
  58872. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  58873. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  58874. }
  58875. // check if the middle point of a polygon diagonal is inside the polygon
  58876. function middleInside(a, b) {
  58877. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  58878. do {
  58879. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  58880. inside = !inside;
  58881. p = p.next;
  58882. } while (p !== a);
  58883. return inside;
  58884. }
  58885. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  58886. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  58887. function splitPolygon(a, b) {
  58888. 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;
  58889. a.next = b;
  58890. b.prev = a;
  58891. a2.next = an;
  58892. an.prev = a2;
  58893. b2.next = a2;
  58894. a2.prev = b2;
  58895. bp.next = b2;
  58896. b2.prev = bp;
  58897. return b2;
  58898. }
  58899. // create a node and optionally link it with previous one (in a circular doubly linked list)
  58900. function insertNode(i, x, y, last) {
  58901. var p = new Node(i, x, y);
  58902. if (!last) {
  58903. p.prev = p;
  58904. p.next = p;
  58905. }
  58906. else {
  58907. p.next = last.next;
  58908. p.prev = last;
  58909. last.next.prev = p;
  58910. last.next = p;
  58911. }
  58912. return p;
  58913. }
  58914. function removeNode(p) {
  58915. p.next.prev = p.prev;
  58916. p.prev.next = p.next;
  58917. if (p.prevZ)
  58918. p.prevZ.nextZ = p.nextZ;
  58919. if (p.nextZ)
  58920. p.nextZ.prevZ = p.prevZ;
  58921. }
  58922. function Node(i, x, y) {
  58923. // vertice index in coordinates array
  58924. this.i = i;
  58925. // vertex coordinates
  58926. this.x = x;
  58927. this.y = y;
  58928. // previous and next vertice nodes in a polygon ring
  58929. this.prev = null;
  58930. this.next = null;
  58931. // z-order curve value
  58932. this.z = null;
  58933. // previous and next nodes in z-order
  58934. this.prevZ = null;
  58935. this.nextZ = null;
  58936. // indicates whether this is a steiner point
  58937. this.steiner = false;
  58938. }
  58939. /**
  58940. * return a percentage difference between the polygon area and its triangulation area;
  58941. * used to verify correctness of triangulation
  58942. */
  58943. function deviation(data, holeIndices, dim, triangles) {
  58944. var hasHoles = holeIndices && holeIndices.length;
  58945. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  58946. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  58947. if (hasHoles) {
  58948. for (var i = 0, len = holeIndices.length; i < len; i++) {
  58949. var start = holeIndices[i] * dim;
  58950. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  58951. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  58952. }
  58953. }
  58954. var trianglesArea = 0;
  58955. for (i = 0; i < triangles.length; i += 3) {
  58956. var a = triangles[i] * dim;
  58957. var b = triangles[i + 1] * dim;
  58958. var c = triangles[i + 2] * dim;
  58959. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  58960. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  58961. }
  58962. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  58963. }
  58964. Earcut.deviation = deviation;
  58965. ;
  58966. function signedArea(data, start, end, dim) {
  58967. var sum = 0;
  58968. for (var i = start, j = end - dim; i < end; i += dim) {
  58969. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  58970. j = i;
  58971. }
  58972. return sum;
  58973. }
  58974. /**
  58975. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  58976. */
  58977. function flatten(data) {
  58978. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  58979. for (var i = 0; i < data.length; i++) {
  58980. for (var j = 0; j < data[i].length; j++) {
  58981. for (var d = 0; d < dim; d++)
  58982. result.vertices.push(data[i][j][d]);
  58983. }
  58984. if (i > 0) {
  58985. holeIndex += data[i - 1].length;
  58986. result.holes.push(holeIndex);
  58987. }
  58988. }
  58989. return result;
  58990. }
  58991. Earcut.flatten = flatten;
  58992. ;
  58993. })(Earcut || (Earcut = {}));
  58994. //# sourceMappingURL=babylon.earcut.js.map
  58995. /// <reference path="..\Math\babylon.math.ts" />
  58996. var BABYLON;
  58997. (function (BABYLON) {
  58998. var IndexedVector2 = (function (_super) {
  58999. __extends(IndexedVector2, _super);
  59000. function IndexedVector2(original, index) {
  59001. var _this = _super.call(this, original.x, original.y) || this;
  59002. _this.index = index;
  59003. return _this;
  59004. }
  59005. return IndexedVector2;
  59006. }(BABYLON.Vector2));
  59007. var PolygonPoints = (function () {
  59008. function PolygonPoints() {
  59009. this.elements = new Array();
  59010. }
  59011. PolygonPoints.prototype.add = function (originalPoints) {
  59012. var _this = this;
  59013. var result = new Array();
  59014. originalPoints.forEach(function (point) {
  59015. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  59016. var newPoint = new IndexedVector2(point, _this.elements.length);
  59017. result.push(newPoint);
  59018. _this.elements.push(newPoint);
  59019. }
  59020. });
  59021. return result;
  59022. };
  59023. PolygonPoints.prototype.computeBounds = function () {
  59024. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  59025. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  59026. this.elements.forEach(function (point) {
  59027. // x
  59028. if (point.x < lmin.x) {
  59029. lmin.x = point.x;
  59030. }
  59031. else if (point.x > lmax.x) {
  59032. lmax.x = point.x;
  59033. }
  59034. // y
  59035. if (point.y < lmin.y) {
  59036. lmin.y = point.y;
  59037. }
  59038. else if (point.y > lmax.y) {
  59039. lmax.y = point.y;
  59040. }
  59041. });
  59042. return {
  59043. min: lmin,
  59044. max: lmax,
  59045. width: lmax.x - lmin.x,
  59046. height: lmax.y - lmin.y
  59047. };
  59048. };
  59049. return PolygonPoints;
  59050. }());
  59051. var Polygon = (function () {
  59052. function Polygon() {
  59053. }
  59054. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  59055. return [
  59056. new BABYLON.Vector2(xmin, ymin),
  59057. new BABYLON.Vector2(xmax, ymin),
  59058. new BABYLON.Vector2(xmax, ymax),
  59059. new BABYLON.Vector2(xmin, ymax)
  59060. ];
  59061. };
  59062. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  59063. if (cx === void 0) { cx = 0; }
  59064. if (cy === void 0) { cy = 0; }
  59065. if (numberOfSides === void 0) { numberOfSides = 32; }
  59066. var result = new Array();
  59067. var angle = 0;
  59068. var increment = (Math.PI * 2) / numberOfSides;
  59069. for (var i = 0; i < numberOfSides; i++) {
  59070. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  59071. angle -= increment;
  59072. }
  59073. return result;
  59074. };
  59075. Polygon.Parse = function (input) {
  59076. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  59077. var i, result = [];
  59078. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  59079. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  59080. }
  59081. return result;
  59082. };
  59083. Polygon.StartingAt = function (x, y) {
  59084. return BABYLON.Path2.StartingAt(x, y);
  59085. };
  59086. return Polygon;
  59087. }());
  59088. BABYLON.Polygon = Polygon;
  59089. var PolygonMeshBuilder = (function () {
  59090. function PolygonMeshBuilder(name, contours, scene) {
  59091. this._points = new PolygonPoints();
  59092. this._outlinepoints = new PolygonPoints();
  59093. this._holes = [];
  59094. this._epoints = new Array();
  59095. this._eholes = new Array();
  59096. this._name = name;
  59097. this._scene = scene;
  59098. var points;
  59099. if (contours instanceof BABYLON.Path2) {
  59100. points = contours.getPoints();
  59101. }
  59102. else {
  59103. points = contours;
  59104. }
  59105. this._addToepoint(points);
  59106. this._points.add(points);
  59107. this._outlinepoints.add(points);
  59108. }
  59109. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  59110. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  59111. var p = points_1[_i];
  59112. this._epoints.push(p.x, p.y);
  59113. }
  59114. };
  59115. PolygonMeshBuilder.prototype.addHole = function (hole) {
  59116. this._points.add(hole);
  59117. var holepoints = new PolygonPoints();
  59118. holepoints.add(hole);
  59119. this._holes.push(holepoints);
  59120. this._eholes.push(this._epoints.length / 2);
  59121. this._addToepoint(hole);
  59122. return this;
  59123. };
  59124. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  59125. var _this = this;
  59126. if (updatable === void 0) { updatable = false; }
  59127. var result = new BABYLON.Mesh(this._name, this._scene);
  59128. var normals = [];
  59129. var positions = [];
  59130. var uvs = [];
  59131. var bounds = this._points.computeBounds();
  59132. this._points.elements.forEach(function (p) {
  59133. normals.push(0, 1.0, 0);
  59134. positions.push(p.x, 0, p.y);
  59135. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  59136. });
  59137. var indices = [];
  59138. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  59139. for (var i = 0; i < res.length; i++) {
  59140. indices.push(res[i]);
  59141. }
  59142. if (depth > 0) {
  59143. var positionscount = (positions.length / 3); //get the current pointcount
  59144. this._points.elements.forEach(function (p) {
  59145. normals.push(0, -1.0, 0);
  59146. positions.push(p.x, -depth, p.y);
  59147. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  59148. });
  59149. var totalCount = indices.length;
  59150. for (var i = 0; i < totalCount; i += 3) {
  59151. var i0 = indices[i + 0];
  59152. var i1 = indices[i + 1];
  59153. var i2 = indices[i + 2];
  59154. indices.push(i2 + positionscount);
  59155. indices.push(i1 + positionscount);
  59156. indices.push(i0 + positionscount);
  59157. }
  59158. //Add the sides
  59159. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  59160. this._holes.forEach(function (hole) {
  59161. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  59162. });
  59163. }
  59164. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  59165. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  59166. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  59167. result.setIndices(indices);
  59168. return result;
  59169. };
  59170. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  59171. var StartIndex = positions.length / 3;
  59172. var ulength = 0;
  59173. for (var i = 0; i < points.elements.length; i++) {
  59174. var p = points.elements[i];
  59175. var p1;
  59176. if ((i + 1) > points.elements.length - 1) {
  59177. p1 = points.elements[0];
  59178. }
  59179. else {
  59180. p1 = points.elements[i + 1];
  59181. }
  59182. positions.push(p.x, 0, p.y);
  59183. positions.push(p.x, -depth, p.y);
  59184. positions.push(p1.x, 0, p1.y);
  59185. positions.push(p1.x, -depth, p1.y);
  59186. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  59187. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  59188. var v3 = v2.subtract(v1);
  59189. var v4 = new BABYLON.Vector3(0, 1, 0);
  59190. var vn = BABYLON.Vector3.Cross(v3, v4);
  59191. vn = vn.normalize();
  59192. uvs.push(ulength / bounds.width, 0);
  59193. uvs.push(ulength / bounds.width, 1);
  59194. ulength += v3.length();
  59195. uvs.push((ulength / bounds.width), 0);
  59196. uvs.push((ulength / bounds.width), 1);
  59197. if (!flip) {
  59198. normals.push(-vn.x, -vn.y, -vn.z);
  59199. normals.push(-vn.x, -vn.y, -vn.z);
  59200. normals.push(-vn.x, -vn.y, -vn.z);
  59201. normals.push(-vn.x, -vn.y, -vn.z);
  59202. indices.push(StartIndex);
  59203. indices.push(StartIndex + 1);
  59204. indices.push(StartIndex + 2);
  59205. indices.push(StartIndex + 1);
  59206. indices.push(StartIndex + 3);
  59207. indices.push(StartIndex + 2);
  59208. }
  59209. else {
  59210. normals.push(vn.x, vn.y, vn.z);
  59211. normals.push(vn.x, vn.y, vn.z);
  59212. normals.push(vn.x, vn.y, vn.z);
  59213. normals.push(vn.x, vn.y, vn.z);
  59214. indices.push(StartIndex);
  59215. indices.push(StartIndex + 2);
  59216. indices.push(StartIndex + 1);
  59217. indices.push(StartIndex + 1);
  59218. indices.push(StartIndex + 2);
  59219. indices.push(StartIndex + 3);
  59220. }
  59221. StartIndex += 4;
  59222. }
  59223. ;
  59224. };
  59225. return PolygonMeshBuilder;
  59226. }());
  59227. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  59228. })(BABYLON || (BABYLON = {}));
  59229. //# sourceMappingURL=babylon.polygonMesh.js.map
  59230. var BABYLON;
  59231. (function (BABYLON) {
  59232. // Unique ID when we import meshes from Babylon to CSG
  59233. var currentCSGMeshId = 0;
  59234. // # class Vertex
  59235. // Represents a vertex of a polygon. Use your own vertex class instead of this
  59236. // one to provide additional features like texture coordinates and vertex
  59237. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  59238. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  59239. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  59240. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  59241. // is not used anywhere else.
  59242. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  59243. var Vertex = (function () {
  59244. function Vertex(pos, normal, uv) {
  59245. this.pos = pos;
  59246. this.normal = normal;
  59247. this.uv = uv;
  59248. }
  59249. Vertex.prototype.clone = function () {
  59250. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  59251. };
  59252. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  59253. // orientation of a polygon is flipped.
  59254. Vertex.prototype.flip = function () {
  59255. this.normal = this.normal.scale(-1);
  59256. };
  59257. // Create a new vertex between this vertex and `other` by linearly
  59258. // interpolating all properties using a parameter of `t`. Subclasses should
  59259. // override this to interpolate additional properties.
  59260. Vertex.prototype.interpolate = function (other, t) {
  59261. 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));
  59262. };
  59263. return Vertex;
  59264. }());
  59265. // # class Plane
  59266. // Represents a plane in 3D space.
  59267. var Plane = (function () {
  59268. function Plane(normal, w) {
  59269. this.normal = normal;
  59270. this.w = w;
  59271. }
  59272. Plane.FromPoints = function (a, b, c) {
  59273. var v0 = c.subtract(a);
  59274. var v1 = b.subtract(a);
  59275. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  59276. return null;
  59277. }
  59278. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  59279. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  59280. };
  59281. Plane.prototype.clone = function () {
  59282. return new Plane(this.normal.clone(), this.w);
  59283. };
  59284. Plane.prototype.flip = function () {
  59285. this.normal.scaleInPlace(-1);
  59286. this.w = -this.w;
  59287. };
  59288. // Split `polygon` by this plane if needed, then put the polygon or polygon
  59289. // fragments in the appropriate lists. Coplanar polygons go into either
  59290. // `coplanarFront` or `coplanarBack` depending on their orientation with
  59291. // respect to this plane. Polygons in front or in back of this plane go into
  59292. // either `front` or `back`.
  59293. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  59294. var COPLANAR = 0;
  59295. var FRONT = 1;
  59296. var BACK = 2;
  59297. var SPANNING = 3;
  59298. // Classify each point as well as the entire polygon into one of the above
  59299. // four classes.
  59300. var polygonType = 0;
  59301. var types = [];
  59302. var i;
  59303. var t;
  59304. for (i = 0; i < polygon.vertices.length; i++) {
  59305. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  59306. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  59307. polygonType |= type;
  59308. types.push(type);
  59309. }
  59310. // Put the polygon in the correct list, splitting it when necessary.
  59311. switch (polygonType) {
  59312. case COPLANAR:
  59313. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  59314. break;
  59315. case FRONT:
  59316. front.push(polygon);
  59317. break;
  59318. case BACK:
  59319. back.push(polygon);
  59320. break;
  59321. case SPANNING:
  59322. var f = [], b = [];
  59323. for (i = 0; i < polygon.vertices.length; i++) {
  59324. var j = (i + 1) % polygon.vertices.length;
  59325. var ti = types[i], tj = types[j];
  59326. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  59327. if (ti !== BACK)
  59328. f.push(vi);
  59329. if (ti !== FRONT)
  59330. b.push(ti !== BACK ? vi.clone() : vi);
  59331. if ((ti | tj) === SPANNING) {
  59332. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  59333. var v = vi.interpolate(vj, t);
  59334. f.push(v);
  59335. b.push(v.clone());
  59336. }
  59337. }
  59338. var poly;
  59339. if (f.length >= 3) {
  59340. poly = new Polygon(f, polygon.shared);
  59341. if (poly.plane)
  59342. front.push(poly);
  59343. }
  59344. if (b.length >= 3) {
  59345. poly = new Polygon(b, polygon.shared);
  59346. if (poly.plane)
  59347. back.push(poly);
  59348. }
  59349. break;
  59350. }
  59351. };
  59352. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  59353. // point is on the plane.
  59354. Plane.EPSILON = 1e-5;
  59355. return Plane;
  59356. }());
  59357. // # class Polygon
  59358. // Represents a convex polygon. The vertices used to initialize a polygon must
  59359. // be coplanar and form a convex loop.
  59360. //
  59361. // Each convex polygon has a `shared` property, which is shared between all
  59362. // polygons that are clones of each other or were split from the same polygon.
  59363. // This can be used to define per-polygon properties (such as surface color).
  59364. var Polygon = (function () {
  59365. function Polygon(vertices, shared) {
  59366. this.vertices = vertices;
  59367. this.shared = shared;
  59368. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  59369. }
  59370. Polygon.prototype.clone = function () {
  59371. var vertices = this.vertices.map(function (v) { return v.clone(); });
  59372. return new Polygon(vertices, this.shared);
  59373. };
  59374. Polygon.prototype.flip = function () {
  59375. this.vertices.reverse().map(function (v) { v.flip(); });
  59376. this.plane.flip();
  59377. };
  59378. return Polygon;
  59379. }());
  59380. // # class Node
  59381. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  59382. // by picking a polygon to split along. That polygon (and all other coplanar
  59383. // polygons) are added directly to that node and the other polygons are added to
  59384. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  59385. // no distinction between internal and leaf nodes.
  59386. var Node = (function () {
  59387. function Node(polygons) {
  59388. this.plane = null;
  59389. this.front = null;
  59390. this.back = null;
  59391. this.polygons = [];
  59392. if (polygons) {
  59393. this.build(polygons);
  59394. }
  59395. }
  59396. Node.prototype.clone = function () {
  59397. var node = new Node();
  59398. node.plane = this.plane && this.plane.clone();
  59399. node.front = this.front && this.front.clone();
  59400. node.back = this.back && this.back.clone();
  59401. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  59402. return node;
  59403. };
  59404. // Convert solid space to empty space and empty space to solid space.
  59405. Node.prototype.invert = function () {
  59406. for (var i = 0; i < this.polygons.length; i++) {
  59407. this.polygons[i].flip();
  59408. }
  59409. if (this.plane) {
  59410. this.plane.flip();
  59411. }
  59412. if (this.front) {
  59413. this.front.invert();
  59414. }
  59415. if (this.back) {
  59416. this.back.invert();
  59417. }
  59418. var temp = this.front;
  59419. this.front = this.back;
  59420. this.back = temp;
  59421. };
  59422. // Recursively remove all polygons in `polygons` that are inside this BSP
  59423. // tree.
  59424. Node.prototype.clipPolygons = function (polygons) {
  59425. if (!this.plane)
  59426. return polygons.slice();
  59427. var front = [], back = [];
  59428. for (var i = 0; i < polygons.length; i++) {
  59429. this.plane.splitPolygon(polygons[i], front, back, front, back);
  59430. }
  59431. if (this.front) {
  59432. front = this.front.clipPolygons(front);
  59433. }
  59434. if (this.back) {
  59435. back = this.back.clipPolygons(back);
  59436. }
  59437. else {
  59438. back = [];
  59439. }
  59440. return front.concat(back);
  59441. };
  59442. // Remove all polygons in this BSP tree that are inside the other BSP tree
  59443. // `bsp`.
  59444. Node.prototype.clipTo = function (bsp) {
  59445. this.polygons = bsp.clipPolygons(this.polygons);
  59446. if (this.front)
  59447. this.front.clipTo(bsp);
  59448. if (this.back)
  59449. this.back.clipTo(bsp);
  59450. };
  59451. // Return a list of all polygons in this BSP tree.
  59452. Node.prototype.allPolygons = function () {
  59453. var polygons = this.polygons.slice();
  59454. if (this.front)
  59455. polygons = polygons.concat(this.front.allPolygons());
  59456. if (this.back)
  59457. polygons = polygons.concat(this.back.allPolygons());
  59458. return polygons;
  59459. };
  59460. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  59461. // new polygons are filtered down to the bottom of the tree and become new
  59462. // nodes there. Each set of polygons is partitioned using the first polygon
  59463. // (no heuristic is used to pick a good split).
  59464. Node.prototype.build = function (polygons) {
  59465. if (!polygons.length)
  59466. return;
  59467. if (!this.plane)
  59468. this.plane = polygons[0].plane.clone();
  59469. var front = [], back = [];
  59470. for (var i = 0; i < polygons.length; i++) {
  59471. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  59472. }
  59473. if (front.length) {
  59474. if (!this.front)
  59475. this.front = new Node();
  59476. this.front.build(front);
  59477. }
  59478. if (back.length) {
  59479. if (!this.back)
  59480. this.back = new Node();
  59481. this.back.build(back);
  59482. }
  59483. };
  59484. return Node;
  59485. }());
  59486. var CSG = (function () {
  59487. function CSG() {
  59488. this.polygons = new Array();
  59489. }
  59490. // Convert BABYLON.Mesh to BABYLON.CSG
  59491. CSG.FromMesh = function (mesh) {
  59492. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  59493. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  59494. if (mesh instanceof BABYLON.Mesh) {
  59495. mesh.computeWorldMatrix(true);
  59496. matrix = mesh.getWorldMatrix();
  59497. meshPosition = mesh.position.clone();
  59498. meshRotation = mesh.rotation.clone();
  59499. if (mesh.rotationQuaternion) {
  59500. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  59501. }
  59502. meshScaling = mesh.scaling.clone();
  59503. }
  59504. else {
  59505. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  59506. }
  59507. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  59508. var subMeshes = mesh.subMeshes;
  59509. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  59510. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  59511. vertices = [];
  59512. for (var j = 0; j < 3; j++) {
  59513. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  59514. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  59515. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  59516. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  59517. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  59518. vertex = new Vertex(position, normal, uv);
  59519. vertices.push(vertex);
  59520. }
  59521. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  59522. // To handle the case of degenerated triangle
  59523. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  59524. if (polygon.plane)
  59525. polygons.push(polygon);
  59526. }
  59527. }
  59528. var csg = CSG.FromPolygons(polygons);
  59529. csg.matrix = matrix;
  59530. csg.position = meshPosition;
  59531. csg.rotation = meshRotation;
  59532. csg.scaling = meshScaling;
  59533. csg.rotationQuaternion = meshRotationQuaternion;
  59534. currentCSGMeshId++;
  59535. return csg;
  59536. };
  59537. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  59538. CSG.FromPolygons = function (polygons) {
  59539. var csg = new CSG();
  59540. csg.polygons = polygons;
  59541. return csg;
  59542. };
  59543. CSG.prototype.clone = function () {
  59544. var csg = new CSG();
  59545. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  59546. csg.copyTransformAttributes(this);
  59547. return csg;
  59548. };
  59549. CSG.prototype.toPolygons = function () {
  59550. return this.polygons;
  59551. };
  59552. CSG.prototype.union = function (csg) {
  59553. var a = new Node(this.clone().polygons);
  59554. var b = new Node(csg.clone().polygons);
  59555. a.clipTo(b);
  59556. b.clipTo(a);
  59557. b.invert();
  59558. b.clipTo(a);
  59559. b.invert();
  59560. a.build(b.allPolygons());
  59561. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  59562. };
  59563. CSG.prototype.unionInPlace = function (csg) {
  59564. var a = new Node(this.polygons);
  59565. var b = new Node(csg.polygons);
  59566. a.clipTo(b);
  59567. b.clipTo(a);
  59568. b.invert();
  59569. b.clipTo(a);
  59570. b.invert();
  59571. a.build(b.allPolygons());
  59572. this.polygons = a.allPolygons();
  59573. };
  59574. CSG.prototype.subtract = function (csg) {
  59575. var a = new Node(this.clone().polygons);
  59576. var b = new Node(csg.clone().polygons);
  59577. a.invert();
  59578. a.clipTo(b);
  59579. b.clipTo(a);
  59580. b.invert();
  59581. b.clipTo(a);
  59582. b.invert();
  59583. a.build(b.allPolygons());
  59584. a.invert();
  59585. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  59586. };
  59587. CSG.prototype.subtractInPlace = function (csg) {
  59588. var a = new Node(this.polygons);
  59589. var b = new Node(csg.polygons);
  59590. a.invert();
  59591. a.clipTo(b);
  59592. b.clipTo(a);
  59593. b.invert();
  59594. b.clipTo(a);
  59595. b.invert();
  59596. a.build(b.allPolygons());
  59597. a.invert();
  59598. this.polygons = a.allPolygons();
  59599. };
  59600. CSG.prototype.intersect = function (csg) {
  59601. var a = new Node(this.clone().polygons);
  59602. var b = new Node(csg.clone().polygons);
  59603. a.invert();
  59604. b.clipTo(a);
  59605. b.invert();
  59606. a.clipTo(b);
  59607. b.clipTo(a);
  59608. a.build(b.allPolygons());
  59609. a.invert();
  59610. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  59611. };
  59612. CSG.prototype.intersectInPlace = function (csg) {
  59613. var a = new Node(this.polygons);
  59614. var b = new Node(csg.polygons);
  59615. a.invert();
  59616. b.clipTo(a);
  59617. b.invert();
  59618. a.clipTo(b);
  59619. b.clipTo(a);
  59620. a.build(b.allPolygons());
  59621. a.invert();
  59622. this.polygons = a.allPolygons();
  59623. };
  59624. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  59625. // not modified.
  59626. CSG.prototype.inverse = function () {
  59627. var csg = this.clone();
  59628. csg.inverseInPlace();
  59629. return csg;
  59630. };
  59631. CSG.prototype.inverseInPlace = function () {
  59632. this.polygons.map(function (p) { p.flip(); });
  59633. };
  59634. // This is used to keep meshes transformations so they can be restored
  59635. // when we build back a Babylon Mesh
  59636. // NB : All CSG operations are performed in world coordinates
  59637. CSG.prototype.copyTransformAttributes = function (csg) {
  59638. this.matrix = csg.matrix;
  59639. this.position = csg.position;
  59640. this.rotation = csg.rotation;
  59641. this.scaling = csg.scaling;
  59642. this.rotationQuaternion = csg.rotationQuaternion;
  59643. return this;
  59644. };
  59645. // Build Raw mesh from CSG
  59646. // Coordinates here are in world space
  59647. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  59648. var matrix = this.matrix.clone();
  59649. matrix.invert();
  59650. 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;
  59651. if (keepSubMeshes) {
  59652. // Sort Polygons, since subMeshes are indices range
  59653. polygons.sort(function (a, b) {
  59654. if (a.shared.meshId === b.shared.meshId) {
  59655. return a.shared.subMeshId - b.shared.subMeshId;
  59656. }
  59657. else {
  59658. return a.shared.meshId - b.shared.meshId;
  59659. }
  59660. });
  59661. }
  59662. for (var i = 0, il = polygons.length; i < il; i++) {
  59663. polygon = polygons[i];
  59664. // Building SubMeshes
  59665. if (!subMesh_dict[polygon.shared.meshId]) {
  59666. subMesh_dict[polygon.shared.meshId] = {};
  59667. }
  59668. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  59669. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  59670. indexStart: +Infinity,
  59671. indexEnd: -Infinity,
  59672. materialIndex: polygon.shared.materialIndex
  59673. };
  59674. }
  59675. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  59676. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  59677. polygonIndices[0] = 0;
  59678. polygonIndices[1] = j - 1;
  59679. polygonIndices[2] = j;
  59680. for (var k = 0; k < 3; k++) {
  59681. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  59682. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  59683. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  59684. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  59685. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  59686. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  59687. // Check if 2 points can be merged
  59688. if (!(typeof vertex_idx !== 'undefined' &&
  59689. normals[vertex_idx * 3] === localNormal.x &&
  59690. normals[vertex_idx * 3 + 1] === localNormal.y &&
  59691. normals[vertex_idx * 3 + 2] === localNormal.z &&
  59692. uvs[vertex_idx * 2] === uv.x &&
  59693. uvs[vertex_idx * 2 + 1] === uv.y)) {
  59694. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  59695. uvs.push(uv.x, uv.y);
  59696. normals.push(normal.x, normal.y, normal.z);
  59697. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  59698. }
  59699. indices.push(vertex_idx);
  59700. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  59701. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  59702. currentIndex++;
  59703. }
  59704. }
  59705. }
  59706. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  59707. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  59708. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  59709. mesh.setIndices(indices);
  59710. if (keepSubMeshes) {
  59711. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  59712. var materialIndexOffset = 0, materialMaxIndex;
  59713. mesh.subMeshes = new Array();
  59714. for (var m in subMesh_dict) {
  59715. materialMaxIndex = -1;
  59716. for (var sm in subMesh_dict[m]) {
  59717. subMesh_obj = subMesh_dict[m][sm];
  59718. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  59719. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  59720. }
  59721. materialIndexOffset += ++materialMaxIndex;
  59722. }
  59723. }
  59724. return mesh;
  59725. };
  59726. // Build Mesh from CSG taking material and transforms into account
  59727. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  59728. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  59729. mesh.material = material;
  59730. mesh.position.copyFrom(this.position);
  59731. mesh.rotation.copyFrom(this.rotation);
  59732. if (this.rotationQuaternion) {
  59733. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  59734. }
  59735. mesh.scaling.copyFrom(this.scaling);
  59736. mesh.computeWorldMatrix(true);
  59737. return mesh;
  59738. };
  59739. return CSG;
  59740. }());
  59741. BABYLON.CSG = CSG;
  59742. })(BABYLON || (BABYLON = {}));
  59743. //# sourceMappingURL=babylon.csg.js.map
  59744. var BABYLON;
  59745. (function (BABYLON) {
  59746. var LensFlare = (function () {
  59747. function LensFlare(size, position, color, imgUrl, system) {
  59748. this.size = size;
  59749. this.position = position;
  59750. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  59751. this.dispose = function () {
  59752. if (this.texture) {
  59753. this.texture.dispose();
  59754. }
  59755. // Remove from scene
  59756. var index = this._system.lensFlares.indexOf(this);
  59757. this._system.lensFlares.splice(index, 1);
  59758. };
  59759. this.color = color || new BABYLON.Color3(1, 1, 1);
  59760. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  59761. this._system = system;
  59762. system.lensFlares.push(this);
  59763. }
  59764. return LensFlare;
  59765. }());
  59766. BABYLON.LensFlare = LensFlare;
  59767. })(BABYLON || (BABYLON = {}));
  59768. //# sourceMappingURL=babylon.lensFlare.js.map
  59769. var BABYLON;
  59770. (function (BABYLON) {
  59771. var LensFlareSystem = (function () {
  59772. function LensFlareSystem(name, emitter, scene) {
  59773. this.name = name;
  59774. this.lensFlares = new Array();
  59775. this.borderLimit = 300;
  59776. this.viewportBorder = 0;
  59777. this.layerMask = 0x0FFFFFFF;
  59778. this._vertexBuffers = {};
  59779. this._isEnabled = true;
  59780. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  59781. this._emitter = emitter;
  59782. this.id = name;
  59783. scene.lensFlareSystems.push(this);
  59784. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  59785. var engine = scene.getEngine();
  59786. // VBO
  59787. var vertices = [];
  59788. vertices.push(1, 1);
  59789. vertices.push(-1, 1);
  59790. vertices.push(-1, -1);
  59791. vertices.push(1, -1);
  59792. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  59793. // Indices
  59794. var indices = [];
  59795. indices.push(0);
  59796. indices.push(1);
  59797. indices.push(2);
  59798. indices.push(0);
  59799. indices.push(2);
  59800. indices.push(3);
  59801. this._indexBuffer = engine.createIndexBuffer(indices);
  59802. // Effects
  59803. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  59804. }
  59805. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  59806. get: function () {
  59807. return this._isEnabled;
  59808. },
  59809. set: function (value) {
  59810. this._isEnabled = value;
  59811. },
  59812. enumerable: true,
  59813. configurable: true
  59814. });
  59815. LensFlareSystem.prototype.getScene = function () {
  59816. return this._scene;
  59817. };
  59818. LensFlareSystem.prototype.getEmitter = function () {
  59819. return this._emitter;
  59820. };
  59821. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  59822. this._emitter = newEmitter;
  59823. };
  59824. LensFlareSystem.prototype.getEmitterPosition = function () {
  59825. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  59826. };
  59827. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  59828. var position = this.getEmitterPosition();
  59829. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  59830. this._positionX = position.x;
  59831. this._positionY = position.y;
  59832. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  59833. if (this.viewportBorder > 0) {
  59834. globalViewport.x -= this.viewportBorder;
  59835. globalViewport.y -= this.viewportBorder;
  59836. globalViewport.width += this.viewportBorder * 2;
  59837. globalViewport.height += this.viewportBorder * 2;
  59838. position.x += this.viewportBorder;
  59839. position.y += this.viewportBorder;
  59840. this._positionX += this.viewportBorder;
  59841. this._positionY += this.viewportBorder;
  59842. }
  59843. if (position.z > 0) {
  59844. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  59845. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  59846. return true;
  59847. }
  59848. return true;
  59849. }
  59850. return false;
  59851. };
  59852. LensFlareSystem.prototype._isVisible = function () {
  59853. if (!this._isEnabled) {
  59854. return false;
  59855. }
  59856. var emitterPosition = this.getEmitterPosition();
  59857. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  59858. var distance = direction.length();
  59859. direction.normalize();
  59860. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  59861. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  59862. return !pickInfo.hit || pickInfo.distance > distance;
  59863. };
  59864. LensFlareSystem.prototype.render = function () {
  59865. if (!this._effect.isReady())
  59866. return false;
  59867. var engine = this._scene.getEngine();
  59868. var viewport = this._scene.activeCamera.viewport;
  59869. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  59870. // Position
  59871. if (!this.computeEffectivePosition(globalViewport)) {
  59872. return false;
  59873. }
  59874. // Visibility
  59875. if (!this._isVisible()) {
  59876. return false;
  59877. }
  59878. // Intensity
  59879. var awayX;
  59880. var awayY;
  59881. if (this._positionX < this.borderLimit + globalViewport.x) {
  59882. awayX = this.borderLimit + globalViewport.x - this._positionX;
  59883. }
  59884. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  59885. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  59886. }
  59887. else {
  59888. awayX = 0;
  59889. }
  59890. if (this._positionY < this.borderLimit + globalViewport.y) {
  59891. awayY = this.borderLimit + globalViewport.y - this._positionY;
  59892. }
  59893. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  59894. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  59895. }
  59896. else {
  59897. awayY = 0;
  59898. }
  59899. var away = (awayX > awayY) ? awayX : awayY;
  59900. away -= this.viewportBorder;
  59901. if (away > this.borderLimit) {
  59902. away = this.borderLimit;
  59903. }
  59904. var intensity = 1.0 - (away / this.borderLimit);
  59905. if (intensity < 0) {
  59906. return false;
  59907. }
  59908. if (intensity > 1.0) {
  59909. intensity = 1.0;
  59910. }
  59911. if (this.viewportBorder > 0) {
  59912. globalViewport.x += this.viewportBorder;
  59913. globalViewport.y += this.viewportBorder;
  59914. globalViewport.width -= this.viewportBorder * 2;
  59915. globalViewport.height -= this.viewportBorder * 2;
  59916. this._positionX -= this.viewportBorder;
  59917. this._positionY -= this.viewportBorder;
  59918. }
  59919. // Position
  59920. var centerX = globalViewport.x + globalViewport.width / 2;
  59921. var centerY = globalViewport.y + globalViewport.height / 2;
  59922. var distX = centerX - this._positionX;
  59923. var distY = centerY - this._positionY;
  59924. // Effects
  59925. engine.enableEffect(this._effect);
  59926. engine.setState(false);
  59927. engine.setDepthBuffer(false);
  59928. // VBOs
  59929. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  59930. // Flares
  59931. for (var index = 0; index < this.lensFlares.length; index++) {
  59932. var flare = this.lensFlares[index];
  59933. engine.setAlphaMode(flare.alphaMode);
  59934. var x = centerX - (distX * flare.position);
  59935. var y = centerY - (distY * flare.position);
  59936. var cw = flare.size;
  59937. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  59938. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  59939. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  59940. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  59941. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  59942. // Texture
  59943. this._effect.setTexture("textureSampler", flare.texture);
  59944. // Color
  59945. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  59946. // Draw order
  59947. engine.draw(true, 0, 6);
  59948. }
  59949. engine.setDepthBuffer(true);
  59950. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  59951. return true;
  59952. };
  59953. LensFlareSystem.prototype.dispose = function () {
  59954. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  59955. if (vertexBuffer) {
  59956. vertexBuffer.dispose();
  59957. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  59958. }
  59959. if (this._indexBuffer) {
  59960. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  59961. this._indexBuffer = null;
  59962. }
  59963. while (this.lensFlares.length) {
  59964. this.lensFlares[0].dispose();
  59965. }
  59966. // Remove from scene
  59967. var index = this._scene.lensFlareSystems.indexOf(this);
  59968. this._scene.lensFlareSystems.splice(index, 1);
  59969. };
  59970. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  59971. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  59972. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  59973. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  59974. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  59975. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  59976. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  59977. var parsedFlare = parsedLensFlareSystem.flares[index];
  59978. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  59979. }
  59980. return lensFlareSystem;
  59981. };
  59982. LensFlareSystem.prototype.serialize = function () {
  59983. var serializationObject = {};
  59984. serializationObject.id = this.id;
  59985. serializationObject.name = this.name;
  59986. serializationObject.emitterId = this.getEmitter().id;
  59987. serializationObject.borderLimit = this.borderLimit;
  59988. serializationObject.flares = [];
  59989. for (var index = 0; index < this.lensFlares.length; index++) {
  59990. var flare = this.lensFlares[index];
  59991. serializationObject.flares.push({
  59992. size: flare.size,
  59993. position: flare.position,
  59994. color: flare.color.asArray(),
  59995. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  59996. });
  59997. }
  59998. return serializationObject;
  59999. };
  60000. return LensFlareSystem;
  60001. }());
  60002. BABYLON.LensFlareSystem = LensFlareSystem;
  60003. })(BABYLON || (BABYLON = {}));
  60004. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  60005. var BABYLON;
  60006. (function (BABYLON) {
  60007. /**
  60008. * This is a holder class for the physics joint created by the physics plugin.
  60009. * It holds a set of functions to control the underlying joint.
  60010. */
  60011. var PhysicsJoint = (function () {
  60012. function PhysicsJoint(type, jointData) {
  60013. this.type = type;
  60014. this.jointData = jointData;
  60015. jointData.nativeParams = jointData.nativeParams || {};
  60016. }
  60017. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  60018. get: function () {
  60019. return this._physicsJoint;
  60020. },
  60021. set: function (newJoint) {
  60022. if (this._physicsJoint) {
  60023. //remove from the wolrd
  60024. }
  60025. this._physicsJoint = newJoint;
  60026. },
  60027. enumerable: true,
  60028. configurable: true
  60029. });
  60030. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  60031. set: function (physicsPlugin) {
  60032. this._physicsPlugin = physicsPlugin;
  60033. },
  60034. enumerable: true,
  60035. configurable: true
  60036. });
  60037. /**
  60038. * Execute a function that is physics-plugin specific.
  60039. * @param {Function} func the function that will be executed.
  60040. * It accepts two parameters: the physics world and the physics joint.
  60041. */
  60042. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  60043. func(this._physicsPlugin.world, this._physicsJoint);
  60044. };
  60045. //TODO check if the native joints are the same
  60046. //Joint Types
  60047. PhysicsJoint.DistanceJoint = 0;
  60048. PhysicsJoint.HingeJoint = 1;
  60049. PhysicsJoint.BallAndSocketJoint = 2;
  60050. PhysicsJoint.WheelJoint = 3;
  60051. PhysicsJoint.SliderJoint = 4;
  60052. //OIMO
  60053. PhysicsJoint.PrismaticJoint = 5;
  60054. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  60055. PhysicsJoint.UniversalJoint = 6;
  60056. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  60057. //Cannon
  60058. //Similar to a Ball-Joint. Different in params
  60059. PhysicsJoint.PointToPointJoint = 8;
  60060. //Cannon only at the moment
  60061. PhysicsJoint.SpringJoint = 9;
  60062. PhysicsJoint.LockJoint = 10;
  60063. return PhysicsJoint;
  60064. }());
  60065. BABYLON.PhysicsJoint = PhysicsJoint;
  60066. /**
  60067. * A class representing a physics distance joint.
  60068. */
  60069. var DistanceJoint = (function (_super) {
  60070. __extends(DistanceJoint, _super);
  60071. function DistanceJoint(jointData) {
  60072. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  60073. }
  60074. /**
  60075. * Update the predefined distance.
  60076. */
  60077. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  60078. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  60079. };
  60080. return DistanceJoint;
  60081. }(PhysicsJoint));
  60082. BABYLON.DistanceJoint = DistanceJoint;
  60083. var MotorEnabledJoint = (function (_super) {
  60084. __extends(MotorEnabledJoint, _super);
  60085. function MotorEnabledJoint(type, jointData) {
  60086. return _super.call(this, type, jointData) || this;
  60087. }
  60088. /**
  60089. * Set the motor values.
  60090. * Attention, this function is plugin specific. Engines won't react 100% the same.
  60091. * @param {number} force the force to apply
  60092. * @param {number} maxForce max force for this motor.
  60093. */
  60094. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  60095. this._physicsPlugin.setMotor(this, force, maxForce);
  60096. };
  60097. /**
  60098. * Set the motor's limits.
  60099. * Attention, this function is plugin specific. Engines won't react 100% the same.
  60100. */
  60101. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  60102. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  60103. };
  60104. return MotorEnabledJoint;
  60105. }(PhysicsJoint));
  60106. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  60107. /**
  60108. * This class represents a single hinge physics joint
  60109. */
  60110. var HingeJoint = (function (_super) {
  60111. __extends(HingeJoint, _super);
  60112. function HingeJoint(jointData) {
  60113. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  60114. }
  60115. /**
  60116. * Set the motor values.
  60117. * Attention, this function is plugin specific. Engines won't react 100% the same.
  60118. * @param {number} force the force to apply
  60119. * @param {number} maxForce max force for this motor.
  60120. */
  60121. HingeJoint.prototype.setMotor = function (force, maxForce) {
  60122. this._physicsPlugin.setMotor(this, force, maxForce);
  60123. };
  60124. /**
  60125. * Set the motor's limits.
  60126. * Attention, this function is plugin specific. Engines won't react 100% the same.
  60127. */
  60128. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  60129. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  60130. };
  60131. return HingeJoint;
  60132. }(MotorEnabledJoint));
  60133. BABYLON.HingeJoint = HingeJoint;
  60134. /**
  60135. * This class represents a dual hinge physics joint (same as wheel joint)
  60136. */
  60137. var Hinge2Joint = (function (_super) {
  60138. __extends(Hinge2Joint, _super);
  60139. function Hinge2Joint(jointData) {
  60140. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  60141. }
  60142. /**
  60143. * Set the motor values.
  60144. * Attention, this function is plugin specific. Engines won't react 100% the same.
  60145. * @param {number} force the force to apply
  60146. * @param {number} maxForce max force for this motor.
  60147. * @param {motorIndex} the motor's index, 0 or 1.
  60148. */
  60149. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  60150. if (motorIndex === void 0) { motorIndex = 0; }
  60151. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  60152. };
  60153. /**
  60154. * Set the motor limits.
  60155. * Attention, this function is plugin specific. Engines won't react 100% the same.
  60156. * @param {number} upperLimit the upper limit
  60157. * @param {number} lowerLimit lower limit
  60158. * @param {motorIndex} the motor's index, 0 or 1.
  60159. */
  60160. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  60161. if (motorIndex === void 0) { motorIndex = 0; }
  60162. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  60163. };
  60164. return Hinge2Joint;
  60165. }(MotorEnabledJoint));
  60166. BABYLON.Hinge2Joint = Hinge2Joint;
  60167. })(BABYLON || (BABYLON = {}));
  60168. //# sourceMappingURL=babylon.physicsJoint.js.map
  60169. var BABYLON;
  60170. (function (BABYLON) {
  60171. var PhysicsImpostor = (function () {
  60172. function PhysicsImpostor(object, type, _options, _scene) {
  60173. if (_options === void 0) { _options = { mass: 0 }; }
  60174. var _this = this;
  60175. this.object = object;
  60176. this.type = type;
  60177. this._options = _options;
  60178. this._scene = _scene;
  60179. this._bodyUpdateRequired = false;
  60180. this._onBeforePhysicsStepCallbacks = new Array();
  60181. this._onAfterPhysicsStepCallbacks = new Array();
  60182. this._onPhysicsCollideCallbacks = [];
  60183. this._deltaPosition = BABYLON.Vector3.Zero();
  60184. this._isDisposed = false;
  60185. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  60186. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  60187. /**
  60188. * this function is executed by the physics engine.
  60189. */
  60190. this.beforeStep = function () {
  60191. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  60192. //conjugate deltaRotation
  60193. if (_this._deltaRotationConjugated) {
  60194. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  60195. }
  60196. else {
  60197. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  60198. }
  60199. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  60200. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  60201. func(_this);
  60202. });
  60203. };
  60204. /**
  60205. * this function is executed by the physics engine.
  60206. */
  60207. this.afterStep = function () {
  60208. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  60209. func(_this);
  60210. });
  60211. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  60212. _this.object.position.addInPlace(_this._deltaPosition);
  60213. if (_this._deltaRotation) {
  60214. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  60215. }
  60216. };
  60217. /**
  60218. * Legacy collision detection event support
  60219. */
  60220. this.onCollideEvent = null;
  60221. //event and body object due to cannon's event-based architecture.
  60222. this.onCollide = function (e) {
  60223. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  60224. return;
  60225. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  60226. if (otherImpostor) {
  60227. // Legacy collision detection event support
  60228. if (_this.onCollideEvent) {
  60229. _this.onCollideEvent(_this, otherImpostor);
  60230. }
  60231. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  60232. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  60233. }).forEach(function (obj) {
  60234. obj.callback(_this, otherImpostor);
  60235. });
  60236. }
  60237. };
  60238. //sanity check!
  60239. if (!this.object) {
  60240. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  60241. return;
  60242. }
  60243. //legacy support for old syntax.
  60244. if (!this._scene && object.getScene) {
  60245. this._scene = object.getScene();
  60246. }
  60247. this._physicsEngine = this._scene.getPhysicsEngine();
  60248. if (!this._physicsEngine) {
  60249. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  60250. }
  60251. else {
  60252. //set the object's quaternion, if not set
  60253. if (!this.object.rotationQuaternion) {
  60254. if (this.object.rotation) {
  60255. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  60256. }
  60257. else {
  60258. this.object.rotationQuaternion = new BABYLON.Quaternion();
  60259. }
  60260. }
  60261. //default options params
  60262. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  60263. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  60264. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  60265. this._joints = [];
  60266. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  60267. if (!this.object.parent) {
  60268. this._init();
  60269. }
  60270. else if (this.object.parent.physicsImpostor) {
  60271. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  60272. }
  60273. }
  60274. }
  60275. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  60276. get: function () {
  60277. return this._isDisposed;
  60278. },
  60279. enumerable: true,
  60280. configurable: true
  60281. });
  60282. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  60283. get: function () {
  60284. return this._physicsEngine.getPhysicsPlugin().getBodyMass(this);
  60285. },
  60286. set: function (value) {
  60287. this.setMass(value);
  60288. },
  60289. enumerable: true,
  60290. configurable: true
  60291. });
  60292. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  60293. get: function () {
  60294. return this._physicsEngine.getPhysicsPlugin().getBodyFriction(this);
  60295. },
  60296. set: function (value) {
  60297. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  60298. },
  60299. enumerable: true,
  60300. configurable: true
  60301. });
  60302. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  60303. get: function () {
  60304. return this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this);
  60305. },
  60306. set: function (value) {
  60307. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  60308. },
  60309. enumerable: true,
  60310. configurable: true
  60311. });
  60312. /**
  60313. * This function will completly initialize this impostor.
  60314. * It will create a new body - but only if this mesh has no parent.
  60315. * If it has, this impostor will not be used other than to define the impostor
  60316. * of the child mesh.
  60317. */
  60318. PhysicsImpostor.prototype._init = function () {
  60319. this._physicsEngine.removeImpostor(this);
  60320. this.physicsBody = null;
  60321. this._parent = this._parent || this._getPhysicsParent();
  60322. if (!this.parent) {
  60323. this._physicsEngine.addImpostor(this);
  60324. }
  60325. };
  60326. PhysicsImpostor.prototype._getPhysicsParent = function () {
  60327. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  60328. var parentMesh = this.object.parent;
  60329. return parentMesh.physicsImpostor;
  60330. }
  60331. return;
  60332. };
  60333. /**
  60334. * Should a new body be generated.
  60335. */
  60336. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  60337. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  60338. };
  60339. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  60340. this.forceUpdate();
  60341. };
  60342. /**
  60343. * Force a regeneration of this or the parent's impostor's body.
  60344. * Use under cautious - This will remove all joints already implemented.
  60345. */
  60346. PhysicsImpostor.prototype.forceUpdate = function () {
  60347. this._init();
  60348. if (this.parent) {
  60349. this.parent.forceUpdate();
  60350. }
  60351. };
  60352. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  60353. /*public get mesh(): AbstractMesh {
  60354. return this._mesh;
  60355. }*/
  60356. /**
  60357. * Gets the body that holds this impostor. Either its own, or its parent.
  60358. */
  60359. get: function () {
  60360. return this._parent ? this._parent.physicsBody : this._physicsBody;
  60361. },
  60362. /**
  60363. * Set the physics body. Used mainly by the physics engine/plugin
  60364. */
  60365. set: function (physicsBody) {
  60366. if (this._physicsBody) {
  60367. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  60368. }
  60369. this._physicsBody = physicsBody;
  60370. this.resetUpdateFlags();
  60371. },
  60372. enumerable: true,
  60373. configurable: true
  60374. });
  60375. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  60376. get: function () {
  60377. return this._parent;
  60378. },
  60379. set: function (value) {
  60380. this._parent = value;
  60381. },
  60382. enumerable: true,
  60383. configurable: true
  60384. });
  60385. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  60386. this._bodyUpdateRequired = false;
  60387. };
  60388. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  60389. if (this.object.getBoundingInfo) {
  60390. var q = this.object.rotationQuaternion;
  60391. //reset rotation
  60392. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  60393. //calculate the world matrix with no rotation
  60394. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  60395. var size = this.object.getBoundingInfo().boundingBox.extendSizeWorld.scale(2);
  60396. //bring back the rotation
  60397. this.object.rotationQuaternion = q;
  60398. //calculate the world matrix with the new rotation
  60399. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  60400. return size;
  60401. }
  60402. else {
  60403. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  60404. }
  60405. };
  60406. PhysicsImpostor.prototype.getObjectCenter = function () {
  60407. if (this.object.getBoundingInfo) {
  60408. return this.object.getBoundingInfo().boundingBox.centerWorld;
  60409. }
  60410. else {
  60411. return this.object.position;
  60412. }
  60413. };
  60414. /**
  60415. * Get a specific parametes from the options parameter.
  60416. */
  60417. PhysicsImpostor.prototype.getParam = function (paramName) {
  60418. return this._options[paramName];
  60419. };
  60420. /**
  60421. * Sets a specific parameter in the options given to the physics plugin
  60422. */
  60423. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  60424. this._options[paramName] = value;
  60425. this._bodyUpdateRequired = true;
  60426. };
  60427. /**
  60428. * Specifically change the body's mass option. Won't recreate the physics body object
  60429. */
  60430. PhysicsImpostor.prototype.setMass = function (mass) {
  60431. if (this.getParam("mass") !== mass) {
  60432. this.setParam("mass", mass);
  60433. }
  60434. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  60435. };
  60436. PhysicsImpostor.prototype.getLinearVelocity = function () {
  60437. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  60438. };
  60439. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  60440. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  60441. };
  60442. PhysicsImpostor.prototype.getAngularVelocity = function () {
  60443. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  60444. };
  60445. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  60446. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  60447. };
  60448. /**
  60449. * Execute a function with the physics plugin native code.
  60450. * Provide a function the will have two variables - the world object and the physics body object.
  60451. */
  60452. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  60453. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  60454. };
  60455. /**
  60456. * Register a function that will be executed before the physics world is stepping forward.
  60457. */
  60458. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  60459. this._onBeforePhysicsStepCallbacks.push(func);
  60460. };
  60461. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  60462. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  60463. if (index > -1) {
  60464. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  60465. }
  60466. else {
  60467. BABYLON.Tools.Warn("Function to remove was not found");
  60468. }
  60469. };
  60470. /**
  60471. * Register a function that will be executed after the physics step
  60472. */
  60473. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  60474. this._onAfterPhysicsStepCallbacks.push(func);
  60475. };
  60476. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  60477. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  60478. if (index > -1) {
  60479. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  60480. }
  60481. else {
  60482. BABYLON.Tools.Warn("Function to remove was not found");
  60483. }
  60484. };
  60485. /**
  60486. * register a function that will be executed when this impostor collides against a different body.
  60487. */
  60488. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  60489. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  60490. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  60491. };
  60492. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  60493. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  60494. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  60495. if (index > -1) {
  60496. this._onPhysicsCollideCallbacks.splice(index, 1);
  60497. }
  60498. else {
  60499. BABYLON.Tools.Warn("Function to remove was not found");
  60500. }
  60501. };
  60502. /**
  60503. * Apply a force
  60504. */
  60505. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  60506. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  60507. };
  60508. /**
  60509. * Apply an impulse
  60510. */
  60511. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  60512. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  60513. };
  60514. /**
  60515. * A help function to create a joint.
  60516. */
  60517. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  60518. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  60519. this.addJoint(otherImpostor, joint);
  60520. };
  60521. /**
  60522. * Add a joint to this impostor with a different impostor.
  60523. */
  60524. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  60525. this._joints.push({
  60526. otherImpostor: otherImpostor,
  60527. joint: joint
  60528. });
  60529. this._physicsEngine.addJoint(this, otherImpostor, joint);
  60530. };
  60531. /**
  60532. * Will keep this body still, in a sleep mode.
  60533. */
  60534. PhysicsImpostor.prototype.sleep = function () {
  60535. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  60536. };
  60537. /**
  60538. * Wake the body up.
  60539. */
  60540. PhysicsImpostor.prototype.wakeUp = function () {
  60541. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  60542. };
  60543. PhysicsImpostor.prototype.clone = function (newObject) {
  60544. if (!newObject)
  60545. return null;
  60546. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  60547. };
  60548. PhysicsImpostor.prototype.dispose = function () {
  60549. var _this = this;
  60550. //no dispose if no physics engine is available.
  60551. if (!this._physicsEngine) {
  60552. return;
  60553. }
  60554. this._joints.forEach(function (j) {
  60555. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  60556. });
  60557. //dispose the physics body
  60558. this._physicsEngine.removeImpostor(this);
  60559. if (this.parent) {
  60560. this.parent.forceUpdate();
  60561. }
  60562. else {
  60563. /*this._object.getChildMeshes().forEach(function(mesh) {
  60564. if (mesh.physicsImpostor) {
  60565. if (disposeChildren) {
  60566. mesh.physicsImpostor.dispose();
  60567. mesh.physicsImpostor = null;
  60568. }
  60569. }
  60570. })*/
  60571. }
  60572. this._isDisposed = true;
  60573. };
  60574. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  60575. this._deltaPosition.copyFrom(position);
  60576. };
  60577. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  60578. if (!this._deltaRotation) {
  60579. this._deltaRotation = new BABYLON.Quaternion();
  60580. }
  60581. this._deltaRotation.copyFrom(rotation);
  60582. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  60583. };
  60584. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  60585. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  60586. };
  60587. PhysicsImpostor.prototype.getRadius = function () {
  60588. return this._physicsEngine.getPhysicsPlugin().getRadius(this);
  60589. };
  60590. /**
  60591. * Sync a bone with this impostor
  60592. * @param bone The bone to sync to the impostor.
  60593. * @param boneMesh The mesh that the bone is influencing.
  60594. * @param jointPivot The pivot of the joint / bone in local space.
  60595. * @param distToJoint Optional distance from the impostor to the joint.
  60596. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  60597. */
  60598. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  60599. var tempVec = PhysicsImpostor._tmpVecs[0];
  60600. var mesh = this.object;
  60601. if (adjustRotation) {
  60602. var tempQuat = PhysicsImpostor._tmpQuat;
  60603. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  60604. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  60605. }
  60606. else {
  60607. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  60608. }
  60609. tempVec.x = 0;
  60610. tempVec.y = 0;
  60611. tempVec.z = 0;
  60612. if (jointPivot) {
  60613. tempVec.x = jointPivot.x;
  60614. tempVec.y = jointPivot.y;
  60615. tempVec.z = jointPivot.z;
  60616. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  60617. if (distToJoint === undefined || distToJoint === null) {
  60618. distToJoint = jointPivot.length();
  60619. }
  60620. tempVec.x *= distToJoint;
  60621. tempVec.y *= distToJoint;
  60622. tempVec.z *= distToJoint;
  60623. }
  60624. if (bone.getParent()) {
  60625. tempVec.addInPlace(mesh.getAbsolutePosition());
  60626. bone.setAbsolutePosition(tempVec, boneMesh);
  60627. }
  60628. else {
  60629. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  60630. boneMesh.position.x -= tempVec.x;
  60631. boneMesh.position.y -= tempVec.y;
  60632. boneMesh.position.z -= tempVec.z;
  60633. }
  60634. };
  60635. /**
  60636. * Sync impostor to a bone
  60637. * @param bone The bone that the impostor will be synced to.
  60638. * @param boneMesh The mesh that the bone is influencing.
  60639. * @param jointPivot The pivot of the joint / bone in local space.
  60640. * @param distToJoint Optional distance from the impostor to the joint.
  60641. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  60642. * @param boneAxis Optional vector3 axis the bone is aligned with
  60643. */
  60644. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  60645. var mesh = this.object;
  60646. if (adjustRotation) {
  60647. var tempQuat = PhysicsImpostor._tmpQuat;
  60648. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  60649. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  60650. }
  60651. else {
  60652. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  60653. }
  60654. var pos = PhysicsImpostor._tmpVecs[0];
  60655. var boneDir = PhysicsImpostor._tmpVecs[1];
  60656. if (!boneAxis) {
  60657. boneAxis = PhysicsImpostor._tmpVecs[2];
  60658. boneAxis.x = 0;
  60659. boneAxis.y = 1;
  60660. boneAxis.z = 0;
  60661. }
  60662. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  60663. bone.getAbsolutePositionToRef(boneMesh, pos);
  60664. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  60665. distToJoint = jointPivot.length();
  60666. }
  60667. if (distToJoint !== undefined && distToJoint !== null) {
  60668. pos.x += boneDir.x * distToJoint;
  60669. pos.y += boneDir.y * distToJoint;
  60670. pos.z += boneDir.z * distToJoint;
  60671. }
  60672. mesh.setAbsolutePosition(pos);
  60673. };
  60674. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  60675. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  60676. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60677. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  60678. //Impostor types
  60679. PhysicsImpostor.NoImpostor = 0;
  60680. PhysicsImpostor.SphereImpostor = 1;
  60681. PhysicsImpostor.BoxImpostor = 2;
  60682. PhysicsImpostor.PlaneImpostor = 3;
  60683. PhysicsImpostor.MeshImpostor = 4;
  60684. PhysicsImpostor.CylinderImpostor = 7;
  60685. PhysicsImpostor.ParticleImpostor = 8;
  60686. PhysicsImpostor.HeightmapImpostor = 9;
  60687. return PhysicsImpostor;
  60688. }());
  60689. BABYLON.PhysicsImpostor = PhysicsImpostor;
  60690. })(BABYLON || (BABYLON = {}));
  60691. //# sourceMappingURL=babylon.physicsImpostor.js.map
  60692. var BABYLON;
  60693. (function (BABYLON) {
  60694. var PhysicsEngine = (function () {
  60695. function PhysicsEngine(gravity, _physicsPlugin) {
  60696. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  60697. this._physicsPlugin = _physicsPlugin;
  60698. //new methods and parameters
  60699. this._impostors = [];
  60700. this._joints = [];
  60701. if (!this._physicsPlugin.isSupported()) {
  60702. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  60703. + "Please make sure it is included.");
  60704. }
  60705. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  60706. this.setGravity(gravity);
  60707. this.setTimeStep();
  60708. }
  60709. PhysicsEngine.prototype.setGravity = function (gravity) {
  60710. this.gravity = gravity;
  60711. this._physicsPlugin.setGravity(this.gravity);
  60712. };
  60713. /**
  60714. * Set the time step of the physics engine.
  60715. * default is 1/60.
  60716. * To slow it down, enter 1/600 for example.
  60717. * To speed it up, 1/30
  60718. * @param {number} newTimeStep the new timestep to apply to this world.
  60719. */
  60720. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  60721. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  60722. this._physicsPlugin.setTimeStep(newTimeStep);
  60723. };
  60724. /**
  60725. * Get the time step of the physics engine.
  60726. */
  60727. PhysicsEngine.prototype.getTimeStep = function () {
  60728. return this._physicsPlugin.getTimeStep();
  60729. };
  60730. PhysicsEngine.prototype.dispose = function () {
  60731. this._impostors.forEach(function (impostor) {
  60732. impostor.dispose();
  60733. });
  60734. this._physicsPlugin.dispose();
  60735. };
  60736. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  60737. return this._physicsPlugin.name;
  60738. };
  60739. /**
  60740. * Adding a new impostor for the impostor tracking.
  60741. * This will be done by the impostor itself.
  60742. * @param {PhysicsImpostor} impostor the impostor to add
  60743. */
  60744. PhysicsEngine.prototype.addImpostor = function (impostor) {
  60745. impostor.uniqueId = this._impostors.push(impostor);
  60746. //if no parent, generate the body
  60747. if (!impostor.parent) {
  60748. this._physicsPlugin.generatePhysicsBody(impostor);
  60749. }
  60750. };
  60751. /**
  60752. * Remove an impostor from the engine.
  60753. * This impostor and its mesh will not longer be updated by the physics engine.
  60754. * @param {PhysicsImpostor} impostor the impostor to remove
  60755. */
  60756. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  60757. var index = this._impostors.indexOf(impostor);
  60758. if (index > -1) {
  60759. var removed = this._impostors.splice(index, 1);
  60760. //Is it needed?
  60761. if (removed.length) {
  60762. //this will also remove it from the world.
  60763. removed[0].physicsBody = null;
  60764. }
  60765. }
  60766. };
  60767. /**
  60768. * Add a joint to the physics engine
  60769. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  60770. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  60771. * @param {PhysicsJoint} the joint that will connect both impostors.
  60772. */
  60773. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  60774. var impostorJoint = {
  60775. mainImpostor: mainImpostor,
  60776. connectedImpostor: connectedImpostor,
  60777. joint: joint
  60778. };
  60779. joint.physicsPlugin = this._physicsPlugin;
  60780. this._joints.push(impostorJoint);
  60781. this._physicsPlugin.generateJoint(impostorJoint);
  60782. };
  60783. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  60784. var matchingJoints = this._joints.filter(function (impostorJoint) {
  60785. return (impostorJoint.connectedImpostor === connectedImpostor
  60786. && impostorJoint.joint === joint
  60787. && impostorJoint.mainImpostor === mainImpostor);
  60788. });
  60789. if (matchingJoints.length) {
  60790. this._physicsPlugin.removeJoint(matchingJoints[0]);
  60791. //TODO remove it from the list as well
  60792. }
  60793. };
  60794. /**
  60795. * Called by the scene. no need to call it.
  60796. */
  60797. PhysicsEngine.prototype._step = function (delta) {
  60798. var _this = this;
  60799. //check if any mesh has no body / requires an update
  60800. this._impostors.forEach(function (impostor) {
  60801. if (impostor.isBodyInitRequired()) {
  60802. _this._physicsPlugin.generatePhysicsBody(impostor);
  60803. }
  60804. });
  60805. if (delta > 0.1) {
  60806. delta = 0.1;
  60807. }
  60808. else if (delta <= 0) {
  60809. delta = 1.0 / 60.0;
  60810. }
  60811. this._physicsPlugin.executeStep(delta, this._impostors);
  60812. };
  60813. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  60814. return this._physicsPlugin;
  60815. };
  60816. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  60817. for (var i = 0; i < this._impostors.length; ++i) {
  60818. if (this._impostors[i].object === object) {
  60819. return this._impostors[i];
  60820. }
  60821. }
  60822. };
  60823. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  60824. for (var i = 0; i < this._impostors.length; ++i) {
  60825. if (this._impostors[i].physicsBody === body) {
  60826. return this._impostors[i];
  60827. }
  60828. }
  60829. };
  60830. // Statics
  60831. PhysicsEngine.Epsilon = 0.001;
  60832. return PhysicsEngine;
  60833. }());
  60834. BABYLON.PhysicsEngine = PhysicsEngine;
  60835. })(BABYLON || (BABYLON = {}));
  60836. //# sourceMappingURL=babylon.physicsEngine.js.map
  60837. var BABYLON;
  60838. (function (BABYLON) {
  60839. var CannonJSPlugin = (function () {
  60840. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  60841. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  60842. if (iterations === void 0) { iterations = 10; }
  60843. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  60844. this.name = "CannonJSPlugin";
  60845. this._physicsMaterials = [];
  60846. this._fixedTimeStep = 1 / 60;
  60847. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  60848. this._currentCollisionGroup = 2;
  60849. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  60850. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  60851. this._tmpPosition = BABYLON.Vector3.Zero();
  60852. this._tmpQuaternion = new BABYLON.Quaternion();
  60853. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  60854. this._tmpDeltaRotation = new BABYLON.Quaternion();
  60855. this._tmpUnityRotation = new BABYLON.Quaternion();
  60856. if (!this.isSupported()) {
  60857. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  60858. return;
  60859. }
  60860. this.world = new CANNON.World();
  60861. this.world.broadphase = new CANNON.NaiveBroadphase();
  60862. this.world.solver.iterations = iterations;
  60863. }
  60864. CannonJSPlugin.prototype.setGravity = function (gravity) {
  60865. this.world.gravity.copy(gravity);
  60866. };
  60867. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  60868. this._fixedTimeStep = timeStep;
  60869. };
  60870. CannonJSPlugin.prototype.getTimeStep = function () {
  60871. return this._fixedTimeStep;
  60872. };
  60873. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  60874. // Delta is in seconds, should be provided in milliseconds
  60875. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  60876. };
  60877. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  60878. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  60879. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  60880. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  60881. };
  60882. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  60883. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  60884. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  60885. impostor.physicsBody.applyForce(impulse, worldPoint);
  60886. };
  60887. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  60888. //parent-child relationship. Does this impostor has a parent impostor?
  60889. if (impostor.parent) {
  60890. if (impostor.physicsBody) {
  60891. this.removePhysicsBody(impostor);
  60892. //TODO is that needed?
  60893. impostor.forceUpdate();
  60894. }
  60895. return;
  60896. }
  60897. //should a new body be created for this impostor?
  60898. if (impostor.isBodyInitRequired()) {
  60899. var shape = this._createShape(impostor);
  60900. //unregister events, if body is being changed
  60901. var oldBody = impostor.physicsBody;
  60902. if (oldBody) {
  60903. this.removePhysicsBody(impostor);
  60904. }
  60905. //create the body and material
  60906. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  60907. var bodyCreationObject = {
  60908. mass: impostor.getParam("mass"),
  60909. material: material
  60910. };
  60911. // A simple extend, in case native options were used.
  60912. var nativeOptions = impostor.getParam("nativeOptions");
  60913. for (var key in nativeOptions) {
  60914. if (nativeOptions.hasOwnProperty(key)) {
  60915. bodyCreationObject[key] = nativeOptions[key];
  60916. }
  60917. }
  60918. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  60919. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  60920. this.world.addEventListener("preStep", impostor.beforeStep);
  60921. this.world.addEventListener("postStep", impostor.afterStep);
  60922. impostor.physicsBody.addShape(shape);
  60923. this.world.add(impostor.physicsBody);
  60924. //try to keep the body moving in the right direction by taking old properties.
  60925. //Should be tested!
  60926. if (oldBody) {
  60927. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  60928. impostor.physicsBody[param].copy(oldBody[param]);
  60929. });
  60930. }
  60931. this._processChildMeshes(impostor);
  60932. }
  60933. //now update the body's transformation
  60934. this._updatePhysicsBodyTransformation(impostor);
  60935. };
  60936. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  60937. var _this = this;
  60938. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  60939. if (meshChildren.length) {
  60940. var processMesh = function (localPosition, mesh) {
  60941. var childImpostor = mesh.getPhysicsImpostor();
  60942. if (childImpostor) {
  60943. var parent = childImpostor.parent;
  60944. if (parent !== mainImpostor) {
  60945. var localPosition = mesh.position;
  60946. if (childImpostor.physicsBody) {
  60947. _this.removePhysicsBody(childImpostor);
  60948. childImpostor.physicsBody = null;
  60949. }
  60950. childImpostor.parent = mainImpostor;
  60951. childImpostor.resetUpdateFlags();
  60952. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  60953. //Add the mass of the children.
  60954. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  60955. }
  60956. }
  60957. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  60958. };
  60959. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  60960. }
  60961. };
  60962. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  60963. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  60964. this.world.removeEventListener("preStep", impostor.beforeStep);
  60965. this.world.removeEventListener("postStep", impostor.afterStep);
  60966. this.world.remove(impostor.physicsBody);
  60967. };
  60968. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  60969. var mainBody = impostorJoint.mainImpostor.physicsBody;
  60970. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  60971. if (!mainBody || !connectedBody) {
  60972. return;
  60973. }
  60974. var constraint;
  60975. var jointData = impostorJoint.joint.jointData;
  60976. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  60977. var constraintData = {
  60978. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  60979. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  60980. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  60981. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  60982. maxForce: jointData.nativeParams.maxForce,
  60983. collideConnected: !!jointData.collision
  60984. };
  60985. switch (impostorJoint.joint.type) {
  60986. case BABYLON.PhysicsJoint.HingeJoint:
  60987. case BABYLON.PhysicsJoint.Hinge2Joint:
  60988. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  60989. break;
  60990. case BABYLON.PhysicsJoint.DistanceJoint:
  60991. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  60992. break;
  60993. case BABYLON.PhysicsJoint.SpringJoint:
  60994. var springData = jointData;
  60995. constraint = new CANNON.Spring(mainBody, connectedBody, {
  60996. restLength: springData.length,
  60997. stiffness: springData.stiffness,
  60998. damping: springData.damping,
  60999. localAnchorA: constraintData.pivotA,
  61000. localAnchorB: constraintData.pivotB
  61001. });
  61002. break;
  61003. case BABYLON.PhysicsJoint.LockJoint:
  61004. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  61005. break;
  61006. case BABYLON.PhysicsJoint.PointToPointJoint:
  61007. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  61008. default:
  61009. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  61010. break;
  61011. }
  61012. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  61013. constraint.collideConnected = !!jointData.collision;
  61014. impostorJoint.joint.physicsJoint = constraint;
  61015. //don't add spring as constraint, as it is not one.
  61016. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  61017. this.world.addConstraint(constraint);
  61018. }
  61019. else {
  61020. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  61021. constraint.applyForce();
  61022. });
  61023. }
  61024. };
  61025. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  61026. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  61027. };
  61028. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  61029. var index;
  61030. var mat;
  61031. for (index = 0; index < this._physicsMaterials.length; index++) {
  61032. mat = this._physicsMaterials[index];
  61033. if (mat.friction === friction && mat.restitution === restitution) {
  61034. return mat;
  61035. }
  61036. }
  61037. var currentMat = new CANNON.Material(name);
  61038. currentMat.friction = friction;
  61039. currentMat.restitution = restitution;
  61040. this._physicsMaterials.push(currentMat);
  61041. return currentMat;
  61042. };
  61043. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  61044. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  61045. };
  61046. CannonJSPlugin.prototype._createShape = function (impostor) {
  61047. var object = impostor.object;
  61048. var returnValue;
  61049. var extendSize = impostor.getObjectExtendSize();
  61050. switch (impostor.type) {
  61051. case BABYLON.PhysicsImpostor.SphereImpostor:
  61052. var radiusX = extendSize.x;
  61053. var radiusY = extendSize.y;
  61054. var radiusZ = extendSize.z;
  61055. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  61056. break;
  61057. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  61058. case BABYLON.PhysicsImpostor.CylinderImpostor:
  61059. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  61060. break;
  61061. case BABYLON.PhysicsImpostor.BoxImpostor:
  61062. var box = extendSize.scale(0.5);
  61063. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  61064. break;
  61065. case BABYLON.PhysicsImpostor.PlaneImpostor:
  61066. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  61067. returnValue = new CANNON.Plane();
  61068. break;
  61069. case BABYLON.PhysicsImpostor.MeshImpostor:
  61070. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  61071. var rawFaces = object.getIndices ? object.getIndices() : [];
  61072. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  61073. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  61074. break;
  61075. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  61076. returnValue = this._createHeightmap(object);
  61077. break;
  61078. case BABYLON.PhysicsImpostor.ParticleImpostor:
  61079. returnValue = new CANNON.Particle();
  61080. break;
  61081. }
  61082. return returnValue;
  61083. };
  61084. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  61085. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61086. var matrix = [];
  61087. //For now pointDepth will not be used and will be automatically calculated.
  61088. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  61089. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  61090. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSizeWorld.x, object.getBoundingInfo().boundingBox.extendSizeWorld.z);
  61091. var elementSize = dim * 2 / arraySize;
  61092. var minY = object.getBoundingInfo().boundingBox.extendSizeWorld.y;
  61093. for (var i = 0; i < pos.length; i = i + 3) {
  61094. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  61095. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  61096. var y = pos[i + 1] + minY;
  61097. if (!matrix[x]) {
  61098. matrix[x] = [];
  61099. }
  61100. if (!matrix[x][z]) {
  61101. matrix[x][z] = y;
  61102. }
  61103. matrix[x][z] = Math.max(y, matrix[x][z]);
  61104. }
  61105. for (var x = 0; x <= arraySize; ++x) {
  61106. if (!matrix[x]) {
  61107. var loc = 1;
  61108. while (!matrix[(x + loc) % arraySize]) {
  61109. loc++;
  61110. }
  61111. matrix[x] = matrix[(x + loc) % arraySize].slice();
  61112. //console.log("missing x", x);
  61113. }
  61114. for (var z = 0; z <= arraySize; ++z) {
  61115. if (!matrix[x][z]) {
  61116. var loc = 1;
  61117. var newValue;
  61118. while (newValue === undefined) {
  61119. newValue = matrix[x][(z + loc++) % arraySize];
  61120. }
  61121. matrix[x][z] = newValue;
  61122. }
  61123. }
  61124. }
  61125. var shape = new CANNON.Heightfield(matrix, {
  61126. elementSize: elementSize
  61127. });
  61128. //For future reference, needed for body transformation
  61129. shape.minY = minY;
  61130. return shape;
  61131. };
  61132. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  61133. var object = impostor.object;
  61134. //make sure it is updated...
  61135. object.computeWorldMatrix && object.computeWorldMatrix(true);
  61136. // The delta between the mesh position and the mesh bounding box center
  61137. var center = impostor.getObjectCenter();
  61138. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  61139. this._tmpPosition.copyFrom(center);
  61140. var quaternion = object.rotationQuaternion;
  61141. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  61142. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  61143. //-90 DEG in X, precalculated
  61144. quaternion = quaternion.multiply(this._minus90X);
  61145. //Invert! (Precalculated, 90 deg in X)
  61146. //No need to clone. this will never change.
  61147. impostor.setDeltaRotation(this._plus90X);
  61148. }
  61149. //If it is a heightfield, if should be centered.
  61150. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  61151. var mesh = object;
  61152. //calculate the correct body position:
  61153. var rotationQuaternion = mesh.rotationQuaternion;
  61154. mesh.rotationQuaternion = this._tmpUnityRotation;
  61155. mesh.computeWorldMatrix(true);
  61156. //get original center with no rotation
  61157. var c = center.clone();
  61158. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  61159. //rotation is back
  61160. mesh.rotationQuaternion = rotationQuaternion;
  61161. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  61162. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSizeWorld.x, 0, -mesh.getBoundingInfo().boundingBox.extendSizeWorld.z);
  61163. mesh.setPivotMatrix(p);
  61164. mesh.computeWorldMatrix(true);
  61165. //calculate the translation
  61166. var translation = mesh.getBoundingInfo().boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  61167. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSizeWorld.y, translation.z);
  61168. //add it inverted to the delta
  61169. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.centerWorld.subtract(c));
  61170. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSizeWorld.y;
  61171. mesh.setPivotMatrix(oldPivot);
  61172. mesh.computeWorldMatrix(true);
  61173. }
  61174. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  61175. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  61176. this._tmpPosition.copyFrom(object.position);
  61177. }
  61178. impostor.setDeltaPosition(this._tmpDeltaPosition);
  61179. //Now update the impostor object
  61180. impostor.physicsBody.position.copy(this._tmpPosition);
  61181. impostor.physicsBody.quaternion.copy(quaternion);
  61182. };
  61183. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  61184. impostor.object.position.copyFrom(impostor.physicsBody.position);
  61185. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  61186. };
  61187. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  61188. impostor.physicsBody.position.copy(newPosition);
  61189. impostor.physicsBody.quaternion.copy(newRotation);
  61190. };
  61191. CannonJSPlugin.prototype.isSupported = function () {
  61192. return window.CANNON !== undefined;
  61193. };
  61194. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  61195. impostor.physicsBody.velocity.copy(velocity);
  61196. };
  61197. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  61198. impostor.physicsBody.angularVelocity.copy(velocity);
  61199. };
  61200. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  61201. var v = impostor.physicsBody.velocity;
  61202. if (!v)
  61203. return null;
  61204. return new BABYLON.Vector3(v.x, v.y, v.z);
  61205. };
  61206. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  61207. var v = impostor.physicsBody.angularVelocity;
  61208. if (!v)
  61209. return null;
  61210. return new BABYLON.Vector3(v.x, v.y, v.z);
  61211. };
  61212. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  61213. impostor.physicsBody.mass = mass;
  61214. impostor.physicsBody.updateMassProperties();
  61215. };
  61216. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  61217. return impostor.physicsBody.mass;
  61218. };
  61219. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  61220. return impostor.physicsBody.material.friction;
  61221. };
  61222. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  61223. impostor.physicsBody.material.friction = friction;
  61224. };
  61225. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  61226. return impostor.physicsBody.material.restitution;
  61227. };
  61228. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  61229. impostor.physicsBody.material.restitution = restitution;
  61230. };
  61231. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  61232. impostor.physicsBody.sleep();
  61233. };
  61234. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  61235. impostor.physicsBody.wakeUp();
  61236. };
  61237. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  61238. joint.physicsJoint.distance = maxDistance;
  61239. };
  61240. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  61241. if (!motorIndex) {
  61242. joint.physicsJoint.enableMotor();
  61243. }
  61244. };
  61245. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  61246. if (!motorIndex) {
  61247. joint.physicsJoint.disableMotor();
  61248. }
  61249. };
  61250. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  61251. if (!motorIndex) {
  61252. joint.physicsJoint.enableMotor();
  61253. joint.physicsJoint.setMotorSpeed(speed);
  61254. if (maxForce) {
  61255. this.setLimit(joint, maxForce);
  61256. }
  61257. }
  61258. };
  61259. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  61260. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  61261. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  61262. };
  61263. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  61264. var body = impostor.physicsBody;
  61265. mesh.position.x = body.position.x;
  61266. mesh.position.y = body.position.y;
  61267. mesh.position.z = body.position.z;
  61268. mesh.rotationQuaternion.x = body.quaternion.x;
  61269. mesh.rotationQuaternion.y = body.quaternion.y;
  61270. mesh.rotationQuaternion.z = body.quaternion.z;
  61271. mesh.rotationQuaternion.w = body.quaternion.w;
  61272. };
  61273. CannonJSPlugin.prototype.getRadius = function (impostor) {
  61274. var shape = impostor.physicsBody.shapes[0];
  61275. return shape.boundingSphereRadius;
  61276. };
  61277. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  61278. var shape = impostor.physicsBody.shapes[0];
  61279. result.x = shape.halfExtents.x * 2;
  61280. result.y = shape.halfExtents.y * 2;
  61281. result.z = shape.halfExtents.z * 2;
  61282. };
  61283. CannonJSPlugin.prototype.dispose = function () {
  61284. };
  61285. return CannonJSPlugin;
  61286. }());
  61287. BABYLON.CannonJSPlugin = CannonJSPlugin;
  61288. })(BABYLON || (BABYLON = {}));
  61289. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  61290. var BABYLON;
  61291. (function (BABYLON) {
  61292. var OimoJSPlugin = (function () {
  61293. function OimoJSPlugin(iterations) {
  61294. this.name = "OimoJSPlugin";
  61295. this._tmpImpostorsArray = [];
  61296. this._tmpPositionVector = BABYLON.Vector3.Zero();
  61297. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  61298. this.world.worldscale(1);
  61299. this.world.clear();
  61300. //making sure no stats are calculated
  61301. this.world.isNoStat = true;
  61302. }
  61303. OimoJSPlugin.prototype.setGravity = function (gravity) {
  61304. this.world.gravity.copy(gravity);
  61305. };
  61306. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  61307. this.world.timeStep = timeStep;
  61308. };
  61309. OimoJSPlugin.prototype.getTimeStep = function () {
  61310. return this.world.timeStep;
  61311. };
  61312. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  61313. var _this = this;
  61314. impostors.forEach(function (impostor) {
  61315. impostor.beforeStep();
  61316. });
  61317. this.world.step();
  61318. impostors.forEach(function (impostor) {
  61319. impostor.afterStep();
  61320. //update the ordered impostors array
  61321. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  61322. });
  61323. //check for collisions
  61324. var contact = this.world.contacts;
  61325. while (contact !== null) {
  61326. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  61327. contact = contact.next;
  61328. continue;
  61329. }
  61330. //is this body colliding with any other? get the impostor
  61331. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  61332. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  61333. if (!mainImpostor || !collidingImpostor) {
  61334. contact = contact.next;
  61335. continue;
  61336. }
  61337. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  61338. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  61339. contact = contact.next;
  61340. }
  61341. };
  61342. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  61343. var mass = impostor.physicsBody.massInfo.mass;
  61344. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  61345. };
  61346. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  61347. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  61348. this.applyImpulse(impostor, force, contactPoint);
  61349. };
  61350. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  61351. var _this = this;
  61352. //parent-child relationship. Does this impostor has a parent impostor?
  61353. if (impostor.parent) {
  61354. if (impostor.physicsBody) {
  61355. this.removePhysicsBody(impostor);
  61356. //TODO is that needed?
  61357. impostor.forceUpdate();
  61358. }
  61359. return;
  61360. }
  61361. if (impostor.isBodyInitRequired()) {
  61362. var bodyConfig = {
  61363. name: impostor.uniqueId,
  61364. //Oimo must have mass, also for static objects.
  61365. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  61366. size: [],
  61367. type: [],
  61368. pos: [],
  61369. rot: [],
  61370. move: impostor.getParam("mass") !== 0,
  61371. //Supporting older versions of Oimo
  61372. world: this.world
  61373. };
  61374. var impostors = [impostor];
  61375. var addToArray = function (parent) {
  61376. if (!parent.getChildMeshes)
  61377. return;
  61378. parent.getChildMeshes().forEach(function (m) {
  61379. if (m.physicsImpostor) {
  61380. impostors.push(m.physicsImpostor);
  61381. m.physicsImpostor._init();
  61382. }
  61383. });
  61384. };
  61385. addToArray(impostor.object);
  61386. var checkWithEpsilon_1 = function (value) {
  61387. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  61388. };
  61389. impostors.forEach(function (i) {
  61390. //get the correct bounding box
  61391. var oldQuaternion = i.object.rotationQuaternion;
  61392. var rot = new OIMO.Euler().setFromQuaternion({
  61393. x: impostor.object.rotationQuaternion.x,
  61394. y: impostor.object.rotationQuaternion.y,
  61395. z: impostor.object.rotationQuaternion.z,
  61396. s: impostor.object.rotationQuaternion.w
  61397. });
  61398. var extendSize = i.getObjectExtendSize();
  61399. if (i === impostor) {
  61400. var center = impostor.getObjectCenter();
  61401. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  61402. //Can also use Array.prototype.push.apply
  61403. bodyConfig.pos.push(center.x);
  61404. bodyConfig.pos.push(center.y);
  61405. bodyConfig.pos.push(center.z);
  61406. //tmp solution
  61407. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  61408. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  61409. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  61410. }
  61411. else {
  61412. bodyConfig.pos.push(i.object.position.x);
  61413. bodyConfig.pos.push(i.object.position.y);
  61414. bodyConfig.pos.push(i.object.position.z);
  61415. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  61416. bodyConfig.rot.push(0);
  61417. bodyConfig.rot.push(0);
  61418. bodyConfig.rot.push(0);
  61419. }
  61420. // register mesh
  61421. switch (i.type) {
  61422. case BABYLON.PhysicsImpostor.ParticleImpostor:
  61423. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  61424. case BABYLON.PhysicsImpostor.SphereImpostor:
  61425. var radiusX = extendSize.x;
  61426. var radiusY = extendSize.y;
  61427. var radiusZ = extendSize.z;
  61428. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  61429. bodyConfig.type.push('sphere');
  61430. //due to the way oimo works with compounds, add 3 times
  61431. bodyConfig.size.push(size);
  61432. bodyConfig.size.push(size);
  61433. bodyConfig.size.push(size);
  61434. break;
  61435. case BABYLON.PhysicsImpostor.CylinderImpostor:
  61436. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  61437. var sizeY = checkWithEpsilon_1(extendSize.y);
  61438. bodyConfig.type.push('cylinder');
  61439. bodyConfig.size.push(sizeX);
  61440. bodyConfig.size.push(sizeY);
  61441. //due to the way oimo works with compounds, add one more value.
  61442. bodyConfig.size.push(sizeY);
  61443. break;
  61444. case BABYLON.PhysicsImpostor.PlaneImpostor:
  61445. case BABYLON.PhysicsImpostor.BoxImpostor:
  61446. default:
  61447. var sizeX = checkWithEpsilon_1(extendSize.x);
  61448. var sizeY = checkWithEpsilon_1(extendSize.y);
  61449. var sizeZ = checkWithEpsilon_1(extendSize.z);
  61450. bodyConfig.type.push('box');
  61451. bodyConfig.size.push(sizeX);
  61452. bodyConfig.size.push(sizeY);
  61453. bodyConfig.size.push(sizeZ);
  61454. break;
  61455. }
  61456. //actually not needed, but hey...
  61457. i.object.rotationQuaternion = oldQuaternion;
  61458. });
  61459. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  61460. }
  61461. else {
  61462. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  61463. }
  61464. impostor.setDeltaPosition(this._tmpPositionVector);
  61465. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  61466. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  61467. };
  61468. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  61469. //impostor.physicsBody.dispose();
  61470. //Same as : (older oimo versions)
  61471. this.world.removeRigidBody(impostor.physicsBody);
  61472. };
  61473. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  61474. var mainBody = impostorJoint.mainImpostor.physicsBody;
  61475. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  61476. if (!mainBody || !connectedBody) {
  61477. return;
  61478. }
  61479. var jointData = impostorJoint.joint.jointData;
  61480. var options = jointData.nativeParams || {};
  61481. var type;
  61482. var nativeJointData = {
  61483. body1: mainBody,
  61484. body2: connectedBody,
  61485. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  61486. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  61487. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  61488. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  61489. min: options.min,
  61490. max: options.max,
  61491. collision: options.collision || jointData.collision,
  61492. spring: options.spring,
  61493. //supporting older version of Oimo
  61494. world: this.world
  61495. };
  61496. switch (impostorJoint.joint.type) {
  61497. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  61498. type = "jointBall";
  61499. break;
  61500. case BABYLON.PhysicsJoint.SpringJoint:
  61501. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  61502. var springData = jointData;
  61503. nativeJointData.min = springData.length || nativeJointData.min;
  61504. //Max should also be set, just make sure it is at least min
  61505. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  61506. case BABYLON.PhysicsJoint.DistanceJoint:
  61507. type = "jointDistance";
  61508. nativeJointData.max = jointData.maxDistance;
  61509. break;
  61510. case BABYLON.PhysicsJoint.PrismaticJoint:
  61511. type = "jointPrisme";
  61512. break;
  61513. case BABYLON.PhysicsJoint.SliderJoint:
  61514. type = "jointSlide";
  61515. break;
  61516. case BABYLON.PhysicsJoint.WheelJoint:
  61517. type = "jointWheel";
  61518. break;
  61519. case BABYLON.PhysicsJoint.HingeJoint:
  61520. default:
  61521. type = "jointHinge";
  61522. break;
  61523. }
  61524. nativeJointData.type = type;
  61525. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  61526. };
  61527. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  61528. //Bug in Oimo prevents us from disposing a joint in the playground
  61529. //joint.joint.physicsJoint.dispose();
  61530. //So we will bruteforce it!
  61531. try {
  61532. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  61533. }
  61534. catch (e) {
  61535. BABYLON.Tools.Warn(e);
  61536. }
  61537. };
  61538. OimoJSPlugin.prototype.isSupported = function () {
  61539. return OIMO !== undefined;
  61540. };
  61541. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  61542. if (!impostor.physicsBody.sleeping) {
  61543. //TODO check that
  61544. if (impostor.physicsBody.shapes.next) {
  61545. var parentShape = this._getLastShape(impostor.physicsBody);
  61546. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  61547. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  61548. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  61549. }
  61550. else {
  61551. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  61552. }
  61553. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  61554. impostor.object.rotationQuaternion.normalize();
  61555. }
  61556. };
  61557. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  61558. var body = impostor.physicsBody;
  61559. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  61560. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  61561. body.syncShapes();
  61562. body.awake();
  61563. };
  61564. OimoJSPlugin.prototype._getLastShape = function (body) {
  61565. var lastShape = body.shapes;
  61566. while (lastShape.next) {
  61567. lastShape = lastShape.next;
  61568. }
  61569. return lastShape;
  61570. };
  61571. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  61572. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  61573. };
  61574. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  61575. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  61576. };
  61577. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  61578. var v = impostor.physicsBody.linearVelocity;
  61579. if (!v)
  61580. return null;
  61581. return new BABYLON.Vector3(v.x, v.y, v.z);
  61582. };
  61583. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  61584. var v = impostor.physicsBody.angularVelocity;
  61585. if (!v)
  61586. return null;
  61587. return new BABYLON.Vector3(v.x, v.y, v.z);
  61588. };
  61589. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  61590. var staticBody = mass === 0;
  61591. //this will actually set the body's density and not its mass.
  61592. //But this is how oimo treats the mass variable.
  61593. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  61594. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  61595. };
  61596. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  61597. return impostor.physicsBody.shapes.density;
  61598. };
  61599. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  61600. return impostor.physicsBody.shapes.friction;
  61601. };
  61602. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  61603. impostor.physicsBody.shapes.friction = friction;
  61604. };
  61605. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  61606. return impostor.physicsBody.shapes.restitution;
  61607. };
  61608. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  61609. impostor.physicsBody.shapes.restitution = restitution;
  61610. };
  61611. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  61612. impostor.physicsBody.sleep();
  61613. };
  61614. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  61615. impostor.physicsBody.awake();
  61616. };
  61617. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  61618. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  61619. if (minDistance !== void 0) {
  61620. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  61621. }
  61622. };
  61623. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  61624. //TODO separate rotational and transational motors.
  61625. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  61626. if (motor) {
  61627. motor.setMotor(speed, maxForce);
  61628. }
  61629. };
  61630. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  61631. //TODO separate rotational and transational motors.
  61632. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  61633. if (motor) {
  61634. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  61635. }
  61636. };
  61637. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  61638. var body = impostor.physicsBody;
  61639. mesh.position.x = body.position.x;
  61640. mesh.position.y = body.position.y;
  61641. mesh.position.z = body.position.z;
  61642. mesh.rotationQuaternion.x = body.orientation.x;
  61643. mesh.rotationQuaternion.y = body.orientation.y;
  61644. mesh.rotationQuaternion.z = body.orientation.z;
  61645. mesh.rotationQuaternion.w = body.orientation.s;
  61646. };
  61647. OimoJSPlugin.prototype.getRadius = function (impostor) {
  61648. return impostor.physicsBody.shapes.radius;
  61649. };
  61650. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  61651. var shape = impostor.physicsBody.shapes;
  61652. result.x = shape.halfWidth * 2;
  61653. result.y = shape.halfHeight * 2;
  61654. result.z = shape.halfDepth * 2;
  61655. };
  61656. OimoJSPlugin.prototype.dispose = function () {
  61657. this.world.clear();
  61658. };
  61659. return OimoJSPlugin;
  61660. }());
  61661. BABYLON.OimoJSPlugin = OimoJSPlugin;
  61662. })(BABYLON || (BABYLON = {}));
  61663. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  61664. var BABYLON;
  61665. (function (BABYLON) {
  61666. var Internals;
  61667. (function (Internals) {
  61668. /*
  61669. * Based on jsTGALoader - Javascript loader for TGA file
  61670. * By Vincent Thibault
  61671. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  61672. */
  61673. var TGATools = (function () {
  61674. function TGATools() {
  61675. }
  61676. TGATools.GetTGAHeader = function (data) {
  61677. var offset = 0;
  61678. var header = {
  61679. id_length: data[offset++],
  61680. colormap_type: data[offset++],
  61681. image_type: data[offset++],
  61682. colormap_index: data[offset++] | data[offset++] << 8,
  61683. colormap_length: data[offset++] | data[offset++] << 8,
  61684. colormap_size: data[offset++],
  61685. origin: [
  61686. data[offset++] | data[offset++] << 8,
  61687. data[offset++] | data[offset++] << 8
  61688. ],
  61689. width: data[offset++] | data[offset++] << 8,
  61690. height: data[offset++] | data[offset++] << 8,
  61691. pixel_size: data[offset++],
  61692. flags: data[offset++]
  61693. };
  61694. return header;
  61695. };
  61696. TGATools.UploadContent = function (gl, data) {
  61697. // Not enough data to contain header ?
  61698. if (data.length < 19) {
  61699. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  61700. return;
  61701. }
  61702. // Read Header
  61703. var offset = 18;
  61704. var header = TGATools.GetTGAHeader(data);
  61705. // Assume it's a valid Targa file.
  61706. if (header.id_length + offset > data.length) {
  61707. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  61708. return;
  61709. }
  61710. // Skip not needed data
  61711. offset += header.id_length;
  61712. var use_rle = false;
  61713. var use_pal = false;
  61714. var use_rgb = false;
  61715. var use_grey = false;
  61716. // Get some informations.
  61717. switch (header.image_type) {
  61718. case TGATools._TYPE_RLE_INDEXED:
  61719. use_rle = true;
  61720. case TGATools._TYPE_INDEXED:
  61721. use_pal = true;
  61722. break;
  61723. case TGATools._TYPE_RLE_RGB:
  61724. use_rle = true;
  61725. case TGATools._TYPE_RGB:
  61726. use_rgb = true;
  61727. break;
  61728. case TGATools._TYPE_RLE_GREY:
  61729. use_rle = true;
  61730. case TGATools._TYPE_GREY:
  61731. use_grey = true;
  61732. break;
  61733. }
  61734. var pixel_data;
  61735. var numAlphaBits = header.flags & 0xf;
  61736. var pixel_size = header.pixel_size >> 3;
  61737. var pixel_total = header.width * header.height * pixel_size;
  61738. // Read palettes
  61739. var palettes;
  61740. if (use_pal) {
  61741. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  61742. }
  61743. // Read LRE
  61744. if (use_rle) {
  61745. pixel_data = new Uint8Array(pixel_total);
  61746. var c, count, i;
  61747. var localOffset = 0;
  61748. var pixels = new Uint8Array(pixel_size);
  61749. while (offset < pixel_total && localOffset < pixel_total) {
  61750. c = data[offset++];
  61751. count = (c & 0x7f) + 1;
  61752. // RLE pixels
  61753. if (c & 0x80) {
  61754. // Bind pixel tmp array
  61755. for (i = 0; i < pixel_size; ++i) {
  61756. pixels[i] = data[offset++];
  61757. }
  61758. // Copy pixel array
  61759. for (i = 0; i < count; ++i) {
  61760. pixel_data.set(pixels, localOffset + i * pixel_size);
  61761. }
  61762. localOffset += pixel_size * count;
  61763. }
  61764. else {
  61765. count *= pixel_size;
  61766. for (i = 0; i < count; ++i) {
  61767. pixel_data[localOffset + i] = data[offset++];
  61768. }
  61769. localOffset += count;
  61770. }
  61771. }
  61772. }
  61773. else {
  61774. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  61775. }
  61776. // Load to texture
  61777. var x_start, y_start, x_step, y_step, y_end, x_end;
  61778. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  61779. default:
  61780. case TGATools._ORIGIN_UL:
  61781. x_start = 0;
  61782. x_step = 1;
  61783. x_end = header.width;
  61784. y_start = 0;
  61785. y_step = 1;
  61786. y_end = header.height;
  61787. break;
  61788. case TGATools._ORIGIN_BL:
  61789. x_start = 0;
  61790. x_step = 1;
  61791. x_end = header.width;
  61792. y_start = header.height - 1;
  61793. y_step = -1;
  61794. y_end = -1;
  61795. break;
  61796. case TGATools._ORIGIN_UR:
  61797. x_start = header.width - 1;
  61798. x_step = -1;
  61799. x_end = -1;
  61800. y_start = 0;
  61801. y_step = 1;
  61802. y_end = header.height;
  61803. break;
  61804. case TGATools._ORIGIN_BR:
  61805. x_start = header.width - 1;
  61806. x_step = -1;
  61807. x_end = -1;
  61808. y_start = header.height - 1;
  61809. y_step = -1;
  61810. y_end = -1;
  61811. break;
  61812. }
  61813. // Load the specify method
  61814. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  61815. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  61816. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  61817. };
  61818. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  61819. var image = pixel_data, colormap = palettes;
  61820. var width = header.width, height = header.height;
  61821. var color, i = 0, x, y;
  61822. var imageData = new Uint8Array(width * height * 4);
  61823. for (y = y_start; y !== y_end; y += y_step) {
  61824. for (x = x_start; x !== x_end; x += x_step, i++) {
  61825. color = image[i];
  61826. imageData[(x + width * y) * 4 + 3] = 255;
  61827. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  61828. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  61829. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  61830. }
  61831. }
  61832. return imageData;
  61833. };
  61834. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  61835. var image = pixel_data;
  61836. var width = header.width, height = header.height;
  61837. var color, i = 0, x, y;
  61838. var imageData = new Uint8Array(width * height * 4);
  61839. for (y = y_start; y !== y_end; y += y_step) {
  61840. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  61841. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  61842. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  61843. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  61844. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  61845. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  61846. }
  61847. }
  61848. return imageData;
  61849. };
  61850. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  61851. var image = pixel_data;
  61852. var width = header.width, height = header.height;
  61853. var i = 0, x, y;
  61854. var imageData = new Uint8Array(width * height * 4);
  61855. for (y = y_start; y !== y_end; y += y_step) {
  61856. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  61857. imageData[(x + width * y) * 4 + 3] = 255;
  61858. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  61859. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  61860. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  61861. }
  61862. }
  61863. return imageData;
  61864. };
  61865. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  61866. var image = pixel_data;
  61867. var width = header.width, height = header.height;
  61868. var i = 0, x, y;
  61869. var imageData = new Uint8Array(width * height * 4);
  61870. for (y = y_start; y !== y_end; y += y_step) {
  61871. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  61872. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  61873. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  61874. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  61875. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  61876. }
  61877. }
  61878. return imageData;
  61879. };
  61880. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  61881. var image = pixel_data;
  61882. var width = header.width, height = header.height;
  61883. var color, i = 0, x, y;
  61884. var imageData = new Uint8Array(width * height * 4);
  61885. for (y = y_start; y !== y_end; y += y_step) {
  61886. for (x = x_start; x !== x_end; x += x_step, i++) {
  61887. color = image[i];
  61888. imageData[(x + width * y) * 4 + 0] = color;
  61889. imageData[(x + width * y) * 4 + 1] = color;
  61890. imageData[(x + width * y) * 4 + 2] = color;
  61891. imageData[(x + width * y) * 4 + 3] = 255;
  61892. }
  61893. }
  61894. return imageData;
  61895. };
  61896. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  61897. var image = pixel_data;
  61898. var width = header.width, height = header.height;
  61899. var i = 0, x, y;
  61900. var imageData = new Uint8Array(width * height * 4);
  61901. for (y = y_start; y !== y_end; y += y_step) {
  61902. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  61903. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  61904. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  61905. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  61906. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  61907. }
  61908. }
  61909. return imageData;
  61910. };
  61911. TGATools._TYPE_NO_DATA = 0;
  61912. TGATools._TYPE_INDEXED = 1;
  61913. TGATools._TYPE_RGB = 2;
  61914. TGATools._TYPE_GREY = 3;
  61915. TGATools._TYPE_RLE_INDEXED = 9;
  61916. TGATools._TYPE_RLE_RGB = 10;
  61917. TGATools._TYPE_RLE_GREY = 11;
  61918. TGATools._ORIGIN_MASK = 0x30;
  61919. TGATools._ORIGIN_SHIFT = 0x04;
  61920. TGATools._ORIGIN_BL = 0x00;
  61921. TGATools._ORIGIN_BR = 0x01;
  61922. TGATools._ORIGIN_UL = 0x02;
  61923. TGATools._ORIGIN_UR = 0x03;
  61924. return TGATools;
  61925. }());
  61926. Internals.TGATools = TGATools;
  61927. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  61928. })(BABYLON || (BABYLON = {}));
  61929. //# sourceMappingURL=babylon.tga.js.map
  61930. var BABYLON;
  61931. (function (BABYLON) {
  61932. var Internals;
  61933. (function (Internals) {
  61934. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  61935. // All values and structures referenced from:
  61936. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  61937. var DDS_MAGIC = 0x20534444;
  61938. 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;
  61939. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  61940. 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;
  61941. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  61942. function FourCCToInt32(value) {
  61943. return value.charCodeAt(0) +
  61944. (value.charCodeAt(1) << 8) +
  61945. (value.charCodeAt(2) << 16) +
  61946. (value.charCodeAt(3) << 24);
  61947. }
  61948. function Int32ToFourCC(value) {
  61949. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  61950. }
  61951. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  61952. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  61953. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  61954. var FOURCC_DX10 = FourCCToInt32("DX10");
  61955. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  61956. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  61957. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  61958. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  61959. var headerLengthInt = 31; // The header length in 32 bit ints
  61960. // Offsets into the header array
  61961. var off_magic = 0;
  61962. var off_size = 1;
  61963. var off_flags = 2;
  61964. var off_height = 3;
  61965. var off_width = 4;
  61966. var off_mipmapCount = 7;
  61967. var off_pfFlags = 20;
  61968. var off_pfFourCC = 21;
  61969. var off_RGBbpp = 22;
  61970. var off_RMask = 23;
  61971. var off_GMask = 24;
  61972. var off_BMask = 25;
  61973. var off_AMask = 26;
  61974. var off_caps1 = 27;
  61975. var off_caps2 = 28;
  61976. var off_caps3 = 29;
  61977. var off_caps4 = 30;
  61978. var off_dxgiFormat = 32;
  61979. ;
  61980. var DDSTools = (function () {
  61981. function DDSTools() {
  61982. }
  61983. DDSTools.GetDDSInfo = function (arrayBuffer) {
  61984. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  61985. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  61986. var mipmapCount = 1;
  61987. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  61988. mipmapCount = Math.max(1, header[off_mipmapCount]);
  61989. }
  61990. var fourCC = header[off_pfFourCC];
  61991. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  61992. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  61993. switch (fourCC) {
  61994. case FOURCC_D3DFMT_R16G16B16A16F:
  61995. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  61996. break;
  61997. case FOURCC_D3DFMT_R32G32B32A32F:
  61998. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  61999. break;
  62000. case FOURCC_DX10:
  62001. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  62002. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  62003. break;
  62004. }
  62005. }
  62006. return {
  62007. width: header[off_width],
  62008. height: header[off_height],
  62009. mipmapCount: mipmapCount,
  62010. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  62011. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  62012. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  62013. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  62014. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || FOURCC_DXT1 === FOURCC_DXT5),
  62015. dxgiFormat: dxgiFormat,
  62016. textureType: textureType
  62017. };
  62018. };
  62019. DDSTools._ToHalfFloat = function (value) {
  62020. if (!DDSTools._FloatView) {
  62021. DDSTools._FloatView = new Float32Array(1);
  62022. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  62023. }
  62024. DDSTools._FloatView[0] = value;
  62025. var x = DDSTools._Int32View[0];
  62026. var bits = (x >> 16) & 0x8000; /* Get the sign */
  62027. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  62028. var e = (x >> 23) & 0xff; /* Using int is faster here */
  62029. /* If zero, or denormal, or exponent underflows too much for a denormal
  62030. * half, return signed zero. */
  62031. if (e < 103) {
  62032. return bits;
  62033. }
  62034. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  62035. if (e > 142) {
  62036. bits |= 0x7c00;
  62037. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  62038. * not Inf, so make sure we set one mantissa bit too. */
  62039. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  62040. return bits;
  62041. }
  62042. /* If exponent underflows but not too much, return a denormal */
  62043. if (e < 113) {
  62044. m |= 0x0800;
  62045. /* Extra rounding may overflow and set mantissa to 0 and exponent
  62046. * to 1, which is OK. */
  62047. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  62048. return bits;
  62049. }
  62050. bits |= ((e - 112) << 10) | (m >> 1);
  62051. bits += m & 1;
  62052. return bits;
  62053. };
  62054. DDSTools._FromHalfFloat = function (value) {
  62055. var s = (value & 0x8000) >> 15;
  62056. var e = (value & 0x7C00) >> 10;
  62057. var f = value & 0x03FF;
  62058. if (e === 0) {
  62059. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  62060. }
  62061. else if (e == 0x1F) {
  62062. return f ? NaN : ((s ? -1 : 1) * Infinity);
  62063. }
  62064. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  62065. };
  62066. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  62067. var destArray = new Float32Array(dataLength);
  62068. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  62069. var index = 0;
  62070. for (var y = 0; y < height; y++) {
  62071. for (var x = 0; x < width; x++) {
  62072. var srcPos = (x + y * width) * 4;
  62073. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  62074. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  62075. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  62076. if (DDSTools.StoreLODInAlphaChannel) {
  62077. destArray[index + 3] = lod;
  62078. }
  62079. else {
  62080. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  62081. }
  62082. index += 4;
  62083. }
  62084. }
  62085. return destArray;
  62086. };
  62087. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  62088. if (DDSTools.StoreLODInAlphaChannel) {
  62089. var destArray = new Uint16Array(dataLength);
  62090. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  62091. var index = 0;
  62092. for (var y = 0; y < height; y++) {
  62093. for (var x = 0; x < width; x++) {
  62094. var srcPos = (x + y * width) * 4;
  62095. destArray[index] = srcData[srcPos];
  62096. destArray[index + 1] = srcData[srcPos + 1];
  62097. destArray[index + 2] = srcData[srcPos + 2];
  62098. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  62099. index += 4;
  62100. }
  62101. }
  62102. return destArray;
  62103. }
  62104. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  62105. };
  62106. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  62107. if (DDSTools.StoreLODInAlphaChannel) {
  62108. var destArray = new Float32Array(dataLength);
  62109. var srcData = new Float32Array(arrayBuffer, dataOffset);
  62110. var index = 0;
  62111. for (var y = 0; y < height; y++) {
  62112. for (var x = 0; x < width; x++) {
  62113. var srcPos = (x + y * width) * 4;
  62114. destArray[index] = srcData[srcPos];
  62115. destArray[index + 1] = srcData[srcPos + 1];
  62116. destArray[index + 2] = srcData[srcPos + 2];
  62117. destArray[index + 3] = lod;
  62118. index += 4;
  62119. }
  62120. }
  62121. return destArray;
  62122. }
  62123. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  62124. };
  62125. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  62126. var destArray = new Uint8Array(dataLength);
  62127. var srcData = new Float32Array(arrayBuffer, dataOffset);
  62128. var index = 0;
  62129. for (var y = 0; y < height; y++) {
  62130. for (var x = 0; x < width; x++) {
  62131. var srcPos = (x + y * width) * 4;
  62132. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  62133. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  62134. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  62135. if (DDSTools.StoreLODInAlphaChannel) {
  62136. destArray[index + 3] = lod;
  62137. }
  62138. else {
  62139. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  62140. }
  62141. index += 4;
  62142. }
  62143. }
  62144. return destArray;
  62145. };
  62146. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  62147. var destArray = new Uint8Array(dataLength);
  62148. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  62149. var index = 0;
  62150. for (var y = 0; y < height; y++) {
  62151. for (var x = 0; x < width; x++) {
  62152. var srcPos = (x + y * width) * 4;
  62153. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  62154. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  62155. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  62156. if (DDSTools.StoreLODInAlphaChannel) {
  62157. destArray[index + 3] = lod;
  62158. }
  62159. else {
  62160. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  62161. }
  62162. index += 4;
  62163. }
  62164. }
  62165. return destArray;
  62166. };
  62167. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  62168. var byteArray = new Uint8Array(dataLength);
  62169. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  62170. var index = 0;
  62171. for (var y = 0; y < height; y++) {
  62172. for (var x = 0; x < width; x++) {
  62173. var srcPos = (x + y * width) * 4;
  62174. byteArray[index] = srcData[srcPos + 2];
  62175. byteArray[index + 1] = srcData[srcPos + 1];
  62176. byteArray[index + 2] = srcData[srcPos];
  62177. byteArray[index + 3] = srcData[srcPos + 3];
  62178. index += 4;
  62179. }
  62180. }
  62181. return byteArray;
  62182. };
  62183. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  62184. var byteArray = new Uint8Array(dataLength);
  62185. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  62186. var index = 0;
  62187. for (var y = 0; y < height; y++) {
  62188. for (var x = 0; x < width; x++) {
  62189. var srcPos = (x + y * width) * 3;
  62190. byteArray[index] = srcData[srcPos + 2];
  62191. byteArray[index + 1] = srcData[srcPos + 1];
  62192. byteArray[index + 2] = srcData[srcPos];
  62193. index += 3;
  62194. }
  62195. }
  62196. return byteArray;
  62197. };
  62198. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  62199. var byteArray = new Uint8Array(dataLength);
  62200. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  62201. var index = 0;
  62202. for (var y = 0; y < height; y++) {
  62203. for (var x = 0; x < width; x++) {
  62204. var srcPos = (x + y * width);
  62205. byteArray[index] = srcData[srcPos];
  62206. index++;
  62207. }
  62208. }
  62209. return byteArray;
  62210. };
  62211. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex) {
  62212. if (lodIndex === void 0) { lodIndex = -1; }
  62213. var ext = engine.getCaps().s3tc;
  62214. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, format, width, height, dataLength, dataOffset, byteArray, mipmapCount, mip;
  62215. if (header[off_magic] != DDS_MAGIC) {
  62216. BABYLON.Tools.Error("Invalid magic number in DDS header");
  62217. return;
  62218. }
  62219. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  62220. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  62221. return;
  62222. }
  62223. if (info.isCompressed && !ext) {
  62224. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  62225. return;
  62226. }
  62227. var bpp = header[off_RGBbpp];
  62228. dataOffset = header[off_size] + 4;
  62229. var computeFormats = false;
  62230. if (info.isFourCC) {
  62231. fourCC = header[off_pfFourCC];
  62232. switch (fourCC) {
  62233. case FOURCC_DXT1:
  62234. blockBytes = 8;
  62235. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  62236. break;
  62237. case FOURCC_DXT3:
  62238. blockBytes = 16;
  62239. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  62240. break;
  62241. case FOURCC_DXT5:
  62242. blockBytes = 16;
  62243. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  62244. break;
  62245. case FOURCC_D3DFMT_R16G16B16A16F:
  62246. computeFormats = true;
  62247. break;
  62248. case FOURCC_D3DFMT_R32G32B32A32F:
  62249. computeFormats = true;
  62250. break;
  62251. case FOURCC_DX10:
  62252. // There is an additionnal header so dataOffset need to be changed
  62253. dataOffset += 5 * 4; // 5 uints
  62254. var supported = false;
  62255. switch (info.dxgiFormat) {
  62256. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  62257. computeFormats = true;
  62258. supported = true;
  62259. break;
  62260. case DXGI_FORMAT_B8G8R8X8_UNORM:
  62261. info.isRGB = true;
  62262. info.isFourCC = false;
  62263. bpp = 32;
  62264. supported = true;
  62265. break;
  62266. }
  62267. if (supported) {
  62268. break;
  62269. }
  62270. default:
  62271. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  62272. return;
  62273. }
  62274. }
  62275. if (computeFormats) {
  62276. format = engine._getWebGLTextureType(info.textureType);
  62277. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  62278. }
  62279. mipmapCount = 1;
  62280. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  62281. mipmapCount = Math.max(1, header[off_mipmapCount]);
  62282. }
  62283. for (var face = 0; face < faces; face++) {
  62284. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  62285. width = header[off_width];
  62286. height = header[off_height];
  62287. for (mip = 0; mip < mipmapCount; ++mip) {
  62288. if (lodIndex === -1 || lodIndex === mip) {
  62289. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  62290. var i = (lodIndex === -1) ? mip : 0;
  62291. if (!info.isCompressed && info.isFourCC) {
  62292. dataLength = width * height * 4;
  62293. var floatArray;
  62294. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  62295. if (bpp === 128) {
  62296. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  62297. }
  62298. else if (bpp === 64) {
  62299. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  62300. }
  62301. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  62302. format = engine._getWebGLTextureType(info.textureType);
  62303. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  62304. }
  62305. else {
  62306. if (bpp === 128) {
  62307. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  62308. }
  62309. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  62310. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  62311. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  62312. format = engine._getWebGLTextureType(info.textureType);
  62313. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  62314. }
  62315. else {
  62316. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  62317. }
  62318. }
  62319. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  62320. }
  62321. else if (info.isRGB) {
  62322. if (bpp === 24) {
  62323. dataLength = width * height * 3;
  62324. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  62325. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  62326. }
  62327. else {
  62328. dataLength = width * height * 4;
  62329. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  62330. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  62331. }
  62332. }
  62333. else if (info.isLuminance) {
  62334. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  62335. var unpaddedRowSize = width;
  62336. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  62337. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  62338. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  62339. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  62340. }
  62341. else {
  62342. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  62343. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  62344. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  62345. }
  62346. }
  62347. dataOffset += width * height * (bpp / 8);
  62348. width *= 0.5;
  62349. height *= 0.5;
  62350. width = Math.max(1.0, width);
  62351. height = Math.max(1.0, height);
  62352. }
  62353. }
  62354. };
  62355. DDSTools.StoreLODInAlphaChannel = false;
  62356. return DDSTools;
  62357. }());
  62358. Internals.DDSTools = DDSTools;
  62359. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62360. })(BABYLON || (BABYLON = {}));
  62361. //# sourceMappingURL=babylon.dds.js.map
  62362. var BABYLON;
  62363. (function (BABYLON) {
  62364. var Internals;
  62365. (function (Internals) {
  62366. /**
  62367. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  62368. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  62369. */
  62370. var KhronosTextureContainer = (function () {
  62371. /**
  62372. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  62373. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  62374. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  62375. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  62376. */
  62377. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  62378. this.arrayBuffer = arrayBuffer;
  62379. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  62380. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  62381. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  62382. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  62383. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  62384. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  62385. BABYLON.Tools.Error("texture missing KTX identifier");
  62386. return;
  62387. }
  62388. // load the reset of the header in native 32 bit int
  62389. var header = new Int32Array(this.arrayBuffer, 12, 13);
  62390. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  62391. var oppositeEndianess = header[0] === 0x01020304;
  62392. // read all the header elements in order they exist in the file, without modification (sans endainness)
  62393. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  62394. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  62395. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  62396. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  62397. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  62398. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  62399. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  62400. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  62401. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  62402. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  62403. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  62404. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  62405. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  62406. if (this.glType !== 0) {
  62407. BABYLON.Tools.Error("only compressed formats currently supported");
  62408. return;
  62409. }
  62410. else {
  62411. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  62412. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  62413. }
  62414. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  62415. BABYLON.Tools.Error("only 2D textures currently supported");
  62416. return;
  62417. }
  62418. if (this.numberOfArrayElements !== 0) {
  62419. BABYLON.Tools.Error("texture arrays not currently supported");
  62420. return;
  62421. }
  62422. if (this.numberOfFaces !== facesExpected) {
  62423. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  62424. return;
  62425. }
  62426. // we now have a completely validated file, so could use existence of loadType as success
  62427. // would need to make this more elaborate & adjust checks above to support more than one load type
  62428. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  62429. }
  62430. // not as fast hardware based, but will probably never need to use
  62431. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  62432. return ((val & 0xFF) << 24)
  62433. | ((val & 0xFF00) << 8)
  62434. | ((val >> 8) & 0xFF00)
  62435. | ((val >> 24) & 0xFF);
  62436. };
  62437. /**
  62438. * It is assumed that the texture has already been created & is currently bound
  62439. */
  62440. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  62441. switch (this.loadType) {
  62442. case KhronosTextureContainer.COMPRESSED_2D:
  62443. this._upload2DCompressedLevels(gl, loadMipmaps);
  62444. break;
  62445. case KhronosTextureContainer.TEX_2D:
  62446. case KhronosTextureContainer.COMPRESSED_3D:
  62447. case KhronosTextureContainer.TEX_3D:
  62448. }
  62449. };
  62450. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  62451. // initialize width & height for level 1
  62452. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  62453. var width = this.pixelWidth;
  62454. var height = this.pixelHeight;
  62455. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  62456. for (var level = 0; level < mipmapCount; level++) {
  62457. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  62458. for (var face = 0; face < this.numberOfFaces; face++) {
  62459. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  62460. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  62461. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  62462. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  62463. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  62464. }
  62465. width = Math.max(1.0, width * 0.5);
  62466. height = Math.max(1.0, height * 0.5);
  62467. }
  62468. };
  62469. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  62470. // load types
  62471. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  62472. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  62473. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  62474. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  62475. return KhronosTextureContainer;
  62476. }());
  62477. Internals.KhronosTextureContainer = KhronosTextureContainer;
  62478. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62479. })(BABYLON || (BABYLON = {}));
  62480. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  62481. var BABYLON;
  62482. (function (BABYLON) {
  62483. var DynamicFloatArrayElementInfo = (function () {
  62484. function DynamicFloatArrayElementInfo() {
  62485. }
  62486. return DynamicFloatArrayElementInfo;
  62487. }());
  62488. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  62489. /**
  62490. * 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.
  62491. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  62492. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  62493. * 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.
  62494. * 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.
  62495. * 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".
  62496. */
  62497. var DynamicFloatArray = (function () {
  62498. /**
  62499. * Construct an instance of the dynamic float array
  62500. * @param stride size of one element in float (i.e. not bytes!)
  62501. * @param initialElementCount the number of available entries at construction
  62502. */
  62503. function DynamicFloatArray(stride, initialElementCount) {
  62504. this.compareValueOffset = null;
  62505. this.sortingAscending = true;
  62506. this._stride = stride;
  62507. this.buffer = new Float32Array(stride * initialElementCount);
  62508. this._lastUsed = 0;
  62509. this._firstFree = 0;
  62510. this._allEntries = new Array(initialElementCount);
  62511. this._freeEntries = new Array(initialElementCount);
  62512. for (var i = 0; i < initialElementCount; i++) {
  62513. var element = new DynamicFloatArrayElementInfo();
  62514. element.offset = i * stride;
  62515. this._allEntries[i] = element;
  62516. this._freeEntries[initialElementCount - i - 1] = element;
  62517. }
  62518. }
  62519. /**
  62520. * Allocate an element in the array.
  62521. * @return the element info instance that contains the offset into the main buffer of the element's location.
  62522. * Beware, this offset may change when you call pack()
  62523. */
  62524. DynamicFloatArray.prototype.allocElement = function () {
  62525. if (this._freeEntries.length === 0) {
  62526. this._growBuffer();
  62527. }
  62528. var el = this._freeEntries.pop();
  62529. this._lastUsed = Math.max(el.offset, this._lastUsed);
  62530. if (el.offset === this._firstFree) {
  62531. if (this._freeEntries.length > 0) {
  62532. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  62533. }
  62534. else {
  62535. this._firstFree += this._stride;
  62536. }
  62537. }
  62538. return el;
  62539. };
  62540. /**
  62541. * Free the element corresponding to the given element info
  62542. * @param elInfo the element that describe the allocated element
  62543. */
  62544. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  62545. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  62546. this._freeEntries.push(elInfo);
  62547. };
  62548. /**
  62549. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  62550. * 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().
  62551. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  62552. */
  62553. DynamicFloatArray.prototype.pack = function () {
  62554. // no free slot? no need to pack
  62555. if (this._freeEntries.length === 0) {
  62556. return this.buffer;
  62557. }
  62558. // If the buffer is already packed the last used will always be lower than the first free
  62559. // 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.
  62560. if (this._lastUsed < this._firstFree) {
  62561. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  62562. return elementsBuffer_1;
  62563. }
  62564. var s = this._stride;
  62565. // 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
  62566. var lastFree = new DynamicFloatArrayElementInfo();
  62567. lastFree.offset = this.totalElementCount * s;
  62568. this._freeEntries.push(lastFree);
  62569. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  62570. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  62571. var firstFreeSlotOffset = sortedFree[0].offset;
  62572. var freeZoneSize = 1;
  62573. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  62574. var prevOffset = sortedFree[0].offset;
  62575. for (var i = 1; i < sortedFree.length; i++) {
  62576. // 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
  62577. if (firstFreeSlotOffset >= occupiedZoneSize) {
  62578. break;
  62579. }
  62580. var curFree = sortedFree[i];
  62581. var curOffset = curFree.offset;
  62582. // Compute the distance between this offset and the previous
  62583. var distance = curOffset - prevOffset;
  62584. // If the distance is the stride size, they are adjacent, it good, move to the next
  62585. if (distance === s) {
  62586. // Free zone is one element bigger
  62587. ++freeZoneSize;
  62588. // as we're about to iterate to the next, the cur becomes the previous...
  62589. prevOffset = curOffset;
  62590. continue;
  62591. }
  62592. // Distance is bigger, which means there's x element between the previous free and this one
  62593. var usedRange = (distance / s) - 1;
  62594. // Two cases the free zone is smaller than the data to move or bigger
  62595. // Copy what can fit in the free zone
  62596. var curMoveOffset = curOffset - s;
  62597. var copyCount = Math.min(freeZoneSize, usedRange);
  62598. for (var j = 0; j < copyCount; j++) {
  62599. var freeI = firstFreeSlotOffset / s;
  62600. var curI = curMoveOffset / s;
  62601. var moveEl = sortedAll[curI];
  62602. this._moveElement(moveEl, firstFreeSlotOffset);
  62603. var replacedEl = sortedAll[freeI];
  62604. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  62605. replacedEl.offset = curMoveOffset;
  62606. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  62607. sortedAll[freeI] = moveEl;
  62608. sortedAll[curI] = replacedEl;
  62609. curMoveOffset -= s;
  62610. firstFreeSlotOffset += s;
  62611. }
  62612. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  62613. if (freeZoneSize <= usedRange) {
  62614. firstFreeSlotOffset = curMoveOffset + s;
  62615. freeZoneSize = 1 + copyCount;
  62616. }
  62617. else {
  62618. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  62619. }
  62620. // as we're about to iterate to the next, the cur becomes the previous...
  62621. prevOffset = curOffset;
  62622. }
  62623. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  62624. this._lastUsed = firstFreeSlotOffset - s;
  62625. this._firstFree = firstFreeSlotOffset;
  62626. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  62627. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  62628. this._allEntries = sortedAll;
  62629. return elementsBuffer;
  62630. };
  62631. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  62632. for (var i = 0; i < this._stride; i++) {
  62633. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  62634. }
  62635. element.offset = destOffset;
  62636. };
  62637. DynamicFloatArray.prototype._growBuffer = function () {
  62638. // Allocate the new buffer with 50% more entries, copy the content of the current one
  62639. var newElCount = Math.floor(this.totalElementCount * 1.5);
  62640. var newBuffer = new Float32Array(newElCount * this._stride);
  62641. newBuffer.set(this.buffer);
  62642. var curCount = this.totalElementCount;
  62643. var addedCount = newElCount - this.totalElementCount;
  62644. for (var i = 0; i < addedCount; i++) {
  62645. var element = new DynamicFloatArrayElementInfo();
  62646. element.offset = (curCount + i) * this.stride;
  62647. this._allEntries.push(element);
  62648. this._freeEntries[addedCount - i - 1] = element;
  62649. }
  62650. this._firstFree = curCount * this.stride;
  62651. this.buffer = newBuffer;
  62652. };
  62653. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  62654. /**
  62655. * Get the total count of entries that can fit in the current buffer
  62656. * @returns the elements count
  62657. */
  62658. get: function () {
  62659. return this._allEntries.length;
  62660. },
  62661. enumerable: true,
  62662. configurable: true
  62663. });
  62664. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  62665. /**
  62666. * Get the count of free entries that can still be allocated without resizing the buffer
  62667. * @returns the free elements count
  62668. */
  62669. get: function () {
  62670. return this._freeEntries.length;
  62671. },
  62672. enumerable: true,
  62673. configurable: true
  62674. });
  62675. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  62676. /**
  62677. * Get the count of allocated elements
  62678. * @returns the allocated elements count
  62679. */
  62680. get: function () {
  62681. return this._allEntries.length - this._freeEntries.length;
  62682. },
  62683. enumerable: true,
  62684. configurable: true
  62685. });
  62686. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  62687. /**
  62688. * Return the size of one element in float
  62689. * @returns the size in float
  62690. */
  62691. get: function () {
  62692. return this._stride;
  62693. },
  62694. enumerable: true,
  62695. configurable: true
  62696. });
  62697. DynamicFloatArray.prototype.sort = function () {
  62698. var _this = this;
  62699. if (!this.compareValueOffset) {
  62700. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  62701. }
  62702. var count = this.usedElementCount;
  62703. // Do we have to (re)create the sort table?
  62704. if (!this._sortTable || this._sortTable.length < count) {
  62705. // 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...
  62706. var newCount = Math.min(this.totalElementCount, count * 2);
  62707. this._sortTable = new Array(newCount);
  62708. }
  62709. if (!this._sortedTable || this._sortedTable.length !== count) {
  62710. this._sortedTable = new Array(count);
  62711. }
  62712. // Because, you know...
  62713. this.pack();
  62714. //let stride = this.stride;
  62715. //for (let i = 0; i < count; i++) {
  62716. // let si = this._sortTable[i];
  62717. // if (!si) {
  62718. // si = new SortInfo();
  62719. // this._sortTable[i] = si;
  62720. // }
  62721. // si.entry = this._allEntries[i];
  62722. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  62723. // si.swapedOffset = null;
  62724. // this._sortedTable[i] = si;
  62725. //}
  62726. var curOffset = 0;
  62727. var stride = this.stride;
  62728. for (var i = 0; i < count; i++, curOffset += stride) {
  62729. var si = this._sortTable[i];
  62730. if (!si) {
  62731. si = new SortInfo();
  62732. this._sortTable[i] = si;
  62733. }
  62734. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  62735. si.offset = curOffset;
  62736. si.swapedOffset = null;
  62737. this._sortedTable[i] = si;
  62738. }
  62739. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  62740. if (this.sortingAscending) {
  62741. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  62742. }
  62743. else {
  62744. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  62745. }
  62746. var swapElements = function (src, dst) {
  62747. for (var i = 0; i < stride; i++) {
  62748. var tps = _this.buffer[dst + i];
  62749. _this.buffer[dst + i] = _this.buffer[src + i];
  62750. _this.buffer[src + i] = tps;
  62751. }
  62752. };
  62753. // 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:
  62754. // 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),
  62755. // and I still want something with a good algorithm complexity.
  62756. // 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,
  62757. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  62758. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  62759. // 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
  62760. // until we find a SortInfo object without a swapedOffset which means we got the right location
  62761. // 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
  62762. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  62763. for (var i = 0; i < count; i++) {
  62764. // Get the element to move
  62765. var sourceSI = this._sortedTable[i];
  62766. var destSI = this._sortTable[i];
  62767. var sourceOff = sourceSI.offset;
  62768. // If the source changed location, find the new one
  62769. if (sourceSI.swapedOffset) {
  62770. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  62771. var curSI = sourceSI;
  62772. while (curSI.swapedOffset) {
  62773. curSI = this._sortTable[curSI.swapedOffset / stride];
  62774. }
  62775. // Finally get the right location
  62776. sourceOff = curSI.offset;
  62777. }
  62778. // Tag the element being replaced with its new location
  62779. destSI.swapedOffset = sourceOff;
  62780. // Swap elements (only if needed)
  62781. if (sourceOff !== destSI.offset) {
  62782. swapElements(sourceOff, destSI.offset);
  62783. }
  62784. // Update the offset in the corresponding DFAE
  62785. //sourceSI.entry.offset = destSI.entry.offset;
  62786. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  62787. }
  62788. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  62789. return true;
  62790. };
  62791. return DynamicFloatArray;
  62792. }());
  62793. BABYLON.DynamicFloatArray = DynamicFloatArray;
  62794. var SortInfo = (function () {
  62795. function SortInfo() {
  62796. this.compareData = this.offset = this.swapedOffset = null;
  62797. }
  62798. return SortInfo;
  62799. }());
  62800. })(BABYLON || (BABYLON = {}));
  62801. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  62802. var BABYLON;
  62803. (function (BABYLON) {
  62804. var Debug;
  62805. (function (Debug) {
  62806. /**
  62807. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  62808. */
  62809. var SkeletonViewer = (function () {
  62810. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  62811. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  62812. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  62813. this.skeleton = skeleton;
  62814. this.mesh = mesh;
  62815. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  62816. this.renderingGroupId = renderingGroupId;
  62817. this.color = BABYLON.Color3.White();
  62818. this._debugLines = [];
  62819. this._isEnabled = false;
  62820. this._scene = scene;
  62821. this.update();
  62822. this._renderFunction = this.update.bind(this);
  62823. }
  62824. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  62825. get: function () {
  62826. return this._isEnabled;
  62827. },
  62828. set: function (value) {
  62829. if (this._isEnabled === value) {
  62830. return;
  62831. }
  62832. this._isEnabled = value;
  62833. if (value) {
  62834. this._scene.registerBeforeRender(this._renderFunction);
  62835. }
  62836. else {
  62837. this._scene.unregisterBeforeRender(this._renderFunction);
  62838. }
  62839. },
  62840. enumerable: true,
  62841. configurable: true
  62842. });
  62843. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  62844. if (x === void 0) { x = 0; }
  62845. if (y === void 0) { y = 0; }
  62846. if (z === void 0) { z = 0; }
  62847. var tmat = BABYLON.Tmp.Matrix[0];
  62848. var parentBone = bone.getParent();
  62849. tmat.copyFrom(bone.getLocalMatrix());
  62850. if (x !== 0 || y !== 0 || z !== 0) {
  62851. var tmat2 = BABYLON.Tmp.Matrix[1];
  62852. BABYLON.Matrix.IdentityToRef(tmat2);
  62853. tmat2.m[12] = x;
  62854. tmat2.m[13] = y;
  62855. tmat2.m[14] = z;
  62856. tmat2.multiplyToRef(tmat, tmat);
  62857. }
  62858. if (parentBone) {
  62859. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  62860. }
  62861. tmat.multiplyToRef(meshMat, tmat);
  62862. position.x = tmat.m[12];
  62863. position.y = tmat.m[13];
  62864. position.z = tmat.m[14];
  62865. };
  62866. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  62867. var len = bones.length;
  62868. var meshPos = this.mesh.position;
  62869. for (var i = 0; i < len; i++) {
  62870. var bone = bones[i];
  62871. var points = this._debugLines[i];
  62872. if (!points) {
  62873. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62874. this._debugLines[i] = points;
  62875. }
  62876. this._getBonePosition(points[0], bone, meshMat);
  62877. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  62878. points[0].subtractInPlace(meshPos);
  62879. points[1].subtractInPlace(meshPos);
  62880. }
  62881. };
  62882. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  62883. var len = bones.length;
  62884. var boneNum = 0;
  62885. var meshPos = this.mesh.position;
  62886. for (var i = len - 1; i >= 0; i--) {
  62887. var childBone = bones[i];
  62888. var parentBone = childBone.getParent();
  62889. if (!parentBone) {
  62890. continue;
  62891. }
  62892. var points = this._debugLines[boneNum];
  62893. if (!points) {
  62894. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62895. this._debugLines[boneNum] = points;
  62896. }
  62897. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  62898. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  62899. points[0].subtractInPlace(meshPos);
  62900. points[1].subtractInPlace(meshPos);
  62901. boneNum++;
  62902. }
  62903. };
  62904. SkeletonViewer.prototype.update = function () {
  62905. if (this.autoUpdateBonesMatrices) {
  62906. this.skeleton.computeAbsoluteTransforms();
  62907. }
  62908. if (this.skeleton.bones[0].length === undefined) {
  62909. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  62910. }
  62911. else {
  62912. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  62913. }
  62914. if (!this._debugMesh) {
  62915. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  62916. this._debugMesh.renderingGroupId = this.renderingGroupId;
  62917. }
  62918. else {
  62919. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  62920. }
  62921. this._debugMesh.position.copyFrom(this.mesh.position);
  62922. this._debugMesh.color = this.color;
  62923. };
  62924. SkeletonViewer.prototype.dispose = function () {
  62925. if (this._debugMesh) {
  62926. this.isEnabled = false;
  62927. this._debugMesh.dispose();
  62928. this._debugMesh = null;
  62929. }
  62930. };
  62931. return SkeletonViewer;
  62932. }());
  62933. Debug.SkeletonViewer = SkeletonViewer;
  62934. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62935. })(BABYLON || (BABYLON = {}));
  62936. //# sourceMappingURL=babylon.skeletonViewer.js.map
  62937. var BABYLON;
  62938. (function (BABYLON) {
  62939. var Debug;
  62940. (function (Debug) {
  62941. var AxesViewer = (function () {
  62942. function AxesViewer(scene, scaleLines) {
  62943. if (scaleLines === void 0) { scaleLines = 1; }
  62944. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62945. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62946. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62947. this.scaleLines = 1;
  62948. this.scaleLines = scaleLines;
  62949. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  62950. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  62951. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  62952. this._xmesh.renderingGroupId = 2;
  62953. this._ymesh.renderingGroupId = 2;
  62954. this._zmesh.renderingGroupId = 2;
  62955. this._xmesh.material.checkReadyOnlyOnce = true;
  62956. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  62957. this._ymesh.material.checkReadyOnlyOnce = true;
  62958. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  62959. this._zmesh.material.checkReadyOnlyOnce = true;
  62960. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  62961. this.scene = scene;
  62962. }
  62963. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  62964. var scaleLines = this.scaleLines;
  62965. this._xmesh.position.copyFrom(position);
  62966. this._ymesh.position.copyFrom(position);
  62967. this._zmesh.position.copyFrom(position);
  62968. var point2 = this._xline[1];
  62969. point2.x = xaxis.x * scaleLines;
  62970. point2.y = xaxis.y * scaleLines;
  62971. point2.z = xaxis.z * scaleLines;
  62972. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  62973. point2 = this._yline[1];
  62974. point2.x = yaxis.x * scaleLines;
  62975. point2.y = yaxis.y * scaleLines;
  62976. point2.z = yaxis.z * scaleLines;
  62977. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  62978. point2 = this._zline[1];
  62979. point2.x = zaxis.x * scaleLines;
  62980. point2.y = zaxis.y * scaleLines;
  62981. point2.z = zaxis.z * scaleLines;
  62982. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  62983. };
  62984. AxesViewer.prototype.dispose = function () {
  62985. if (this._xmesh) {
  62986. this._xmesh.dispose();
  62987. this._ymesh.dispose();
  62988. this._zmesh.dispose();
  62989. this._xmesh = null;
  62990. this._ymesh = null;
  62991. this._zmesh = null;
  62992. this._xline = null;
  62993. this._yline = null;
  62994. this._zline = null;
  62995. this.scene = null;
  62996. }
  62997. };
  62998. return AxesViewer;
  62999. }());
  63000. Debug.AxesViewer = AxesViewer;
  63001. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  63002. })(BABYLON || (BABYLON = {}));
  63003. //# sourceMappingURL=babylon.axesViewer.js.map
  63004. var BABYLON;
  63005. (function (BABYLON) {
  63006. var Debug;
  63007. (function (Debug) {
  63008. var BoneAxesViewer = (function (_super) {
  63009. __extends(BoneAxesViewer, _super);
  63010. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  63011. if (scaleLines === void 0) { scaleLines = 1; }
  63012. var _this = _super.call(this, scene, scaleLines) || this;
  63013. _this.pos = BABYLON.Vector3.Zero();
  63014. _this.xaxis = BABYLON.Vector3.Zero();
  63015. _this.yaxis = BABYLON.Vector3.Zero();
  63016. _this.zaxis = BABYLON.Vector3.Zero();
  63017. _this.mesh = mesh;
  63018. _this.bone = bone;
  63019. return _this;
  63020. }
  63021. BoneAxesViewer.prototype.update = function () {
  63022. var bone = this.bone;
  63023. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  63024. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  63025. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  63026. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  63027. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  63028. };
  63029. BoneAxesViewer.prototype.dispose = function () {
  63030. if (this.pos) {
  63031. this.pos = null;
  63032. this.xaxis = null;
  63033. this.yaxis = null;
  63034. this.zaxis = null;
  63035. this.mesh = null;
  63036. this.bone = null;
  63037. _super.prototype.dispose.call(this);
  63038. }
  63039. };
  63040. return BoneAxesViewer;
  63041. }(Debug.AxesViewer));
  63042. Debug.BoneAxesViewer = BoneAxesViewer;
  63043. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  63044. })(BABYLON || (BABYLON = {}));
  63045. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  63046. var BABYLON;
  63047. (function (BABYLON) {
  63048. var RayHelper = (function () {
  63049. function RayHelper(ray) {
  63050. this.ray = ray;
  63051. }
  63052. RayHelper.CreateAndShow = function (ray, scene, color) {
  63053. var helper = new RayHelper(ray);
  63054. helper.show(scene, color);
  63055. return helper;
  63056. };
  63057. RayHelper.prototype.show = function (scene, color) {
  63058. if (!this._renderFunction) {
  63059. var ray = this.ray;
  63060. this._renderFunction = this._render.bind(this);
  63061. this._scene = scene;
  63062. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  63063. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  63064. this._scene.registerBeforeRender(this._renderFunction);
  63065. }
  63066. if (color) {
  63067. this._renderLine.color.copyFrom(color);
  63068. }
  63069. };
  63070. RayHelper.prototype.hide = function () {
  63071. if (this._renderFunction) {
  63072. this._scene.unregisterBeforeRender(this._renderFunction);
  63073. this._scene = null;
  63074. this._renderFunction = null;
  63075. this._renderLine.dispose();
  63076. this._renderLine = null;
  63077. this._renderPoints = null;
  63078. }
  63079. };
  63080. RayHelper.prototype._render = function () {
  63081. var ray = this.ray;
  63082. var point = this._renderPoints[1];
  63083. var len = Math.min(ray.length, 1000000);
  63084. point.copyFrom(ray.direction);
  63085. point.scaleInPlace(len);
  63086. point.addInPlace(ray.origin);
  63087. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  63088. };
  63089. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  63090. this._attachedToMesh = mesh;
  63091. var ray = this.ray;
  63092. if (!ray.direction) {
  63093. ray.direction = BABYLON.Vector3.Zero();
  63094. }
  63095. if (!ray.origin) {
  63096. ray.origin = BABYLON.Vector3.Zero();
  63097. }
  63098. if (length) {
  63099. ray.length = length;
  63100. }
  63101. if (!meshSpaceOrigin) {
  63102. meshSpaceOrigin = BABYLON.Vector3.Zero();
  63103. }
  63104. if (!meshSpaceDirection) {
  63105. // -1 so that this will work with Mesh.lookAt
  63106. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  63107. }
  63108. if (!this._meshSpaceDirection) {
  63109. this._meshSpaceDirection = meshSpaceDirection.clone();
  63110. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  63111. }
  63112. else {
  63113. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  63114. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  63115. }
  63116. if (!this._updateToMeshFunction) {
  63117. this._updateToMeshFunction = this._updateToMesh.bind(this);
  63118. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  63119. }
  63120. this._updateToMesh();
  63121. };
  63122. RayHelper.prototype.detachFromMesh = function () {
  63123. if (this._attachedToMesh) {
  63124. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  63125. this._attachedToMesh = null;
  63126. this._updateToMeshFunction = null;
  63127. }
  63128. };
  63129. RayHelper.prototype._updateToMesh = function () {
  63130. var ray = this.ray;
  63131. if (this._attachedToMesh._isDisposed) {
  63132. this.detachFromMesh();
  63133. return;
  63134. }
  63135. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  63136. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  63137. };
  63138. RayHelper.prototype.dispose = function () {
  63139. this.hide();
  63140. this.detachFromMesh();
  63141. this.ray = null;
  63142. };
  63143. return RayHelper;
  63144. }());
  63145. BABYLON.RayHelper = RayHelper;
  63146. })(BABYLON || (BABYLON = {}));
  63147. //# sourceMappingURL=babylon.rayHelper.js.map
  63148. var BABYLON;
  63149. (function (BABYLON) {
  63150. var DebugLayer = (function () {
  63151. function DebugLayer(scene) {
  63152. this._scene = scene;
  63153. }
  63154. /** Creates the inspector window. */
  63155. DebugLayer.prototype._createInspector = function (config) {
  63156. if (config === void 0) { config = {}; }
  63157. var popup = config.popup || false;
  63158. var initialTab = config.initialTab || 0;
  63159. var parentElement = config.parentElement || null;
  63160. if (!this._inspector) {
  63161. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  63162. } // else nothing to do,; instance is already existing
  63163. };
  63164. DebugLayer.prototype.isVisible = function () {
  63165. if (!this._inspector) {
  63166. return false;
  63167. }
  63168. return true;
  63169. };
  63170. DebugLayer.prototype.hide = function () {
  63171. if (this._inspector) {
  63172. try {
  63173. this._inspector.dispose();
  63174. }
  63175. catch (e) {
  63176. // If the inspector has been removed directly from the inspector tool
  63177. }
  63178. this._inspector = null;
  63179. }
  63180. };
  63181. DebugLayer.prototype.show = function (config) {
  63182. if (config === void 0) { config = {}; }
  63183. if (typeof INSPECTOR == 'undefined') {
  63184. // Load inspector and add it to the DOM
  63185. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  63186. }
  63187. else {
  63188. // Otherwise creates the inspector
  63189. this._createInspector(config);
  63190. }
  63191. };
  63192. // Get protocol used - http or https
  63193. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  63194. return DebugLayer;
  63195. }());
  63196. BABYLON.DebugLayer = DebugLayer;
  63197. })(BABYLON || (BABYLON = {}));
  63198. //# sourceMappingURL=babylon.debugLayer.js.map
  63199. var BABYLON;
  63200. (function (BABYLON) {
  63201. var Debug;
  63202. (function (Debug) {
  63203. var PhysicsViewer = (function () {
  63204. function PhysicsViewer(scene) {
  63205. this._impostors = [];
  63206. this._meshes = [];
  63207. this._numMeshes = 0;
  63208. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  63209. this._physicsEnginePlugin = this._scene.getPhysicsEngine().getPhysicsPlugin();
  63210. }
  63211. PhysicsViewer.prototype._updateDebugMeshes = function () {
  63212. var plugin = this._physicsEnginePlugin;
  63213. for (var i = 0; i < this._numMeshes; i++) {
  63214. if (this._impostors[i].isDisposed) {
  63215. this.hideImpostor(this._impostors[i--]);
  63216. }
  63217. else {
  63218. plugin.syncMeshWithImpostor(this._meshes[i], this._impostors[i]);
  63219. }
  63220. }
  63221. };
  63222. PhysicsViewer.prototype.showImpostor = function (impostor) {
  63223. for (var i = 0; i < this._numMeshes; i++) {
  63224. if (this._impostors[i] == impostor) {
  63225. return;
  63226. }
  63227. }
  63228. var debugMesh = this._getDebugMesh(impostor, this._scene);
  63229. if (debugMesh) {
  63230. this._impostors[this._numMeshes] = impostor;
  63231. this._meshes[this._numMeshes] = debugMesh;
  63232. if (this._numMeshes === 0) {
  63233. this._renderFunction = this._updateDebugMeshes.bind(this);
  63234. this._scene.registerBeforeRender(this._renderFunction);
  63235. }
  63236. this._numMeshes++;
  63237. }
  63238. };
  63239. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  63240. var removed = false;
  63241. for (var i = 0; i < this._numMeshes; i++) {
  63242. if (this._impostors[i] == impostor) {
  63243. this._scene.removeMesh(this._meshes[i]);
  63244. this._meshes[i].dispose();
  63245. this._numMeshes--;
  63246. if (this._numMeshes > 0) {
  63247. this._meshes[i] = this._meshes[this._numMeshes];
  63248. this._impostors[i] = this._impostors[this._numMeshes];
  63249. this._meshes[this._numMeshes] = null;
  63250. this._impostors[this._numMeshes] = null;
  63251. }
  63252. else {
  63253. this._meshes[0] = null;
  63254. this._impostors[0] = null;
  63255. }
  63256. removed = true;
  63257. break;
  63258. }
  63259. }
  63260. if (removed && this._numMeshes === 0) {
  63261. this._scene.unregisterBeforeRender(this._renderFunction);
  63262. }
  63263. };
  63264. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  63265. if (!this._debugMaterial) {
  63266. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  63267. this._debugMaterial.wireframe = true;
  63268. }
  63269. return this._debugMaterial;
  63270. };
  63271. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  63272. if (!this._debugBoxMesh) {
  63273. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  63274. this._debugBoxMesh.renderingGroupId = 1;
  63275. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  63276. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  63277. scene.removeMesh(this._debugBoxMesh);
  63278. }
  63279. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  63280. };
  63281. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  63282. if (!this._debugSphereMesh) {
  63283. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  63284. this._debugSphereMesh.renderingGroupId = 1;
  63285. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  63286. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  63287. scene.removeMesh(this._debugSphereMesh);
  63288. }
  63289. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  63290. };
  63291. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  63292. var body = impostor.physicsBody;
  63293. var shape = body.shapes[0];
  63294. var mesh;
  63295. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  63296. mesh = this._getDebugBoxMesh(scene);
  63297. impostor.getBoxSizeToRef(mesh.scaling);
  63298. }
  63299. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  63300. mesh = this._getDebugSphereMesh(scene);
  63301. var radius = impostor.getRadius();
  63302. mesh.scaling.x = radius * 2;
  63303. mesh.scaling.y = radius * 2;
  63304. mesh.scaling.z = radius * 2;
  63305. }
  63306. return mesh;
  63307. };
  63308. PhysicsViewer.prototype.dispose = function () {
  63309. for (var i = 0; i < this._numMeshes; i++) {
  63310. this.hideImpostor(this._impostors[i]);
  63311. }
  63312. if (this._debugBoxMesh) {
  63313. this._debugBoxMesh.dispose();
  63314. }
  63315. if (this._debugSphereMesh) {
  63316. this._debugSphereMesh.dispose();
  63317. }
  63318. if (this._debugMaterial) {
  63319. this._debugMaterial.dispose();
  63320. }
  63321. this._impostors.length = 0;
  63322. this._scene = null;
  63323. this._physicsEnginePlugin = null;
  63324. };
  63325. return PhysicsViewer;
  63326. }());
  63327. Debug.PhysicsViewer = PhysicsViewer;
  63328. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  63329. })(BABYLON || (BABYLON = {}));
  63330. //# sourceMappingURL=babylon.physicsViewer.js.map
  63331. var BABYLON;
  63332. (function (BABYLON) {
  63333. var BoundingBoxRenderer = (function () {
  63334. function BoundingBoxRenderer(scene) {
  63335. this.frontColor = new BABYLON.Color3(1, 1, 1);
  63336. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  63337. this.showBackLines = true;
  63338. this.renderList = new BABYLON.SmartArray(32);
  63339. this._vertexBuffers = {};
  63340. this._scene = scene;
  63341. }
  63342. BoundingBoxRenderer.prototype._prepareRessources = function () {
  63343. if (this._colorShader) {
  63344. return;
  63345. }
  63346. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  63347. attributes: [BABYLON.VertexBuffer.PositionKind],
  63348. uniforms: ["world", "viewProjection", "color"]
  63349. });
  63350. var engine = this._scene.getEngine();
  63351. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  63352. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  63353. this._createIndexBuffer();
  63354. };
  63355. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  63356. var engine = this._scene.getEngine();
  63357. 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]);
  63358. };
  63359. BoundingBoxRenderer.prototype._rebuild = function () {
  63360. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  63361. this._createIndexBuffer();
  63362. };
  63363. BoundingBoxRenderer.prototype.reset = function () {
  63364. this.renderList.reset();
  63365. };
  63366. BoundingBoxRenderer.prototype.render = function () {
  63367. if (this.renderList.length === 0) {
  63368. return;
  63369. }
  63370. this._prepareRessources();
  63371. if (!this._colorShader.isReady()) {
  63372. return;
  63373. }
  63374. var engine = this._scene.getEngine();
  63375. engine.setDepthWrite(false);
  63376. this._colorShader._preBind();
  63377. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  63378. var boundingBox = this.renderList.data[boundingBoxIndex];
  63379. var min = boundingBox.minimum;
  63380. var max = boundingBox.maximum;
  63381. var diff = max.subtract(min);
  63382. var median = min.add(diff.scale(0.5));
  63383. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  63384. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  63385. .multiply(boundingBox.getWorldMatrix());
  63386. // VBOs
  63387. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  63388. if (this.showBackLines) {
  63389. // Back
  63390. engine.setDepthFunctionToGreaterOrEqual();
  63391. this._scene.resetCachedMaterial();
  63392. this._colorShader.setColor4("color", this.backColor.toColor4());
  63393. this._colorShader.bind(worldMatrix);
  63394. // Draw order
  63395. engine.draw(false, 0, 24);
  63396. }
  63397. // Front
  63398. engine.setDepthFunctionToLess();
  63399. this._scene.resetCachedMaterial();
  63400. this._colorShader.setColor4("color", this.frontColor.toColor4());
  63401. this._colorShader.bind(worldMatrix);
  63402. // Draw order
  63403. engine.draw(false, 0, 24);
  63404. }
  63405. this._colorShader.unbind();
  63406. engine.setDepthFunctionToLessOrEqual();
  63407. engine.setDepthWrite(true);
  63408. };
  63409. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  63410. this._prepareRessources();
  63411. if (!this._colorShader.isReady()) {
  63412. return;
  63413. }
  63414. var engine = this._scene.getEngine();
  63415. engine.setDepthWrite(false);
  63416. engine.setColorWrite(false);
  63417. this._colorShader._preBind();
  63418. var boundingBox = mesh._boundingInfo.boundingBox;
  63419. var min = boundingBox.minimum;
  63420. var max = boundingBox.maximum;
  63421. var diff = max.subtract(min);
  63422. var median = min.add(diff.scale(0.5));
  63423. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  63424. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  63425. .multiply(boundingBox.getWorldMatrix());
  63426. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  63427. engine.setDepthFunctionToLess();
  63428. this._scene.resetCachedMaterial();
  63429. this._colorShader.bind(worldMatrix);
  63430. engine.draw(false, 0, 24);
  63431. this._colorShader.unbind();
  63432. engine.setDepthFunctionToLessOrEqual();
  63433. engine.setDepthWrite(true);
  63434. engine.setColorWrite(true);
  63435. };
  63436. BoundingBoxRenderer.prototype.dispose = function () {
  63437. if (!this._colorShader) {
  63438. return;
  63439. }
  63440. this.renderList.dispose();
  63441. this._colorShader.dispose();
  63442. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63443. if (buffer) {
  63444. buffer.dispose();
  63445. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  63446. }
  63447. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  63448. };
  63449. return BoundingBoxRenderer;
  63450. }());
  63451. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  63452. })(BABYLON || (BABYLON = {}));
  63453. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  63454. var BABYLON;
  63455. (function (BABYLON) {
  63456. var MorphTarget = (function () {
  63457. function MorphTarget(name, influence) {
  63458. if (influence === void 0) { influence = 0; }
  63459. this.name = name;
  63460. this.animations = new Array();
  63461. this.onInfluenceChanged = new BABYLON.Observable();
  63462. this.influence = influence;
  63463. }
  63464. Object.defineProperty(MorphTarget.prototype, "influence", {
  63465. get: function () {
  63466. return this._influence;
  63467. },
  63468. set: function (influence) {
  63469. if (this._influence === influence) {
  63470. return;
  63471. }
  63472. var previous = this._influence;
  63473. this._influence = influence;
  63474. if (this.onInfluenceChanged.hasObservers) {
  63475. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  63476. }
  63477. },
  63478. enumerable: true,
  63479. configurable: true
  63480. });
  63481. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  63482. get: function () {
  63483. return this._normals !== undefined;
  63484. },
  63485. enumerable: true,
  63486. configurable: true
  63487. });
  63488. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  63489. get: function () {
  63490. return this._tangents !== undefined;
  63491. },
  63492. enumerable: true,
  63493. configurable: true
  63494. });
  63495. MorphTarget.prototype.setPositions = function (data) {
  63496. this._positions = new Float32Array(data);
  63497. };
  63498. MorphTarget.prototype.getPositions = function () {
  63499. return this._positions;
  63500. };
  63501. MorphTarget.prototype.setNormals = function (data) {
  63502. this._normals = new Float32Array(data);
  63503. };
  63504. MorphTarget.prototype.getNormals = function () {
  63505. return this._normals;
  63506. };
  63507. MorphTarget.prototype.setTangents = function (data) {
  63508. this._tangents = new Float32Array(data);
  63509. };
  63510. MorphTarget.prototype.getTangents = function () {
  63511. return this._tangents;
  63512. };
  63513. /**
  63514. * Serializes the current target into a Serialization object.
  63515. * Returns the serialized object.
  63516. */
  63517. MorphTarget.prototype.serialize = function () {
  63518. var serializationObject = {};
  63519. serializationObject.name = this.name;
  63520. serializationObject.influence = this.influence;
  63521. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  63522. if (this.hasNormals) {
  63523. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  63524. }
  63525. if (this.hasTangents) {
  63526. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  63527. }
  63528. return serializationObject;
  63529. };
  63530. // Statics
  63531. MorphTarget.Parse = function (serializationObject) {
  63532. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  63533. result.setPositions(serializationObject.positions);
  63534. if (serializationObject.normals) {
  63535. result.setNormals(serializationObject.normals);
  63536. }
  63537. if (serializationObject.tangents) {
  63538. result.setTangents(serializationObject.tangents);
  63539. }
  63540. return result;
  63541. };
  63542. MorphTarget.FromMesh = function (mesh, name, influence) {
  63543. if (!name) {
  63544. name = mesh.name;
  63545. }
  63546. var result = new MorphTarget(name, influence);
  63547. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  63548. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  63549. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  63550. }
  63551. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  63552. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  63553. }
  63554. return result;
  63555. };
  63556. return MorphTarget;
  63557. }());
  63558. BABYLON.MorphTarget = MorphTarget;
  63559. })(BABYLON || (BABYLON = {}));
  63560. //# sourceMappingURL=babylon.morphTarget.js.map
  63561. var BABYLON;
  63562. (function (BABYLON) {
  63563. var MorphTargetManager = (function () {
  63564. function MorphTargetManager(scene) {
  63565. this._targets = new Array();
  63566. this._targetObservable = new Array();
  63567. this._activeTargets = new BABYLON.SmartArray(16);
  63568. this._supportsNormals = false;
  63569. this._supportsTangents = false;
  63570. this._vertexCount = 0;
  63571. this._uniqueId = 0;
  63572. this._tempInfluences = new Array();
  63573. if (!scene) {
  63574. scene = BABYLON.Engine.LastCreatedScene;
  63575. }
  63576. this._scene = scene;
  63577. this._scene.morphTargetManagers.push(this);
  63578. this._uniqueId = scene.getUniqueId();
  63579. }
  63580. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  63581. get: function () {
  63582. return this._uniqueId;
  63583. },
  63584. enumerable: true,
  63585. configurable: true
  63586. });
  63587. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  63588. get: function () {
  63589. return this._vertexCount;
  63590. },
  63591. enumerable: true,
  63592. configurable: true
  63593. });
  63594. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  63595. get: function () {
  63596. return this._supportsNormals;
  63597. },
  63598. enumerable: true,
  63599. configurable: true
  63600. });
  63601. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  63602. get: function () {
  63603. return this._supportsTangents;
  63604. },
  63605. enumerable: true,
  63606. configurable: true
  63607. });
  63608. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  63609. get: function () {
  63610. return this._targets.length;
  63611. },
  63612. enumerable: true,
  63613. configurable: true
  63614. });
  63615. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  63616. get: function () {
  63617. return this._activeTargets.length;
  63618. },
  63619. enumerable: true,
  63620. configurable: true
  63621. });
  63622. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  63623. get: function () {
  63624. return this._influences;
  63625. },
  63626. enumerable: true,
  63627. configurable: true
  63628. });
  63629. MorphTargetManager.prototype.getActiveTarget = function (index) {
  63630. return this._activeTargets.data[index];
  63631. };
  63632. MorphTargetManager.prototype.getTarget = function (index) {
  63633. return this._targets[index];
  63634. };
  63635. MorphTargetManager.prototype.addTarget = function (target) {
  63636. var _this = this;
  63637. if (this._vertexCount) {
  63638. if (this._vertexCount !== target.getPositions().length / 3) {
  63639. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  63640. return;
  63641. }
  63642. }
  63643. this._targets.push(target);
  63644. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  63645. _this._syncActiveTargets(needUpdate);
  63646. }));
  63647. this._syncActiveTargets(true);
  63648. };
  63649. MorphTargetManager.prototype.removeTarget = function (target) {
  63650. var index = this._targets.indexOf(target);
  63651. if (index >= 0) {
  63652. this._targets.splice(index, 1);
  63653. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  63654. this._vertexCount = 0;
  63655. this._syncActiveTargets(true);
  63656. }
  63657. };
  63658. /**
  63659. * Serializes the current manager into a Serialization object.
  63660. * Returns the serialized object.
  63661. */
  63662. MorphTargetManager.prototype.serialize = function () {
  63663. var serializationObject = {};
  63664. serializationObject.id = this.uniqueId;
  63665. serializationObject.targets = [];
  63666. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  63667. var target = _a[_i];
  63668. serializationObject.targets.push(target.serialize());
  63669. }
  63670. return serializationObject;
  63671. };
  63672. MorphTargetManager.prototype._onInfluenceChanged = function (needUpdate) {
  63673. this._syncActiveTargets(needUpdate);
  63674. };
  63675. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  63676. var influenceCount = 0;
  63677. this._activeTargets.reset();
  63678. this._supportsNormals = true;
  63679. this._supportsTangents = true;
  63680. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  63681. var target = _a[_i];
  63682. if (target.influence > 0) {
  63683. this._activeTargets.push(target);
  63684. this._tempInfluences[influenceCount++] = target.influence;
  63685. this._supportsNormals = this._supportsNormals && target.hasNormals;
  63686. this._supportsTangents = this._supportsTangents && target.hasTangents;
  63687. if (this._vertexCount === 0) {
  63688. this._vertexCount = target.getPositions().length / 3;
  63689. }
  63690. }
  63691. }
  63692. if (!this._influences || this._influences.length !== influenceCount) {
  63693. this._influences = new Float32Array(influenceCount);
  63694. }
  63695. for (var index = 0; index < influenceCount; index++) {
  63696. this._influences[index] = this._tempInfluences[index];
  63697. }
  63698. if (needUpdate) {
  63699. // Flag meshes as dirty to resync with the active targets
  63700. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  63701. var mesh = _c[_b];
  63702. if (mesh.morphTargetManager === this) {
  63703. mesh._syncGeometryWithMorphTargetManager();
  63704. }
  63705. }
  63706. }
  63707. };
  63708. // Statics
  63709. MorphTargetManager.Parse = function (serializationObject, scene) {
  63710. var result = new MorphTargetManager(scene);
  63711. result._uniqueId = serializationObject.id;
  63712. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  63713. var targetData = _a[_i];
  63714. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  63715. }
  63716. return result;
  63717. };
  63718. return MorphTargetManager;
  63719. }());
  63720. BABYLON.MorphTargetManager = MorphTargetManager;
  63721. })(BABYLON || (BABYLON = {}));
  63722. //# sourceMappingURL=babylon.morphTargetManager.js.map
  63723. var BABYLON;
  63724. (function (BABYLON) {
  63725. /**
  63726. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  63727. * It can help converting any input color in a desired output one. This can then be used to create effects
  63728. * from sepia, black and white to sixties or futuristic rendering...
  63729. *
  63730. * The only supported format is currently 3dl.
  63731. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  63732. */
  63733. var ColorGradingTexture = (function (_super) {
  63734. __extends(ColorGradingTexture, _super);
  63735. /**
  63736. * Instantiates a ColorGradingTexture from the following parameters.
  63737. *
  63738. * @param url The location of the color gradind data (currently only supporting 3dl)
  63739. * @param scene The scene the texture will be used in
  63740. */
  63741. function ColorGradingTexture(url, scene) {
  63742. var _this = _super.call(this, scene) || this;
  63743. if (!url) {
  63744. return _this;
  63745. }
  63746. _this._textureMatrix = BABYLON.Matrix.Identity();
  63747. _this.name = url;
  63748. _this.url = url;
  63749. _this.hasAlpha = false;
  63750. _this.isCube = false;
  63751. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63752. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63753. _this.anisotropicFilteringLevel = 1;
  63754. _this._texture = _this._getFromCache(url, true);
  63755. if (!_this._texture) {
  63756. if (!scene.useDelayedTextureLoading) {
  63757. _this.loadTexture();
  63758. }
  63759. else {
  63760. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63761. }
  63762. }
  63763. return _this;
  63764. }
  63765. /**
  63766. * Returns the texture matrix used in most of the material.
  63767. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  63768. */
  63769. ColorGradingTexture.prototype.getTextureMatrix = function () {
  63770. return this._textureMatrix;
  63771. };
  63772. /**
  63773. * Occurs when the file being loaded is a .3dl LUT file.
  63774. */
  63775. ColorGradingTexture.prototype.load3dlTexture = function () {
  63776. var _this = this;
  63777. var mipLevels = 0;
  63778. var floatArrayView = null;
  63779. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63780. this._texture = texture;
  63781. var callback = function (text) {
  63782. var data;
  63783. var tempData;
  63784. var line;
  63785. var lines = text.split('\n');
  63786. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  63787. var maxColor = 0;
  63788. for (var i = 0; i < lines.length; i++) {
  63789. line = lines[i];
  63790. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  63791. continue;
  63792. if (line.indexOf('#') === 0)
  63793. continue;
  63794. var words = line.split(" ");
  63795. if (size === 0) {
  63796. // Number of space + one
  63797. size = words.length;
  63798. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  63799. tempData = new Float32Array(size * size * size * 4);
  63800. continue;
  63801. }
  63802. if (size != 0) {
  63803. var r = Math.max(parseInt(words[0]), 0);
  63804. var g = Math.max(parseInt(words[1]), 0);
  63805. var b = Math.max(parseInt(words[2]), 0);
  63806. maxColor = Math.max(r, maxColor);
  63807. maxColor = Math.max(g, maxColor);
  63808. maxColor = Math.max(b, maxColor);
  63809. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  63810. tempData[pixelStorageIndex + 0] = r;
  63811. tempData[pixelStorageIndex + 1] = g;
  63812. tempData[pixelStorageIndex + 2] = b;
  63813. pixelIndexSlice++;
  63814. if (pixelIndexSlice % size == 0) {
  63815. pixelIndexH++;
  63816. pixelIndexSlice = 0;
  63817. if (pixelIndexH % size == 0) {
  63818. pixelIndexW++;
  63819. pixelIndexH = 0;
  63820. }
  63821. }
  63822. }
  63823. }
  63824. for (var i = 0; i < tempData.length; i++) {
  63825. if (i > 0 && (i + 1) % 4 === 0) {
  63826. data[i] = 255;
  63827. }
  63828. else {
  63829. var value = tempData[i];
  63830. data[i] = (value / maxColor * 255);
  63831. }
  63832. }
  63833. texture.updateSize(size * size, size);
  63834. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  63835. };
  63836. BABYLON.Tools.LoadFile(this.url, callback);
  63837. return this._texture;
  63838. };
  63839. /**
  63840. * Starts the loading process of the texture.
  63841. */
  63842. ColorGradingTexture.prototype.loadTexture = function () {
  63843. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  63844. this.load3dlTexture();
  63845. }
  63846. };
  63847. /**
  63848. * Clones the color gradind texture.
  63849. */
  63850. ColorGradingTexture.prototype.clone = function () {
  63851. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  63852. // Base texture
  63853. newTexture.level = this.level;
  63854. return newTexture;
  63855. };
  63856. /**
  63857. * Called during delayed load for textures.
  63858. */
  63859. ColorGradingTexture.prototype.delayLoad = function () {
  63860. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63861. return;
  63862. }
  63863. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63864. this._texture = this._getFromCache(this.url, true);
  63865. if (!this._texture) {
  63866. this.loadTexture();
  63867. }
  63868. };
  63869. /**
  63870. * Parses a color grading texture serialized by Babylon.
  63871. * @param parsedTexture The texture information being parsedTexture
  63872. * @param scene The scene to load the texture in
  63873. * @param rootUrl The root url of the data assets to load
  63874. * @return A color gradind texture
  63875. */
  63876. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63877. var texture = null;
  63878. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  63879. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  63880. texture.name = parsedTexture.name;
  63881. texture.level = parsedTexture.level;
  63882. }
  63883. return texture;
  63884. };
  63885. /**
  63886. * Serializes the LUT texture to json format.
  63887. */
  63888. ColorGradingTexture.prototype.serialize = function () {
  63889. if (!this.name) {
  63890. return null;
  63891. }
  63892. var serializationObject = {};
  63893. serializationObject.name = this.name;
  63894. serializationObject.level = this.level;
  63895. serializationObject.customType = "BABYLON.ColorGradingTexture";
  63896. return serializationObject;
  63897. };
  63898. /**
  63899. * Empty line regex stored for GC.
  63900. */
  63901. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  63902. return ColorGradingTexture;
  63903. }(BABYLON.BaseTexture));
  63904. BABYLON.ColorGradingTexture = ColorGradingTexture;
  63905. })(BABYLON || (BABYLON = {}));
  63906. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  63907. var BABYLON;
  63908. (function (BABYLON) {
  63909. /**
  63910. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  63911. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  63912. * 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;
  63913. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  63914. */
  63915. var ColorCurves = (function () {
  63916. function ColorCurves() {
  63917. this._dirty = true;
  63918. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  63919. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  63920. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  63921. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  63922. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  63923. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  63924. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  63925. this._globalHue = 30;
  63926. this._globalDensity = 0;
  63927. this._globalSaturation = 0;
  63928. this._globalExposure = 0;
  63929. this._highlightsHue = 30;
  63930. this._highlightsDensity = 0;
  63931. this._highlightsSaturation = 0;
  63932. this._highlightsExposure = 0;
  63933. this._midtonesHue = 30;
  63934. this._midtonesDensity = 0;
  63935. this._midtonesSaturation = 0;
  63936. this._midtonesExposure = 0;
  63937. this._shadowsHue = 30;
  63938. this._shadowsDensity = 0;
  63939. this._shadowsSaturation = 0;
  63940. this._shadowsExposure = 0;
  63941. }
  63942. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  63943. /**
  63944. * Gets the global Hue value.
  63945. * 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).
  63946. */
  63947. get: function () {
  63948. return this._globalHue;
  63949. },
  63950. /**
  63951. * Sets the global Hue value.
  63952. * 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).
  63953. */
  63954. set: function (value) {
  63955. this._globalHue = value;
  63956. this._dirty = true;
  63957. },
  63958. enumerable: true,
  63959. configurable: true
  63960. });
  63961. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  63962. /**
  63963. * Gets the global Density value.
  63964. * 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.
  63965. * Values less than zero provide a filter of opposite hue.
  63966. */
  63967. get: function () {
  63968. return this._globalDensity;
  63969. },
  63970. /**
  63971. * Sets the global Density value.
  63972. * 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.
  63973. * Values less than zero provide a filter of opposite hue.
  63974. */
  63975. set: function (value) {
  63976. this._globalDensity = value;
  63977. this._dirty = true;
  63978. },
  63979. enumerable: true,
  63980. configurable: true
  63981. });
  63982. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  63983. /**
  63984. * Gets the global Saturation value.
  63985. * 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.
  63986. */
  63987. get: function () {
  63988. return this._globalSaturation;
  63989. },
  63990. /**
  63991. * Sets the global Saturation value.
  63992. * 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.
  63993. */
  63994. set: function (value) {
  63995. this._globalSaturation = value;
  63996. this._dirty = true;
  63997. },
  63998. enumerable: true,
  63999. configurable: true
  64000. });
  64001. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  64002. /**
  64003. * Gets the highlights Hue value.
  64004. * 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).
  64005. */
  64006. get: function () {
  64007. return this._highlightsHue;
  64008. },
  64009. /**
  64010. * Sets the highlights Hue value.
  64011. * 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).
  64012. */
  64013. set: function (value) {
  64014. this._highlightsHue = value;
  64015. this._dirty = true;
  64016. },
  64017. enumerable: true,
  64018. configurable: true
  64019. });
  64020. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  64021. /**
  64022. * Gets the highlights Density value.
  64023. * 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.
  64024. * Values less than zero provide a filter of opposite hue.
  64025. */
  64026. get: function () {
  64027. return this._highlightsDensity;
  64028. },
  64029. /**
  64030. * Sets the highlights Density value.
  64031. * 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.
  64032. * Values less than zero provide a filter of opposite hue.
  64033. */
  64034. set: function (value) {
  64035. this._highlightsDensity = value;
  64036. this._dirty = true;
  64037. },
  64038. enumerable: true,
  64039. configurable: true
  64040. });
  64041. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  64042. /**
  64043. * Gets the highlights Saturation value.
  64044. * 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.
  64045. */
  64046. get: function () {
  64047. return this._highlightsSaturation;
  64048. },
  64049. /**
  64050. * Sets the highlights Saturation value.
  64051. * 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.
  64052. */
  64053. set: function (value) {
  64054. this._highlightsSaturation = value;
  64055. this._dirty = true;
  64056. },
  64057. enumerable: true,
  64058. configurable: true
  64059. });
  64060. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  64061. /**
  64062. * Gets the highlights Exposure value.
  64063. * 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.
  64064. */
  64065. get: function () {
  64066. return this._highlightsExposure;
  64067. },
  64068. /**
  64069. * Sets the highlights Exposure value.
  64070. * 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.
  64071. */
  64072. set: function (value) {
  64073. this._highlightsExposure = value;
  64074. this._dirty = true;
  64075. },
  64076. enumerable: true,
  64077. configurable: true
  64078. });
  64079. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  64080. /**
  64081. * Gets the midtones Hue value.
  64082. * 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).
  64083. */
  64084. get: function () {
  64085. return this._midtonesHue;
  64086. },
  64087. /**
  64088. * Sets the midtones Hue value.
  64089. * 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).
  64090. */
  64091. set: function (value) {
  64092. this._midtonesHue = value;
  64093. this._dirty = true;
  64094. },
  64095. enumerable: true,
  64096. configurable: true
  64097. });
  64098. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  64099. /**
  64100. * Gets the midtones Density value.
  64101. * 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.
  64102. * Values less than zero provide a filter of opposite hue.
  64103. */
  64104. get: function () {
  64105. return this._midtonesDensity;
  64106. },
  64107. /**
  64108. * Sets the midtones Density value.
  64109. * 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.
  64110. * Values less than zero provide a filter of opposite hue.
  64111. */
  64112. set: function (value) {
  64113. this._midtonesDensity = value;
  64114. this._dirty = true;
  64115. },
  64116. enumerable: true,
  64117. configurable: true
  64118. });
  64119. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  64120. /**
  64121. * Gets the midtones Saturation value.
  64122. * 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.
  64123. */
  64124. get: function () {
  64125. return this._midtonesSaturation;
  64126. },
  64127. /**
  64128. * Sets the midtones Saturation value.
  64129. * 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.
  64130. */
  64131. set: function (value) {
  64132. this._midtonesSaturation = value;
  64133. this._dirty = true;
  64134. },
  64135. enumerable: true,
  64136. configurable: true
  64137. });
  64138. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  64139. /**
  64140. * Gets the midtones Exposure value.
  64141. * 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.
  64142. */
  64143. get: function () {
  64144. return this._midtonesExposure;
  64145. },
  64146. /**
  64147. * Sets the midtones Exposure value.
  64148. * 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.
  64149. */
  64150. set: function (value) {
  64151. this._midtonesExposure = value;
  64152. this._dirty = true;
  64153. },
  64154. enumerable: true,
  64155. configurable: true
  64156. });
  64157. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  64158. /**
  64159. * Gets the shadows Hue value.
  64160. * 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).
  64161. */
  64162. get: function () {
  64163. return this._shadowsHue;
  64164. },
  64165. /**
  64166. * Sets the shadows Hue value.
  64167. * 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).
  64168. */
  64169. set: function (value) {
  64170. this._shadowsHue = value;
  64171. this._dirty = true;
  64172. },
  64173. enumerable: true,
  64174. configurable: true
  64175. });
  64176. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  64177. /**
  64178. * Gets the shadows Density value.
  64179. * 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.
  64180. * Values less than zero provide a filter of opposite hue.
  64181. */
  64182. get: function () {
  64183. return this._shadowsDensity;
  64184. },
  64185. /**
  64186. * Sets the shadows Density value.
  64187. * 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.
  64188. * Values less than zero provide a filter of opposite hue.
  64189. */
  64190. set: function (value) {
  64191. this._shadowsDensity = value;
  64192. this._dirty = true;
  64193. },
  64194. enumerable: true,
  64195. configurable: true
  64196. });
  64197. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  64198. /**
  64199. * Gets the shadows Saturation value.
  64200. * 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.
  64201. */
  64202. get: function () {
  64203. return this._shadowsSaturation;
  64204. },
  64205. /**
  64206. * Sets the shadows Saturation value.
  64207. * 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.
  64208. */
  64209. set: function (value) {
  64210. this._shadowsSaturation = value;
  64211. this._dirty = true;
  64212. },
  64213. enumerable: true,
  64214. configurable: true
  64215. });
  64216. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  64217. /**
  64218. * Gets the shadows Exposure value.
  64219. * 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.
  64220. */
  64221. get: function () {
  64222. return this._shadowsExposure;
  64223. },
  64224. /**
  64225. * Sets the shadows Exposure value.
  64226. * 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.
  64227. */
  64228. set: function (value) {
  64229. this._shadowsExposure = value;
  64230. this._dirty = true;
  64231. },
  64232. enumerable: true,
  64233. configurable: true
  64234. });
  64235. ColorCurves.prototype.getClassName = function () {
  64236. return "ColorCurves";
  64237. };
  64238. /**
  64239. * Binds the color curves to the shader.
  64240. * @param colorCurves The color curve to bind
  64241. * @param effect The effect to bind to
  64242. */
  64243. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  64244. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  64245. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  64246. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  64247. if (colorCurves._dirty) {
  64248. colorCurves._dirty = false;
  64249. // Fill in global info.
  64250. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  64251. // Compute highlights info.
  64252. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  64253. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  64254. // Compute midtones info.
  64255. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  64256. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  64257. // Compute shadows info.
  64258. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  64259. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  64260. // Compute deltas (neutral is midtones).
  64261. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  64262. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  64263. }
  64264. if (effect) {
  64265. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  64266. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  64267. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  64268. }
  64269. };
  64270. /**
  64271. * Prepare the list of uniforms associated with the ColorCurves effects.
  64272. * @param uniformsList The list of uniforms used in the effect
  64273. */
  64274. ColorCurves.PrepareUniforms = function (uniformsList) {
  64275. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  64276. };
  64277. /**
  64278. * Returns color grading data based on a hue, density, saturation and exposure value.
  64279. * @param filterHue The hue of the color filter.
  64280. * @param filterDensity The density of the color filter.
  64281. * @param saturation The saturation.
  64282. * @param exposure The exposure.
  64283. * @param result The result data container.
  64284. */
  64285. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  64286. if (hue == null) {
  64287. return;
  64288. }
  64289. hue = ColorCurves.clamp(hue, 0, 360);
  64290. density = ColorCurves.clamp(density, -100, 100);
  64291. saturation = ColorCurves.clamp(saturation, -100, 100);
  64292. exposure = ColorCurves.clamp(exposure, -100, 100);
  64293. // Remap the slider/config filter density with non-linear mapping and also scale by half
  64294. // so that the maximum filter density is only 50% control. This provides fine control
  64295. // for small values and reasonable range.
  64296. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  64297. density *= 0.5;
  64298. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  64299. if (density < 0) {
  64300. density *= -1;
  64301. hue = (hue + 180) % 360;
  64302. }
  64303. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  64304. result.scaleToRef(2, result);
  64305. result.a = 1 + 0.01 * saturation;
  64306. };
  64307. /**
  64308. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  64309. * @param value The input slider value in range [-100,100].
  64310. * @returns Adjusted value.
  64311. */
  64312. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  64313. value /= 100;
  64314. var x = Math.abs(value);
  64315. x = Math.pow(x, 2);
  64316. if (value < 0) {
  64317. x *= -1;
  64318. }
  64319. x *= 100;
  64320. return x;
  64321. };
  64322. /**
  64323. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  64324. * @param hue The hue (H) input.
  64325. * @param saturation The saturation (S) input.
  64326. * @param brightness The brightness (B) input.
  64327. * @result An RGBA color represented as Vector4.
  64328. */
  64329. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  64330. var h = ColorCurves.clamp(hue, 0, 360);
  64331. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  64332. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  64333. if (s === 0) {
  64334. result.r = v;
  64335. result.g = v;
  64336. result.b = v;
  64337. }
  64338. else {
  64339. // sector 0 to 5
  64340. h /= 60;
  64341. var i = Math.floor(h);
  64342. // fractional part of h
  64343. var f = h - i;
  64344. var p = v * (1 - s);
  64345. var q = v * (1 - s * f);
  64346. var t = v * (1 - s * (1 - f));
  64347. switch (i) {
  64348. case 0:
  64349. result.r = v;
  64350. result.g = t;
  64351. result.b = p;
  64352. break;
  64353. case 1:
  64354. result.r = q;
  64355. result.g = v;
  64356. result.b = p;
  64357. break;
  64358. case 2:
  64359. result.r = p;
  64360. result.g = v;
  64361. result.b = t;
  64362. break;
  64363. case 3:
  64364. result.r = p;
  64365. result.g = q;
  64366. result.b = v;
  64367. break;
  64368. case 4:
  64369. result.r = t;
  64370. result.g = p;
  64371. result.b = v;
  64372. break;
  64373. default:// case 5:
  64374. result.r = v;
  64375. result.g = p;
  64376. result.b = q;
  64377. break;
  64378. }
  64379. }
  64380. result.a = 1;
  64381. };
  64382. /**
  64383. * Returns a value clamped between min and max
  64384. * @param value The value to clamp
  64385. * @param min The minimum of value
  64386. * @param max The maximum of value
  64387. * @returns The clamped value.
  64388. */
  64389. ColorCurves.clamp = function (value, min, max) {
  64390. return Math.min(Math.max(value, min), max);
  64391. };
  64392. /**
  64393. * Clones the current color curve instance.
  64394. * @return The cloned curves
  64395. */
  64396. ColorCurves.prototype.clone = function () {
  64397. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  64398. };
  64399. /**
  64400. * Serializes the current color curve instance to a json representation.
  64401. * @return a JSON representation
  64402. */
  64403. ColorCurves.prototype.serialize = function () {
  64404. return BABYLON.SerializationHelper.Serialize(this);
  64405. };
  64406. /**
  64407. * Parses the color curve from a json representation.
  64408. * @param source the JSON source to parse
  64409. * @return The parsed curves
  64410. */
  64411. ColorCurves.Parse = function (source) {
  64412. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  64413. };
  64414. __decorate([
  64415. BABYLON.serialize()
  64416. ], ColorCurves.prototype, "_globalHue", void 0);
  64417. __decorate([
  64418. BABYLON.serialize()
  64419. ], ColorCurves.prototype, "_globalDensity", void 0);
  64420. __decorate([
  64421. BABYLON.serialize()
  64422. ], ColorCurves.prototype, "_globalSaturation", void 0);
  64423. __decorate([
  64424. BABYLON.serialize()
  64425. ], ColorCurves.prototype, "_globalExposure", void 0);
  64426. __decorate([
  64427. BABYLON.serialize()
  64428. ], ColorCurves.prototype, "_highlightsHue", void 0);
  64429. __decorate([
  64430. BABYLON.serialize()
  64431. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  64432. __decorate([
  64433. BABYLON.serialize()
  64434. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  64435. __decorate([
  64436. BABYLON.serialize()
  64437. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  64438. __decorate([
  64439. BABYLON.serialize()
  64440. ], ColorCurves.prototype, "_midtonesHue", void 0);
  64441. __decorate([
  64442. BABYLON.serialize()
  64443. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  64444. __decorate([
  64445. BABYLON.serialize()
  64446. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  64447. __decorate([
  64448. BABYLON.serialize()
  64449. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  64450. return ColorCurves;
  64451. }());
  64452. BABYLON.ColorCurves = ColorCurves;
  64453. })(BABYLON || (BABYLON = {}));
  64454. //# sourceMappingURL=babylon.colorCurves.js.map
  64455. var BABYLON;
  64456. (function (BABYLON) {
  64457. var Octree = (function () {
  64458. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  64459. if (maxDepth === void 0) { maxDepth = 2; }
  64460. this.maxDepth = maxDepth;
  64461. this.dynamicContent = new Array();
  64462. this._maxBlockCapacity = maxBlockCapacity || 64;
  64463. this._selectionContent = new BABYLON.SmartArray(1024);
  64464. this._creationFunc = creationFunc;
  64465. }
  64466. // Methods
  64467. Octree.prototype.update = function (worldMin, worldMax, entries) {
  64468. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  64469. };
  64470. Octree.prototype.addMesh = function (entry) {
  64471. for (var index = 0; index < this.blocks.length; index++) {
  64472. var block = this.blocks[index];
  64473. block.addEntry(entry);
  64474. }
  64475. };
  64476. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  64477. this._selectionContent.reset();
  64478. for (var index = 0; index < this.blocks.length; index++) {
  64479. var block = this.blocks[index];
  64480. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  64481. }
  64482. if (allowDuplicate) {
  64483. this._selectionContent.concat(this.dynamicContent);
  64484. }
  64485. else {
  64486. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  64487. }
  64488. return this._selectionContent;
  64489. };
  64490. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  64491. this._selectionContent.reset();
  64492. for (var index = 0; index < this.blocks.length; index++) {
  64493. var block = this.blocks[index];
  64494. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  64495. }
  64496. if (allowDuplicate) {
  64497. this._selectionContent.concat(this.dynamicContent);
  64498. }
  64499. else {
  64500. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  64501. }
  64502. return this._selectionContent;
  64503. };
  64504. Octree.prototype.intersectsRay = function (ray) {
  64505. this._selectionContent.reset();
  64506. for (var index = 0; index < this.blocks.length; index++) {
  64507. var block = this.blocks[index];
  64508. block.intersectsRay(ray, this._selectionContent);
  64509. }
  64510. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  64511. return this._selectionContent;
  64512. };
  64513. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  64514. target.blocks = new Array();
  64515. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  64516. // Segmenting space
  64517. for (var x = 0; x < 2; x++) {
  64518. for (var y = 0; y < 2; y++) {
  64519. for (var z = 0; z < 2; z++) {
  64520. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  64521. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  64522. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  64523. block.addEntries(entries);
  64524. target.blocks.push(block);
  64525. }
  64526. }
  64527. }
  64528. };
  64529. Octree.CreationFuncForMeshes = function (entry, block) {
  64530. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  64531. block.entries.push(entry);
  64532. }
  64533. };
  64534. Octree.CreationFuncForSubMeshes = function (entry, block) {
  64535. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  64536. block.entries.push(entry);
  64537. }
  64538. };
  64539. return Octree;
  64540. }());
  64541. BABYLON.Octree = Octree;
  64542. })(BABYLON || (BABYLON = {}));
  64543. //# sourceMappingURL=babylon.octree.js.map
  64544. var BABYLON;
  64545. (function (BABYLON) {
  64546. var OctreeBlock = (function () {
  64547. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  64548. this.entries = new Array();
  64549. this._boundingVectors = new Array();
  64550. this._capacity = capacity;
  64551. this._depth = depth;
  64552. this._maxDepth = maxDepth;
  64553. this._creationFunc = creationFunc;
  64554. this._minPoint = minPoint;
  64555. this._maxPoint = maxPoint;
  64556. this._boundingVectors.push(minPoint.clone());
  64557. this._boundingVectors.push(maxPoint.clone());
  64558. this._boundingVectors.push(minPoint.clone());
  64559. this._boundingVectors[2].x = maxPoint.x;
  64560. this._boundingVectors.push(minPoint.clone());
  64561. this._boundingVectors[3].y = maxPoint.y;
  64562. this._boundingVectors.push(minPoint.clone());
  64563. this._boundingVectors[4].z = maxPoint.z;
  64564. this._boundingVectors.push(maxPoint.clone());
  64565. this._boundingVectors[5].z = minPoint.z;
  64566. this._boundingVectors.push(maxPoint.clone());
  64567. this._boundingVectors[6].x = minPoint.x;
  64568. this._boundingVectors.push(maxPoint.clone());
  64569. this._boundingVectors[7].y = minPoint.y;
  64570. }
  64571. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  64572. // Property
  64573. get: function () {
  64574. return this._capacity;
  64575. },
  64576. enumerable: true,
  64577. configurable: true
  64578. });
  64579. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  64580. get: function () {
  64581. return this._minPoint;
  64582. },
  64583. enumerable: true,
  64584. configurable: true
  64585. });
  64586. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  64587. get: function () {
  64588. return this._maxPoint;
  64589. },
  64590. enumerable: true,
  64591. configurable: true
  64592. });
  64593. // Methods
  64594. OctreeBlock.prototype.addEntry = function (entry) {
  64595. if (this.blocks) {
  64596. for (var index = 0; index < this.blocks.length; index++) {
  64597. var block = this.blocks[index];
  64598. block.addEntry(entry);
  64599. }
  64600. return;
  64601. }
  64602. this._creationFunc(entry, this);
  64603. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  64604. this.createInnerBlocks();
  64605. }
  64606. };
  64607. OctreeBlock.prototype.addEntries = function (entries) {
  64608. for (var index = 0; index < entries.length; index++) {
  64609. var mesh = entries[index];
  64610. this.addEntry(mesh);
  64611. }
  64612. };
  64613. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  64614. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  64615. if (this.blocks) {
  64616. for (var index = 0; index < this.blocks.length; index++) {
  64617. var block = this.blocks[index];
  64618. block.select(frustumPlanes, selection, allowDuplicate);
  64619. }
  64620. return;
  64621. }
  64622. if (allowDuplicate) {
  64623. selection.concat(this.entries);
  64624. }
  64625. else {
  64626. selection.concatWithNoDuplicate(this.entries);
  64627. }
  64628. }
  64629. };
  64630. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  64631. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  64632. if (this.blocks) {
  64633. for (var index = 0; index < this.blocks.length; index++) {
  64634. var block = this.blocks[index];
  64635. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  64636. }
  64637. return;
  64638. }
  64639. if (allowDuplicate) {
  64640. selection.concat(this.entries);
  64641. }
  64642. else {
  64643. selection.concatWithNoDuplicate(this.entries);
  64644. }
  64645. }
  64646. };
  64647. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  64648. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  64649. if (this.blocks) {
  64650. for (var index = 0; index < this.blocks.length; index++) {
  64651. var block = this.blocks[index];
  64652. block.intersectsRay(ray, selection);
  64653. }
  64654. return;
  64655. }
  64656. selection.concatWithNoDuplicate(this.entries);
  64657. }
  64658. };
  64659. OctreeBlock.prototype.createInnerBlocks = function () {
  64660. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  64661. };
  64662. return OctreeBlock;
  64663. }());
  64664. BABYLON.OctreeBlock = OctreeBlock;
  64665. })(BABYLON || (BABYLON = {}));
  64666. //# sourceMappingURL=babylon.octreeBlock.js.map
  64667. var BABYLON;
  64668. (function (BABYLON) {
  64669. var SIMDVector3 = (function () {
  64670. function SIMDVector3() {
  64671. }
  64672. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  64673. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  64674. };
  64675. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  64676. var m = transformation.m;
  64677. var m0 = SIMD.Float32x4.load(m, 0);
  64678. var m1 = SIMD.Float32x4.load(m, 4);
  64679. var m2 = SIMD.Float32x4.load(m, 8);
  64680. var m3 = SIMD.Float32x4.load(m, 12);
  64681. 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));
  64682. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  64683. result.x = SIMD.Float32x4.extractLane(r, 0);
  64684. result.y = SIMD.Float32x4.extractLane(r, 1);
  64685. result.z = SIMD.Float32x4.extractLane(r, 2);
  64686. };
  64687. return SIMDVector3;
  64688. }());
  64689. var SIMDMatrix = (function () {
  64690. function SIMDMatrix() {
  64691. }
  64692. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  64693. var tm = this.m;
  64694. var om = other.m;
  64695. var m0 = SIMD.Float32x4.load(om, 0);
  64696. var m1 = SIMD.Float32x4.load(om, 4);
  64697. var m2 = SIMD.Float32x4.load(om, 8);
  64698. var m3 = SIMD.Float32x4.load(om, 12);
  64699. for (var i = 0; i < 16; i += 4) {
  64700. 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)))));
  64701. }
  64702. return this;
  64703. };
  64704. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  64705. var src = this.m;
  64706. var dest = other.m;
  64707. // Load the 4 rows
  64708. var src0 = SIMD.Float32x4.load(src, 0);
  64709. var src1 = SIMD.Float32x4.load(src, 4);
  64710. var src2 = SIMD.Float32x4.load(src, 8);
  64711. var src3 = SIMD.Float32x4.load(src, 12);
  64712. // Transpose the source matrix. Sort of. Not a true transpose operation
  64713. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  64714. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  64715. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  64716. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  64717. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  64718. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  64719. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  64720. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  64721. // This is a true transposition, but it will lead to an incorrect result
  64722. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  64723. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  64724. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  64725. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  64726. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  64727. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  64728. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  64729. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  64730. // ----
  64731. tmp1 = SIMD.Float32x4.mul(row2, row3);
  64732. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  64733. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  64734. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  64735. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  64736. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  64737. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  64738. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  64739. // ----
  64740. tmp1 = SIMD.Float32x4.mul(row1, row2);
  64741. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  64742. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  64743. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  64744. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  64745. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  64746. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  64747. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  64748. // ----
  64749. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  64750. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  64751. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  64752. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  64753. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  64754. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  64755. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  64756. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  64757. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  64758. // ----
  64759. tmp1 = SIMD.Float32x4.mul(row0, row1);
  64760. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  64761. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  64762. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  64763. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  64764. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  64765. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  64766. // ----
  64767. tmp1 = SIMD.Float32x4.mul(row0, row3);
  64768. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  64769. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  64770. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  64771. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  64772. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  64773. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  64774. // ----
  64775. tmp1 = SIMD.Float32x4.mul(row0, row2);
  64776. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  64777. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  64778. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  64779. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  64780. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  64781. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  64782. // Compute determinant
  64783. var det = SIMD.Float32x4.mul(row0, minor0);
  64784. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  64785. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  64786. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  64787. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  64788. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  64789. // These shuffles aren't necessary if the faulty transposition is done
  64790. // up at the top of this function.
  64791. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  64792. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  64793. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  64794. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  64795. // Compute final values by multiplying with 1/det
  64796. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  64797. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  64798. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  64799. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  64800. return this;
  64801. };
  64802. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  64803. var out = result.m;
  64804. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  64805. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  64806. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  64807. // cc.kmVec3Subtract(f, pCenter, pEye);
  64808. var f = SIMD.Float32x4.sub(center, eye);
  64809. // cc.kmVec3Normalize(f, f);
  64810. var tmp = SIMD.Float32x4.mul(f, f);
  64811. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  64812. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  64813. // cc.kmVec3Assign(up, pUp);
  64814. // cc.kmVec3Normalize(up, up);
  64815. tmp = SIMD.Float32x4.mul(up, up);
  64816. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  64817. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  64818. // cc.kmVec3Cross(s, f, up);
  64819. 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)));
  64820. // cc.kmVec3Normalize(s, s);
  64821. tmp = SIMD.Float32x4.mul(s, s);
  64822. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  64823. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  64824. // cc.kmVec3Cross(u, s, f);
  64825. 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)));
  64826. // cc.kmVec3Normalize(s, s);
  64827. tmp = SIMD.Float32x4.mul(s, s);
  64828. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  64829. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  64830. var zero = SIMD.Float32x4.splat(0.0);
  64831. s = SIMD.Float32x4.neg(s);
  64832. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  64833. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  64834. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  64835. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  64836. 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);
  64837. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  64838. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  64839. 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)))));
  64840. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  64841. 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)))));
  64842. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  64843. 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)))));
  64844. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  64845. 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)))));
  64846. };
  64847. return SIMDMatrix;
  64848. }());
  64849. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  64850. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  64851. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  64852. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  64853. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  64854. var SIMDHelper = (function () {
  64855. function SIMDHelper() {
  64856. }
  64857. Object.defineProperty(SIMDHelper, "IsEnabled", {
  64858. get: function () {
  64859. return SIMDHelper._isEnabled;
  64860. },
  64861. enumerable: true,
  64862. configurable: true
  64863. });
  64864. SIMDHelper.DisableSIMD = function () {
  64865. // Replace functions
  64866. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  64867. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  64868. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  64869. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  64870. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  64871. SIMDHelper._isEnabled = false;
  64872. };
  64873. SIMDHelper.EnableSIMD = function () {
  64874. if (self.SIMD === undefined) {
  64875. return;
  64876. }
  64877. // check if polyfills needed
  64878. if (!self.Math.fround) {
  64879. self.Math.fround = (function (array) { return function (x) {
  64880. return array[0] = x, array[0];
  64881. }; })(new Float32Array(1));
  64882. }
  64883. if (!self.Math.imul) {
  64884. self.Math.imul = function (a, b) {
  64885. var ah = (a >>> 16) & 0xffff;
  64886. var al = a & 0xffff;
  64887. var bh = (b >>> 16) & 0xffff;
  64888. var bl = b & 0xffff;
  64889. // the shift by 0 fixes the sign on the high part
  64890. // the final |0 converts the unsigned value into a signed value
  64891. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  64892. };
  64893. }
  64894. // Replace functions
  64895. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  64896. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  64897. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  64898. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  64899. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  64900. SIMDHelper._isEnabled = true;
  64901. };
  64902. SIMDHelper._isEnabled = false;
  64903. return SIMDHelper;
  64904. }());
  64905. BABYLON.SIMDHelper = SIMDHelper;
  64906. })(BABYLON || (BABYLON = {}));
  64907. //# sourceMappingURL=babylon.math.SIMD.js.map
  64908. var BABYLON;
  64909. (function (BABYLON) {
  64910. var VRDistortionCorrectionPostProcess = (function (_super) {
  64911. __extends(VRDistortionCorrectionPostProcess, _super);
  64912. //ANY
  64913. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  64914. var _this = _super.call(this, name, "vrDistortionCorrection", [
  64915. 'LensCenter',
  64916. 'Scale',
  64917. 'ScaleIn',
  64918. 'HmdWarpParam'
  64919. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  64920. _this._isRightEye = isRightEye;
  64921. _this._distortionFactors = vrMetrics.distortionK;
  64922. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  64923. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  64924. _this.onSizeChangedObservable.add(function () {
  64925. _this.aspectRatio = _this.width * .5 / _this.height;
  64926. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  64927. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  64928. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  64929. });
  64930. _this.onApplyObservable.add(function (effect) {
  64931. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  64932. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  64933. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  64934. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  64935. });
  64936. return _this;
  64937. }
  64938. return VRDistortionCorrectionPostProcess;
  64939. }(BABYLON.PostProcess));
  64940. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  64941. })(BABYLON || (BABYLON = {}));
  64942. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  64943. var BABYLON;
  64944. (function (BABYLON) {
  64945. var AnaglyphPostProcess = (function (_super) {
  64946. __extends(AnaglyphPostProcess, _super);
  64947. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  64948. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  64949. _this._passedProcess = rigCameras[0]._rigPostProcess;
  64950. _this.onApplyObservable.add(function (effect) {
  64951. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  64952. });
  64953. return _this;
  64954. }
  64955. return AnaglyphPostProcess;
  64956. }(BABYLON.PostProcess));
  64957. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  64958. })(BABYLON || (BABYLON = {}));
  64959. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  64960. var BABYLON;
  64961. (function (BABYLON) {
  64962. var StereoscopicInterlacePostProcess = (function (_super) {
  64963. __extends(StereoscopicInterlacePostProcess, _super);
  64964. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  64965. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  64966. _this._passedProcess = rigCameras[0]._rigPostProcess;
  64967. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  64968. _this.onSizeChangedObservable.add(function () {
  64969. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  64970. });
  64971. _this.onApplyObservable.add(function (effect) {
  64972. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  64973. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  64974. });
  64975. return _this;
  64976. }
  64977. return StereoscopicInterlacePostProcess;
  64978. }(BABYLON.PostProcess));
  64979. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  64980. })(BABYLON || (BABYLON = {}));
  64981. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  64982. var BABYLON;
  64983. (function (BABYLON) {
  64984. var FreeCameraDeviceOrientationInput = (function () {
  64985. function FreeCameraDeviceOrientationInput() {
  64986. var _this = this;
  64987. this._screenOrientationAngle = 0;
  64988. this._screenQuaternion = new BABYLON.Quaternion();
  64989. this._alpha = 0;
  64990. this._beta = 0;
  64991. this._gamma = 0;
  64992. this._orientationChanged = function () {
  64993. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  64994. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  64995. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  64996. };
  64997. this._deviceOrientation = function (evt) {
  64998. _this._alpha = evt.alpha;
  64999. _this._beta = evt.beta;
  65000. _this._gamma = evt.gamma;
  65001. };
  65002. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  65003. this._orientationChanged();
  65004. }
  65005. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  65006. get: function () {
  65007. return this._camera;
  65008. },
  65009. set: function (camera) {
  65010. this._camera = camera;
  65011. if (this._camera != null && !this._camera.rotationQuaternion) {
  65012. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  65013. }
  65014. },
  65015. enumerable: true,
  65016. configurable: true
  65017. });
  65018. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  65019. window.addEventListener("orientationchange", this._orientationChanged);
  65020. window.addEventListener("deviceorientation", this._deviceOrientation);
  65021. //In certain cases, the attach control is called AFTER orientation was changed,
  65022. //So this is needed.
  65023. this._orientationChanged();
  65024. };
  65025. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  65026. window.removeEventListener("orientationchange", this._orientationChanged);
  65027. window.removeEventListener("deviceorientation", this._deviceOrientation);
  65028. };
  65029. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  65030. //if no device orientation provided, don't update the rotation.
  65031. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  65032. if (!this._alpha)
  65033. return;
  65034. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  65035. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  65036. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  65037. //Mirror on XY Plane
  65038. this._camera.rotationQuaternion.z *= -1;
  65039. this._camera.rotationQuaternion.w *= -1;
  65040. };
  65041. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  65042. return "FreeCameraDeviceOrientationInput";
  65043. };
  65044. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  65045. return "deviceOrientation";
  65046. };
  65047. return FreeCameraDeviceOrientationInput;
  65048. }());
  65049. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  65050. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  65051. })(BABYLON || (BABYLON = {}));
  65052. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  65053. var BABYLON;
  65054. (function (BABYLON) {
  65055. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  65056. function ArcRotateCameraVRDeviceOrientationInput() {
  65057. this.alphaCorrection = 1;
  65058. this.betaCorrection = 1;
  65059. this.gammaCorrection = 1;
  65060. this._alpha = 0;
  65061. this._beta = 0;
  65062. this._gamma = 0;
  65063. this._dirty = false;
  65064. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  65065. }
  65066. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  65067. this.camera.attachControl(element, noPreventDefault);
  65068. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  65069. };
  65070. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  65071. var camera = this.camera;
  65072. this._alpha = +evt.alpha | 0;
  65073. this._beta = +evt.beta | 0;
  65074. this._gamma = +evt.gamma | 0;
  65075. this._dirty = true;
  65076. };
  65077. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  65078. if (this._dirty) {
  65079. this._dirty = false;
  65080. if (this._gamma < 0) {
  65081. this._gamma = 180 + this._gamma;
  65082. }
  65083. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  65084. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  65085. }
  65086. };
  65087. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  65088. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  65089. };
  65090. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  65091. return "ArcRotateCameraVRDeviceOrientationInput";
  65092. };
  65093. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  65094. return "VRDeviceOrientation";
  65095. };
  65096. return ArcRotateCameraVRDeviceOrientationInput;
  65097. }());
  65098. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  65099. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  65100. })(BABYLON || (BABYLON = {}));
  65101. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  65102. var BABYLON;
  65103. (function (BABYLON) {
  65104. var VRCameraMetrics = (function () {
  65105. function VRCameraMetrics() {
  65106. this.compensateDistortion = true;
  65107. }
  65108. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  65109. get: function () {
  65110. return this.hResolution / (2 * this.vResolution);
  65111. },
  65112. enumerable: true,
  65113. configurable: true
  65114. });
  65115. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  65116. get: function () {
  65117. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  65118. },
  65119. enumerable: true,
  65120. configurable: true
  65121. });
  65122. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  65123. get: function () {
  65124. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  65125. var h = (4 * meters) / this.hScreenSize;
  65126. return BABYLON.Matrix.Translation(h, 0, 0);
  65127. },
  65128. enumerable: true,
  65129. configurable: true
  65130. });
  65131. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  65132. get: function () {
  65133. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  65134. var h = (4 * meters) / this.hScreenSize;
  65135. return BABYLON.Matrix.Translation(-h, 0, 0);
  65136. },
  65137. enumerable: true,
  65138. configurable: true
  65139. });
  65140. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  65141. get: function () {
  65142. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  65143. },
  65144. enumerable: true,
  65145. configurable: true
  65146. });
  65147. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  65148. get: function () {
  65149. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  65150. },
  65151. enumerable: true,
  65152. configurable: true
  65153. });
  65154. VRCameraMetrics.GetDefault = function () {
  65155. var result = new VRCameraMetrics();
  65156. result.hResolution = 1280;
  65157. result.vResolution = 800;
  65158. result.hScreenSize = 0.149759993;
  65159. result.vScreenSize = 0.0935999975;
  65160. result.vScreenCenter = 0.0467999987;
  65161. result.eyeToScreenDistance = 0.0410000011;
  65162. result.lensSeparationDistance = 0.0635000020;
  65163. result.interpupillaryDistance = 0.0640000030;
  65164. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  65165. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  65166. result.postProcessScaleFactor = 1.714605507808412;
  65167. result.lensCenterOffset = 0.151976421;
  65168. return result;
  65169. };
  65170. return VRCameraMetrics;
  65171. }());
  65172. BABYLON.VRCameraMetrics = VRCameraMetrics;
  65173. })(BABYLON || (BABYLON = {}));
  65174. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  65175. var BABYLON;
  65176. (function (BABYLON) {
  65177. var WebVRFreeCamera = (function (_super) {
  65178. __extends(WebVRFreeCamera, _super);
  65179. function WebVRFreeCamera(name, position, scene, webVROptions) {
  65180. if (webVROptions === void 0) { webVROptions = {}; }
  65181. var _this = _super.call(this, name, position, scene) || this;
  65182. _this.webVROptions = webVROptions;
  65183. _this._vrDevice = null;
  65184. _this.rawPose = null;
  65185. _this._vrEnabled = false;
  65186. _this._specsVersion = 1.1;
  65187. _this._attached = false;
  65188. _this._positionOffset = BABYLON.Vector3.Zero();
  65189. _this._descendants = [];
  65190. _this.devicePosition = BABYLON.Vector3.Zero();
  65191. _this.deviceScaleFactor = 1;
  65192. _this.controllers = [];
  65193. _this.onControllersAttachedObservable = new BABYLON.Observable();
  65194. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  65195. _this.minZ = 0.1;
  65196. //legacy support - the compensation boolean was removed.
  65197. if (arguments.length === 5) {
  65198. _this.webVROptions = arguments[4];
  65199. }
  65200. // default webVR options
  65201. if (_this.webVROptions.trackPosition == undefined) {
  65202. _this.webVROptions.trackPosition = true;
  65203. }
  65204. if (_this.webVROptions.controllerMeshes == undefined) {
  65205. _this.webVROptions.controllerMeshes = true;
  65206. }
  65207. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  65208. _this.webVROptions.defaultLightingOnControllers = true;
  65209. }
  65210. _this.rotationQuaternion = new BABYLON.Quaternion();
  65211. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  65212. if (_this.webVROptions && _this.webVROptions.positionScale) {
  65213. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  65214. }
  65215. //enable VR
  65216. _this.getEngine().initWebVR();
  65217. //check specs version
  65218. if (!window.VRFrameData) {
  65219. _this._specsVersion = 1.0;
  65220. _this._frameData = {};
  65221. }
  65222. else {
  65223. _this._frameData = new VRFrameData();
  65224. }
  65225. _this.getEngine().getVRDevice(_this.webVROptions.displayName, function (device) {
  65226. if (!device) {
  65227. return;
  65228. }
  65229. _this._vrEnabled = true;
  65230. _this._vrDevice = device;
  65231. //reset the rig parameters.
  65232. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  65233. if (_this._attached) {
  65234. _this.getEngine().enableVR(_this._vrDevice);
  65235. }
  65236. });
  65237. /**
  65238. * The idea behind the following lines:
  65239. * objects that have the camera as parent should actually have the rig cameras as a parent.
  65240. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  65241. * the second will not show it correctly.
  65242. *
  65243. * To solve this - each object that has the camera as parent will be added to a protected array.
  65244. * When the rig camera renders, it will take this array and set all of those to be its children.
  65245. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  65246. * Amazing!
  65247. */
  65248. scene.onBeforeCameraRenderObservable.add(function (camera) {
  65249. if (camera.parent === _this && _this.rigParenting) {
  65250. _this._descendants = _this.getDescendants(true, function (n) {
  65251. // don't take the cameras or the controllers!
  65252. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  65253. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  65254. return !isController && !isRigCamera;
  65255. });
  65256. _this._descendants.forEach(function (node) {
  65257. node.parent = camera;
  65258. });
  65259. }
  65260. });
  65261. scene.onAfterCameraRenderObservable.add(function (camera) {
  65262. if (camera.parent === _this && _this.rigParenting) {
  65263. _this._descendants.forEach(function (node) {
  65264. node.parent = _this;
  65265. });
  65266. }
  65267. });
  65268. return _this;
  65269. }
  65270. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  65271. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  65272. var gp = _a[_i];
  65273. if (gp.hand === name) {
  65274. return gp;
  65275. }
  65276. }
  65277. return undefined;
  65278. };
  65279. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  65280. get: function () {
  65281. if (!this._leftController) {
  65282. this._leftController = this.getControllerByName("left");
  65283. }
  65284. return this._leftController;
  65285. },
  65286. enumerable: true,
  65287. configurable: true
  65288. });
  65289. ;
  65290. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  65291. get: function () {
  65292. if (!this._rightController) {
  65293. this._rightController = this.getControllerByName("right");
  65294. }
  65295. return this._rightController;
  65296. },
  65297. enumerable: true,
  65298. configurable: true
  65299. });
  65300. ;
  65301. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  65302. if (length === void 0) { length = 100; }
  65303. if (this.leftCamera) {
  65304. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera
  65305. }
  65306. else {
  65307. return _super.prototype.getForwardRay.call(this, length);
  65308. }
  65309. };
  65310. WebVRFreeCamera.prototype._checkInputs = function () {
  65311. if (this._vrEnabled) {
  65312. if (this._specsVersion === 1.1) {
  65313. this._vrDevice.getFrameData(this._frameData);
  65314. }
  65315. else {
  65316. //backwards comp
  65317. var pose = this._vrDevice.getPose();
  65318. this._frameData.pose = pose;
  65319. }
  65320. this.updateFromDevice(this._frameData.pose);
  65321. }
  65322. _super.prototype._checkInputs.call(this);
  65323. };
  65324. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  65325. if (poseData && poseData.orientation) {
  65326. this.rawPose = poseData;
  65327. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  65328. if (this.getScene().useRightHandedSystem) {
  65329. this.deviceRotationQuaternion.z *= -1;
  65330. this.deviceRotationQuaternion.w *= -1;
  65331. }
  65332. if (this.webVROptions.trackPosition && this.rawPose.position) {
  65333. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  65334. if (this.getScene().useRightHandedSystem) {
  65335. this.devicePosition.z *= -1;
  65336. }
  65337. }
  65338. }
  65339. };
  65340. /**
  65341. * WebVR's attach control will start broadcasting frames to the device.
  65342. * Note that in certain browsers (chrome for example) this function must be called
  65343. * within a user-interaction callback. Example:
  65344. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  65345. *
  65346. * @param {HTMLElement} element
  65347. * @param {boolean} [noPreventDefault]
  65348. *
  65349. * @memberOf WebVRFreeCamera
  65350. */
  65351. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  65352. _super.prototype.attachControl.call(this, element, noPreventDefault);
  65353. this._attached = true;
  65354. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  65355. if (this._vrEnabled) {
  65356. this.getEngine().enableVR(this._vrDevice);
  65357. }
  65358. // try to attach the controllers, if found.
  65359. this.initControllers();
  65360. };
  65361. WebVRFreeCamera.prototype.detachControl = function (element) {
  65362. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  65363. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  65364. _super.prototype.detachControl.call(this, element);
  65365. this._vrEnabled = false;
  65366. this._attached = false;
  65367. this.getEngine().disableVR();
  65368. };
  65369. WebVRFreeCamera.prototype.getClassName = function () {
  65370. return "WebVRFreeCamera";
  65371. };
  65372. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  65373. //uses the vrDisplay's "resetPose()".
  65374. //pitch and roll won't be affected.
  65375. this._vrDevice.resetPose();
  65376. };
  65377. WebVRFreeCamera.prototype._updateRigCameras = function () {
  65378. var camLeft = this._rigCameras[0];
  65379. var camRight = this._rigCameras[1];
  65380. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  65381. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  65382. camLeft.position.copyFrom(this.devicePosition);
  65383. camRight.position.copyFrom(this.devicePosition);
  65384. };
  65385. /**
  65386. * This function is called by the two RIG cameras.
  65387. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  65388. */
  65389. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  65390. var _this = this;
  65391. //WebVR 1.0
  65392. if (this._cameraRigParams["specs"] === 1.0) {
  65393. this._updateCameraRotationMatrix();
  65394. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  65395. // Computing target and final matrix
  65396. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  65397. if (this.getScene().useRightHandedSystem) {
  65398. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  65399. }
  65400. else {
  65401. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  65402. }
  65403. //now move the eye in the right direction
  65404. var eyeParams = this._cameraRigParams["eyeParameters"];
  65405. var offset = eyeParams.offset;
  65406. // it will actually always be 0, but just in case
  65407. if (this.getScene().useRightHandedSystem) {
  65408. offset[2] *= -1;
  65409. }
  65410. BABYLON.Matrix.TranslationToRef(-offset[0], offset[1], -offset[2], BABYLON.Tmp.Matrix[0]);
  65411. this._webvrViewMatrix.multiplyToRef(BABYLON.Tmp.Matrix[0], this._webvrViewMatrix);
  65412. }
  65413. else {
  65414. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  65415. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  65416. if (!this.getScene().useRightHandedSystem) {
  65417. [2, 6, 8, 9, 14].forEach(function (num) {
  65418. _this._webvrViewMatrix.m[num] *= -1;
  65419. });
  65420. }
  65421. // update the camera rotation matrix
  65422. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  65423. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  65424. // Computing target and final matrix
  65425. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  65426. }
  65427. var parentCamera = this._cameraRigParams["parentCamera"];
  65428. // should the view matrix be updated with scale and position offset?
  65429. if (parentCamera.deviceScaleFactor !== 1) {
  65430. this._webvrViewMatrix.invert();
  65431. // scale the position, if set
  65432. if (parentCamera.deviceScaleFactor) {
  65433. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  65434. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  65435. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  65436. }
  65437. this._webvrViewMatrix.invert();
  65438. }
  65439. return this._webvrViewMatrix;
  65440. };
  65441. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  65442. var _this = this;
  65443. if (this._cameraRigParams["specs"] === 1.0) {
  65444. var eyeParams = this._cameraRigParams["eyeParameters"];
  65445. // deprecated!!
  65446. BABYLON.Matrix.PerspectiveFovWebVRToRef(eyeParams.fieldOfView, this.minZ, this.maxZ, this._projectionMatrix, this.getScene().useRightHandedSystem);
  65447. }
  65448. else {
  65449. var parentCamera = this.parent;
  65450. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  65451. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  65452. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  65453. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  65454. //babylon compatible matrix
  65455. if (!this.getScene().useRightHandedSystem) {
  65456. [8, 9, 10, 11].forEach(function (num) {
  65457. _this._projectionMatrix.m[num] *= -1;
  65458. });
  65459. }
  65460. }
  65461. return this._projectionMatrix;
  65462. };
  65463. WebVRFreeCamera.prototype.initControllers = function () {
  65464. var _this = this;
  65465. this.controllers = [];
  65466. var manager = this.getScene().gamepadManager;
  65467. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  65468. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  65469. var webVrController = gamepad;
  65470. var index = _this.controllers.indexOf(webVrController);
  65471. if (index === -1) {
  65472. // we are good
  65473. return;
  65474. }
  65475. _this.controllers.splice(index, 1);
  65476. }
  65477. });
  65478. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  65479. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  65480. var webVrController = gamepad;
  65481. if (_this.webVROptions.controllerMeshes) {
  65482. webVrController.initControllerMesh(_this.getScene(), function (loadedMesh) {
  65483. if (_this.webVROptions.defaultLightingOnControllers) {
  65484. if (!_this._lightOnControllers) {
  65485. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  65486. }
  65487. loadedMesh.getChildren().forEach(function (mesh) {
  65488. _this._lightOnControllers.includedOnlyMeshes.push(mesh);
  65489. });
  65490. }
  65491. });
  65492. }
  65493. webVrController.attachToPoseControlledCamera(_this);
  65494. // since this is async - sanity check. Is the controller already stored?
  65495. if (_this.controllers.indexOf(webVrController) === -1) {
  65496. //add to the controllers array
  65497. _this.controllers.push(webVrController);
  65498. //did we find enough controllers? Great! let the developer know.
  65499. if (_this.controllers.length >= 2) {
  65500. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  65501. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  65502. // So we're overriding setting left & right manually to be sure
  65503. var firstViveWandDetected = false;
  65504. for (var i = 0; i < _this.controllers.length; i++) {
  65505. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  65506. if (!firstViveWandDetected) {
  65507. firstViveWandDetected = true;
  65508. _this.controllers[i].hand = "left";
  65509. }
  65510. else {
  65511. _this.controllers[i].hand = "right";
  65512. }
  65513. }
  65514. }
  65515. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  65516. }
  65517. }
  65518. }
  65519. });
  65520. };
  65521. return WebVRFreeCamera;
  65522. }(BABYLON.FreeCamera));
  65523. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  65524. })(BABYLON || (BABYLON = {}));
  65525. //# sourceMappingURL=babylon.webVRCamera.js.map
  65526. /// <reference path="babylon.freeCamera.ts" />
  65527. var BABYLON;
  65528. (function (BABYLON) {
  65529. // We're mainly based on the logic defined into the FreeCamera code
  65530. var DeviceOrientationCamera = (function (_super) {
  65531. __extends(DeviceOrientationCamera, _super);
  65532. function DeviceOrientationCamera(name, position, scene) {
  65533. var _this = _super.call(this, name, position, scene) || this;
  65534. _this._quaternionCache = new BABYLON.Quaternion();
  65535. _this.inputs.addDeviceOrientation();
  65536. return _this;
  65537. }
  65538. DeviceOrientationCamera.prototype.getClassName = function () {
  65539. return "DeviceOrientationCamera";
  65540. };
  65541. DeviceOrientationCamera.prototype._checkInputs = function () {
  65542. _super.prototype._checkInputs.call(this);
  65543. this._quaternionCache.copyFrom(this.rotationQuaternion);
  65544. if (this._initialQuaternion) {
  65545. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  65546. }
  65547. };
  65548. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  65549. var _this = this;
  65550. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  65551. //can only work if this camera has a rotation quaternion already.
  65552. if (!this.rotationQuaternion)
  65553. return;
  65554. if (!this._initialQuaternion) {
  65555. this._initialQuaternion = new BABYLON.Quaternion();
  65556. }
  65557. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  65558. ['x', 'y', 'z'].forEach(function (axisName) {
  65559. if (!axis[axisName]) {
  65560. _this._initialQuaternion[axisName] = 0;
  65561. }
  65562. else {
  65563. _this._initialQuaternion[axisName] *= -1;
  65564. }
  65565. });
  65566. this._initialQuaternion.normalize();
  65567. //force rotation update
  65568. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  65569. };
  65570. return DeviceOrientationCamera;
  65571. }(BABYLON.FreeCamera));
  65572. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  65573. })(BABYLON || (BABYLON = {}));
  65574. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  65575. var BABYLON;
  65576. (function (BABYLON) {
  65577. var VRDeviceOrientationFreeCamera = (function (_super) {
  65578. __extends(VRDeviceOrientationFreeCamera, _super);
  65579. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  65580. if (compensateDistortion === void 0) { compensateDistortion = true; }
  65581. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  65582. var _this = _super.call(this, name, position, scene) || this;
  65583. vrCameraMetrics.compensateDistortion = compensateDistortion;
  65584. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  65585. return _this;
  65586. }
  65587. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  65588. return "VRDeviceOrientationFreeCamera";
  65589. };
  65590. return VRDeviceOrientationFreeCamera;
  65591. }(BABYLON.DeviceOrientationCamera));
  65592. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  65593. var VRDeviceOrientationGamepadCamera = (function (_super) {
  65594. __extends(VRDeviceOrientationGamepadCamera, _super);
  65595. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  65596. if (compensateDistortion === void 0) { compensateDistortion = true; }
  65597. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  65598. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  65599. _this.inputs.addGamepad();
  65600. return _this;
  65601. }
  65602. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  65603. return "VRDeviceOrientationGamepadCamera";
  65604. };
  65605. return VRDeviceOrientationGamepadCamera;
  65606. }(VRDeviceOrientationFreeCamera));
  65607. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  65608. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  65609. __extends(VRDeviceOrientationArcRotateCamera, _super);
  65610. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  65611. if (compensateDistortion === void 0) { compensateDistortion = true; }
  65612. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  65613. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  65614. vrCameraMetrics.compensateDistortion = compensateDistortion;
  65615. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  65616. _this.inputs.addVRDeviceOrientation();
  65617. return _this;
  65618. }
  65619. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  65620. return "VRDeviceOrientationArcRotateCamera";
  65621. };
  65622. return VRDeviceOrientationArcRotateCamera;
  65623. }(BABYLON.ArcRotateCamera));
  65624. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  65625. })(BABYLON || (BABYLON = {}));
  65626. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  65627. /// <reference path="babylon.freeCamera.ts" />
  65628. /// <reference path="babylon.arcRotateCamera.ts" />
  65629. /// <reference path="babylon.gamepadCamera.ts" />
  65630. /// <reference path="babylon.universalCamera.ts" />
  65631. var BABYLON;
  65632. (function (BABYLON) {
  65633. var AnaglyphFreeCamera = (function (_super) {
  65634. __extends(AnaglyphFreeCamera, _super);
  65635. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  65636. var _this = _super.call(this, name, position, scene) || this;
  65637. _this.interaxialDistance = interaxialDistance;
  65638. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  65639. return _this;
  65640. }
  65641. AnaglyphFreeCamera.prototype.getClassName = function () {
  65642. return "AnaglyphFreeCamera";
  65643. };
  65644. return AnaglyphFreeCamera;
  65645. }(BABYLON.FreeCamera));
  65646. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  65647. var AnaglyphArcRotateCamera = (function (_super) {
  65648. __extends(AnaglyphArcRotateCamera, _super);
  65649. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  65650. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  65651. _this.interaxialDistance = interaxialDistance;
  65652. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  65653. return _this;
  65654. }
  65655. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  65656. return "AnaglyphArcRotateCamera";
  65657. };
  65658. return AnaglyphArcRotateCamera;
  65659. }(BABYLON.ArcRotateCamera));
  65660. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  65661. var AnaglyphGamepadCamera = (function (_super) {
  65662. __extends(AnaglyphGamepadCamera, _super);
  65663. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  65664. var _this = _super.call(this, name, position, scene) || this;
  65665. _this.interaxialDistance = interaxialDistance;
  65666. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  65667. return _this;
  65668. }
  65669. AnaglyphGamepadCamera.prototype.getClassName = function () {
  65670. return "AnaglyphGamepadCamera";
  65671. };
  65672. return AnaglyphGamepadCamera;
  65673. }(BABYLON.GamepadCamera));
  65674. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  65675. var AnaglyphUniversalCamera = (function (_super) {
  65676. __extends(AnaglyphUniversalCamera, _super);
  65677. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  65678. var _this = _super.call(this, name, position, scene) || this;
  65679. _this.interaxialDistance = interaxialDistance;
  65680. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  65681. return _this;
  65682. }
  65683. AnaglyphUniversalCamera.prototype.getClassName = function () {
  65684. return "AnaglyphUniversalCamera";
  65685. };
  65686. return AnaglyphUniversalCamera;
  65687. }(BABYLON.UniversalCamera));
  65688. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  65689. var StereoscopicFreeCamera = (function (_super) {
  65690. __extends(StereoscopicFreeCamera, _super);
  65691. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  65692. var _this = _super.call(this, name, position, scene) || this;
  65693. _this.interaxialDistance = interaxialDistance;
  65694. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  65695. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  65696. return _this;
  65697. }
  65698. StereoscopicFreeCamera.prototype.getClassName = function () {
  65699. return "StereoscopicFreeCamera";
  65700. };
  65701. return StereoscopicFreeCamera;
  65702. }(BABYLON.FreeCamera));
  65703. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  65704. var StereoscopicArcRotateCamera = (function (_super) {
  65705. __extends(StereoscopicArcRotateCamera, _super);
  65706. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  65707. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  65708. _this.interaxialDistance = interaxialDistance;
  65709. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  65710. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  65711. return _this;
  65712. }
  65713. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  65714. return "StereoscopicArcRotateCamera";
  65715. };
  65716. return StereoscopicArcRotateCamera;
  65717. }(BABYLON.ArcRotateCamera));
  65718. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  65719. var StereoscopicGamepadCamera = (function (_super) {
  65720. __extends(StereoscopicGamepadCamera, _super);
  65721. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  65722. var _this = _super.call(this, name, position, scene) || this;
  65723. _this.interaxialDistance = interaxialDistance;
  65724. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  65725. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  65726. return _this;
  65727. }
  65728. StereoscopicGamepadCamera.prototype.getClassName = function () {
  65729. return "StereoscopicGamepadCamera";
  65730. };
  65731. return StereoscopicGamepadCamera;
  65732. }(BABYLON.GamepadCamera));
  65733. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  65734. var StereoscopicUniversalCamera = (function (_super) {
  65735. __extends(StereoscopicUniversalCamera, _super);
  65736. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  65737. var _this = _super.call(this, name, position, scene) || this;
  65738. _this.interaxialDistance = interaxialDistance;
  65739. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  65740. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  65741. return _this;
  65742. }
  65743. StereoscopicUniversalCamera.prototype.getClassName = function () {
  65744. return "StereoscopicUniversalCamera";
  65745. };
  65746. return StereoscopicUniversalCamera;
  65747. }(BABYLON.UniversalCamera));
  65748. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  65749. })(BABYLON || (BABYLON = {}));
  65750. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  65751. var BABYLON;
  65752. (function (BABYLON) {
  65753. var VRExperienceHelper = (function () {
  65754. function VRExperienceHelper(scene, webVROptions) {
  65755. if (webVROptions === void 0) { webVROptions = {}; }
  65756. var _this = this;
  65757. this.webVROptions = webVROptions;
  65758. this._webVRsupportedAndReady = false;
  65759. this._isInVRMode = false;
  65760. this._scene = scene;
  65761. if (!this._scene.activeCamera) {
  65762. this._scene.activeCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", new BABYLON.Vector3(0, 2, 0), scene);
  65763. }
  65764. else {
  65765. var newCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._scene.activeCamera.position, scene);
  65766. if (scene.activeCamera.rotation) {
  65767. newCamera.rotation = scene.activeCamera.rotation.clone();
  65768. }
  65769. this._scene.activeCamera = newCamera;
  65770. }
  65771. this._position = this._scene.activeCamera.position;
  65772. this._canvas = scene.getEngine().getRenderingCanvas();
  65773. this._scene.activeCamera.attachControl(this._canvas);
  65774. this._btnVR = document.createElement("BUTTON");
  65775. this._btnVR.className = "babylonVRicon";
  65776. this._btnVR.id = "babylonVRiconbtn";
  65777. this._btnVR.title = "Click to switch to VR";
  65778. 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) }";
  65779. var style = document.createElement('style');
  65780. style.appendChild(document.createTextNode(css));
  65781. document.getElementsByTagName('head')[0].appendChild(style);
  65782. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  65783. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  65784. window.addEventListener("resize", function () {
  65785. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  65786. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  65787. });
  65788. // Exiting VR mode using 'ESC' key on desktop
  65789. document.addEventListener("keydown", function (event) {
  65790. if (event.keyCode === 27 && _this._isInVRMode) {
  65791. _this.exitVR();
  65792. }
  65793. });
  65794. // Exiting VR mode double tapping the touch screen
  65795. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  65796. if (_this._isInVRMode) {
  65797. _this.exitVR();
  65798. }
  65799. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  65800. if (navigator.getVRDisplays) {
  65801. navigator.getVRDisplays().then(function (headsets) {
  65802. if (headsets.length > 0) {
  65803. scene.getEngine().initWebVR();
  65804. _this._webVRsupportedAndReady = true;
  65805. }
  65806. document.body.appendChild(_this._btnVR);
  65807. });
  65808. }
  65809. else {
  65810. document.body.appendChild(this._btnVR);
  65811. }
  65812. this._btnVR.addEventListener("click", function () {
  65813. _this.enterVR();
  65814. });
  65815. }
  65816. VRExperienceHelper.prototype.enterVR = function () {
  65817. this._scene.activeCamera.dispose();
  65818. // If WebVR is supported and a headset is connected
  65819. if (this._webVRsupportedAndReady) {
  65820. this._scene.activeCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene);
  65821. }
  65822. else {
  65823. this._scene.activeCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  65824. this._scene.getEngine().switchFullscreen(true);
  65825. }
  65826. this._scene.activeCamera.attachControl(this._canvas);
  65827. this._isInVRMode = true;
  65828. this._btnVR.style.display = "none";
  65829. };
  65830. VRExperienceHelper.prototype.exitVR = function () {
  65831. if (this._webVRsupportedAndReady) {
  65832. this._scene.getEngine().disableVR();
  65833. }
  65834. if (this._scene.activeCamera) {
  65835. this._position = this._scene.activeCamera.position;
  65836. this._scene.activeCamera.dispose();
  65837. }
  65838. this._scene.activeCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position, this._scene);
  65839. this._scene.activeCamera.attachControl(this._canvas);
  65840. this._isInVRMode = false;
  65841. this._btnVR.style.display = "";
  65842. };
  65843. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  65844. get: function () {
  65845. return this._position;
  65846. },
  65847. set: function (value) {
  65848. this._position = value;
  65849. this._scene.activeCamera.position = value;
  65850. },
  65851. enumerable: true,
  65852. configurable: true
  65853. });
  65854. VRExperienceHelper.prototype.dispose = function () {
  65855. if (this._isInVRMode) {
  65856. this.exitVR();
  65857. }
  65858. document.body.removeChild(this._btnVR);
  65859. };
  65860. VRExperienceHelper.prototype.getClassName = function () {
  65861. return "VRExperienceHelper";
  65862. };
  65863. return VRExperienceHelper;
  65864. }());
  65865. BABYLON.VRExperienceHelper = VRExperienceHelper;
  65866. })(BABYLON || (BABYLON = {}));
  65867. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  65868. // Mainly based on these 2 articles :
  65869. // 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
  65870. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  65871. var BABYLON;
  65872. (function (BABYLON) {
  65873. var JoystickAxis;
  65874. (function (JoystickAxis) {
  65875. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  65876. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  65877. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  65878. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  65879. var VirtualJoystick = (function () {
  65880. function VirtualJoystick(leftJoystick) {
  65881. var _this = this;
  65882. if (leftJoystick) {
  65883. this._leftJoystick = true;
  65884. }
  65885. else {
  65886. this._leftJoystick = false;
  65887. }
  65888. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  65889. VirtualJoystick._globalJoystickIndex++;
  65890. // By default left & right arrow keys are moving the X
  65891. // and up & down keys are moving the Y
  65892. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  65893. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  65894. this.reverseLeftRight = false;
  65895. this.reverseUpDown = false;
  65896. // collections of pointers
  65897. this._touches = new BABYLON.StringDictionary();
  65898. this.deltaPosition = BABYLON.Vector3.Zero();
  65899. this._joystickSensibility = 25;
  65900. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  65901. this._rotationSpeed = 25;
  65902. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  65903. this._rotateOnAxisRelativeToMesh = false;
  65904. this._onResize = function (evt) {
  65905. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  65906. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  65907. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  65908. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  65909. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  65910. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  65911. };
  65912. // injecting a canvas element on top of the canvas 3D game
  65913. if (!VirtualJoystick.vjCanvas) {
  65914. window.addEventListener("resize", this._onResize, false);
  65915. VirtualJoystick.vjCanvas = document.createElement("canvas");
  65916. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  65917. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  65918. VirtualJoystick.vjCanvas.width = window.innerWidth;
  65919. VirtualJoystick.vjCanvas.height = window.innerHeight;
  65920. VirtualJoystick.vjCanvas.style.width = "100%";
  65921. VirtualJoystick.vjCanvas.style.height = "100%";
  65922. VirtualJoystick.vjCanvas.style.position = "absolute";
  65923. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  65924. VirtualJoystick.vjCanvas.style.top = "0px";
  65925. VirtualJoystick.vjCanvas.style.left = "0px";
  65926. VirtualJoystick.vjCanvas.style.zIndex = "5";
  65927. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  65928. // Support for jQuery PEP polyfill
  65929. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  65930. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  65931. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  65932. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  65933. document.body.appendChild(VirtualJoystick.vjCanvas);
  65934. }
  65935. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  65936. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  65937. this.pressed = false;
  65938. // default joystick color
  65939. this._joystickColor = "cyan";
  65940. this._joystickPointerID = -1;
  65941. // current joystick position
  65942. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  65943. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  65944. // origin joystick position
  65945. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  65946. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  65947. this._onPointerDownHandlerRef = function (evt) {
  65948. _this._onPointerDown(evt);
  65949. };
  65950. this._onPointerMoveHandlerRef = function (evt) {
  65951. _this._onPointerMove(evt);
  65952. };
  65953. this._onPointerOutHandlerRef = function (evt) {
  65954. _this._onPointerUp(evt);
  65955. };
  65956. this._onPointerUpHandlerRef = function (evt) {
  65957. _this._onPointerUp(evt);
  65958. };
  65959. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  65960. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  65961. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  65962. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  65963. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  65964. evt.preventDefault(); // Disables system menu
  65965. }, false);
  65966. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  65967. }
  65968. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  65969. this._joystickSensibility = newJoystickSensibility;
  65970. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  65971. };
  65972. VirtualJoystick.prototype._onPointerDown = function (e) {
  65973. var positionOnScreenCondition;
  65974. e.preventDefault();
  65975. if (this._leftJoystick === true) {
  65976. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  65977. }
  65978. else {
  65979. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  65980. }
  65981. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  65982. // First contact will be dedicated to the virtual joystick
  65983. this._joystickPointerID = e.pointerId;
  65984. this._joystickPointerStartPos.x = e.clientX;
  65985. this._joystickPointerStartPos.y = e.clientY;
  65986. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  65987. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  65988. this._deltaJoystickVector.x = 0;
  65989. this._deltaJoystickVector.y = 0;
  65990. this.pressed = true;
  65991. this._touches.add(e.pointerId.toString(), e);
  65992. }
  65993. else {
  65994. // You can only trigger the action buttons with a joystick declared
  65995. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  65996. this._action();
  65997. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  65998. }
  65999. }
  66000. };
  66001. VirtualJoystick.prototype._onPointerMove = function (e) {
  66002. // If the current pointer is the one associated to the joystick (first touch contact)
  66003. if (this._joystickPointerID == e.pointerId) {
  66004. this._joystickPointerPos.x = e.clientX;
  66005. this._joystickPointerPos.y = e.clientY;
  66006. this._deltaJoystickVector = this._joystickPointerPos.clone();
  66007. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  66008. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  66009. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  66010. switch (this._axisTargetedByLeftAndRight) {
  66011. case JoystickAxis.X:
  66012. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  66013. break;
  66014. case JoystickAxis.Y:
  66015. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  66016. break;
  66017. case JoystickAxis.Z:
  66018. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  66019. break;
  66020. }
  66021. var directionUpDown = this.reverseUpDown ? 1 : -1;
  66022. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  66023. switch (this._axisTargetedByUpAndDown) {
  66024. case JoystickAxis.X:
  66025. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  66026. break;
  66027. case JoystickAxis.Y:
  66028. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  66029. break;
  66030. case JoystickAxis.Z:
  66031. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  66032. break;
  66033. }
  66034. }
  66035. else {
  66036. var data = this._touches.get(e.pointerId.toString());
  66037. if (data) {
  66038. data.x = e.clientX;
  66039. data.y = e.clientY;
  66040. }
  66041. }
  66042. };
  66043. VirtualJoystick.prototype._onPointerUp = function (e) {
  66044. if (this._joystickPointerID == e.pointerId) {
  66045. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  66046. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  66047. this._joystickPointerID = -1;
  66048. this.pressed = false;
  66049. }
  66050. else {
  66051. var touch = this._touches.get(e.pointerId.toString());
  66052. if (touch) {
  66053. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  66054. }
  66055. }
  66056. this._deltaJoystickVector.x = 0;
  66057. this._deltaJoystickVector.y = 0;
  66058. this._touches.remove(e.pointerId.toString());
  66059. };
  66060. /**
  66061. * Change the color of the virtual joystick
  66062. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  66063. */
  66064. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  66065. this._joystickColor = newColor;
  66066. };
  66067. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  66068. this._action = action;
  66069. };
  66070. // Define which axis you'd like to control for left & right
  66071. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  66072. switch (axis) {
  66073. case JoystickAxis.X:
  66074. case JoystickAxis.Y:
  66075. case JoystickAxis.Z:
  66076. this._axisTargetedByLeftAndRight = axis;
  66077. break;
  66078. default:
  66079. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  66080. break;
  66081. }
  66082. };
  66083. // Define which axis you'd like to control for up & down
  66084. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  66085. switch (axis) {
  66086. case JoystickAxis.X:
  66087. case JoystickAxis.Y:
  66088. case JoystickAxis.Z:
  66089. this._axisTargetedByUpAndDown = axis;
  66090. break;
  66091. default:
  66092. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  66093. break;
  66094. }
  66095. };
  66096. VirtualJoystick.prototype._clearCanvas = function () {
  66097. if (this._leftJoystick) {
  66098. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  66099. }
  66100. else {
  66101. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  66102. }
  66103. };
  66104. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  66105. var _this = this;
  66106. if (this.pressed) {
  66107. this._touches.forEach(function (key, touch) {
  66108. if (touch.pointerId === _this._joystickPointerID) {
  66109. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  66110. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  66111. VirtualJoystick.vjCanvasContext.beginPath();
  66112. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  66113. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  66114. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  66115. VirtualJoystick.vjCanvasContext.stroke();
  66116. VirtualJoystick.vjCanvasContext.closePath();
  66117. VirtualJoystick.vjCanvasContext.beginPath();
  66118. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  66119. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  66120. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  66121. VirtualJoystick.vjCanvasContext.stroke();
  66122. VirtualJoystick.vjCanvasContext.closePath();
  66123. VirtualJoystick.vjCanvasContext.beginPath();
  66124. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  66125. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  66126. VirtualJoystick.vjCanvasContext.stroke();
  66127. VirtualJoystick.vjCanvasContext.closePath();
  66128. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  66129. }
  66130. else {
  66131. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  66132. VirtualJoystick.vjCanvasContext.beginPath();
  66133. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  66134. VirtualJoystick.vjCanvasContext.beginPath();
  66135. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  66136. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  66137. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  66138. VirtualJoystick.vjCanvasContext.stroke();
  66139. VirtualJoystick.vjCanvasContext.closePath();
  66140. touch.prevX = touch.x;
  66141. touch.prevY = touch.y;
  66142. }
  66143. ;
  66144. });
  66145. }
  66146. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  66147. };
  66148. VirtualJoystick.prototype.releaseCanvas = function () {
  66149. if (VirtualJoystick.vjCanvas) {
  66150. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  66151. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  66152. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  66153. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  66154. window.removeEventListener("resize", this._onResize);
  66155. document.body.removeChild(VirtualJoystick.vjCanvas);
  66156. VirtualJoystick.vjCanvas = null;
  66157. }
  66158. };
  66159. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  66160. VirtualJoystick._globalJoystickIndex = 0;
  66161. return VirtualJoystick;
  66162. }());
  66163. BABYLON.VirtualJoystick = VirtualJoystick;
  66164. })(BABYLON || (BABYLON = {}));
  66165. //# sourceMappingURL=babylon.virtualJoystick.js.map
  66166. var BABYLON;
  66167. (function (BABYLON) {
  66168. // We're mainly based on the logic defined into the FreeCamera code
  66169. var VirtualJoysticksCamera = (function (_super) {
  66170. __extends(VirtualJoysticksCamera, _super);
  66171. function VirtualJoysticksCamera(name, position, scene) {
  66172. var _this = _super.call(this, name, position, scene) || this;
  66173. _this.inputs.addVirtualJoystick();
  66174. return _this;
  66175. }
  66176. VirtualJoysticksCamera.prototype.getClassName = function () {
  66177. return "VirtualJoysticksCamera";
  66178. };
  66179. return VirtualJoysticksCamera;
  66180. }(BABYLON.FreeCamera));
  66181. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  66182. })(BABYLON || (BABYLON = {}));
  66183. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  66184. var BABYLON;
  66185. (function (BABYLON) {
  66186. var FreeCameraVirtualJoystickInput = (function () {
  66187. function FreeCameraVirtualJoystickInput() {
  66188. }
  66189. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  66190. return this._leftjoystick;
  66191. };
  66192. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  66193. return this._rightjoystick;
  66194. };
  66195. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  66196. if (this._leftjoystick) {
  66197. var camera = this.camera;
  66198. var speed = camera._computeLocalCameraSpeed() * 50;
  66199. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  66200. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  66201. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  66202. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  66203. if (!this._leftjoystick.pressed) {
  66204. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  66205. }
  66206. if (!this._rightjoystick.pressed) {
  66207. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  66208. }
  66209. }
  66210. };
  66211. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  66212. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  66213. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  66214. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  66215. this._leftjoystick.setJoystickSensibility(0.15);
  66216. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  66217. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  66218. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  66219. this._rightjoystick.reverseUpDown = true;
  66220. this._rightjoystick.setJoystickSensibility(0.05);
  66221. this._rightjoystick.setJoystickColor("yellow");
  66222. };
  66223. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  66224. this._leftjoystick.releaseCanvas();
  66225. this._rightjoystick.releaseCanvas();
  66226. };
  66227. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  66228. return "FreeCameraVirtualJoystickInput";
  66229. };
  66230. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  66231. return "virtualJoystick";
  66232. };
  66233. return FreeCameraVirtualJoystickInput;
  66234. }());
  66235. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  66236. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  66237. })(BABYLON || (BABYLON = {}));
  66238. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  66239. var BABYLON;
  66240. (function (BABYLON) {
  66241. var SimplificationSettings = (function () {
  66242. function SimplificationSettings(quality, distance, optimizeMesh) {
  66243. this.quality = quality;
  66244. this.distance = distance;
  66245. this.optimizeMesh = optimizeMesh;
  66246. }
  66247. return SimplificationSettings;
  66248. }());
  66249. BABYLON.SimplificationSettings = SimplificationSettings;
  66250. var SimplificationQueue = (function () {
  66251. function SimplificationQueue() {
  66252. this.running = false;
  66253. this._simplificationArray = [];
  66254. }
  66255. SimplificationQueue.prototype.addTask = function (task) {
  66256. this._simplificationArray.push(task);
  66257. };
  66258. SimplificationQueue.prototype.executeNext = function () {
  66259. var task = this._simplificationArray.pop();
  66260. if (task) {
  66261. this.running = true;
  66262. this.runSimplification(task);
  66263. }
  66264. else {
  66265. this.running = false;
  66266. }
  66267. };
  66268. SimplificationQueue.prototype.runSimplification = function (task) {
  66269. var _this = this;
  66270. if (task.parallelProcessing) {
  66271. //parallel simplifier
  66272. task.settings.forEach(function (setting) {
  66273. var simplifier = _this.getSimplifier(task);
  66274. simplifier.simplify(setting, function (newMesh) {
  66275. task.mesh.addLODLevel(setting.distance, newMesh);
  66276. newMesh.isVisible = true;
  66277. //check if it is the last
  66278. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  66279. //all done, run the success callback.
  66280. task.successCallback();
  66281. }
  66282. _this.executeNext();
  66283. });
  66284. });
  66285. }
  66286. else {
  66287. //single simplifier.
  66288. var simplifier = this.getSimplifier(task);
  66289. var runDecimation = function (setting, callback) {
  66290. simplifier.simplify(setting, function (newMesh) {
  66291. task.mesh.addLODLevel(setting.distance, newMesh);
  66292. newMesh.isVisible = true;
  66293. //run the next quality level
  66294. callback();
  66295. });
  66296. };
  66297. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  66298. runDecimation(task.settings[loop.index], function () {
  66299. loop.executeNext();
  66300. });
  66301. }, function () {
  66302. //execution ended, run the success callback.
  66303. if (task.successCallback) {
  66304. task.successCallback();
  66305. }
  66306. _this.executeNext();
  66307. });
  66308. }
  66309. };
  66310. SimplificationQueue.prototype.getSimplifier = function (task) {
  66311. switch (task.simplificationType) {
  66312. case SimplificationType.QUADRATIC:
  66313. default:
  66314. return new QuadraticErrorSimplification(task.mesh);
  66315. }
  66316. };
  66317. return SimplificationQueue;
  66318. }());
  66319. BABYLON.SimplificationQueue = SimplificationQueue;
  66320. /**
  66321. * The implemented types of simplification.
  66322. * At the moment only Quadratic Error Decimation is implemented.
  66323. */
  66324. var SimplificationType;
  66325. (function (SimplificationType) {
  66326. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  66327. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  66328. var DecimationTriangle = (function () {
  66329. function DecimationTriangle(vertices) {
  66330. this.vertices = vertices;
  66331. this.error = new Array(4);
  66332. this.deleted = false;
  66333. this.isDirty = false;
  66334. this.deletePending = false;
  66335. this.borderFactor = 0;
  66336. }
  66337. return DecimationTriangle;
  66338. }());
  66339. BABYLON.DecimationTriangle = DecimationTriangle;
  66340. var DecimationVertex = (function () {
  66341. function DecimationVertex(position, id) {
  66342. this.position = position;
  66343. this.id = id;
  66344. this.isBorder = true;
  66345. this.q = new QuadraticMatrix();
  66346. this.triangleCount = 0;
  66347. this.triangleStart = 0;
  66348. this.originalOffsets = [];
  66349. }
  66350. DecimationVertex.prototype.updatePosition = function (newPosition) {
  66351. this.position.copyFrom(newPosition);
  66352. };
  66353. return DecimationVertex;
  66354. }());
  66355. BABYLON.DecimationVertex = DecimationVertex;
  66356. var QuadraticMatrix = (function () {
  66357. function QuadraticMatrix(data) {
  66358. this.data = new Array(10);
  66359. for (var i = 0; i < 10; ++i) {
  66360. if (data && data[i]) {
  66361. this.data[i] = data[i];
  66362. }
  66363. else {
  66364. this.data[i] = 0;
  66365. }
  66366. }
  66367. }
  66368. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  66369. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  66370. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  66371. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  66372. return det;
  66373. };
  66374. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  66375. for (var i = 0; i < 10; ++i) {
  66376. this.data[i] += matrix.data[i];
  66377. }
  66378. };
  66379. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  66380. for (var i = 0; i < 10; ++i) {
  66381. this.data[i] += data[i];
  66382. }
  66383. };
  66384. QuadraticMatrix.prototype.add = function (matrix) {
  66385. var m = new QuadraticMatrix();
  66386. for (var i = 0; i < 10; ++i) {
  66387. m.data[i] = this.data[i] + matrix.data[i];
  66388. }
  66389. return m;
  66390. };
  66391. QuadraticMatrix.FromData = function (a, b, c, d) {
  66392. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  66393. };
  66394. //returning an array to avoid garbage collection
  66395. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  66396. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  66397. };
  66398. return QuadraticMatrix;
  66399. }());
  66400. BABYLON.QuadraticMatrix = QuadraticMatrix;
  66401. var Reference = (function () {
  66402. function Reference(vertexId, triangleId) {
  66403. this.vertexId = vertexId;
  66404. this.triangleId = triangleId;
  66405. }
  66406. return Reference;
  66407. }());
  66408. BABYLON.Reference = Reference;
  66409. /**
  66410. * An implementation of the Quadratic Error simplification algorithm.
  66411. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  66412. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  66413. * @author RaananW
  66414. */
  66415. var QuadraticErrorSimplification = (function () {
  66416. function QuadraticErrorSimplification(_mesh) {
  66417. this._mesh = _mesh;
  66418. this.initialized = false;
  66419. this.syncIterations = 5000;
  66420. this.aggressiveness = 7;
  66421. this.decimationIterations = 100;
  66422. this.boundingBoxEpsilon = BABYLON.Epsilon;
  66423. }
  66424. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  66425. var _this = this;
  66426. this.initDecimatedMesh();
  66427. //iterating through the submeshes array, one after the other.
  66428. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  66429. _this.initWithMesh(loop.index, function () {
  66430. _this.runDecimation(settings, loop.index, function () {
  66431. loop.executeNext();
  66432. });
  66433. }, settings.optimizeMesh);
  66434. }, function () {
  66435. setTimeout(function () {
  66436. successCallback(_this._reconstructedMesh);
  66437. }, 0);
  66438. });
  66439. };
  66440. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  66441. var _this = this;
  66442. var gCount = 0;
  66443. triangle.vertices.forEach(function (vertex) {
  66444. var count = 0;
  66445. var vPos = vertex.position;
  66446. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  66447. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  66448. ++count;
  66449. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  66450. ++count;
  66451. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  66452. ++count;
  66453. if (count > 1) {
  66454. ++gCount;
  66455. }
  66456. ;
  66457. });
  66458. if (gCount > 1) {
  66459. console.log(triangle, gCount);
  66460. }
  66461. return gCount > 1;
  66462. };
  66463. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  66464. var _this = this;
  66465. var targetCount = ~~(this.triangles.length * settings.quality);
  66466. var deletedTriangles = 0;
  66467. var triangleCount = this.triangles.length;
  66468. var iterationFunction = function (iteration, callback) {
  66469. setTimeout(function () {
  66470. if (iteration % 5 === 0) {
  66471. _this.updateMesh(iteration === 0);
  66472. }
  66473. for (var i = 0; i < _this.triangles.length; ++i) {
  66474. _this.triangles[i].isDirty = false;
  66475. }
  66476. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  66477. var trianglesIterator = function (i) {
  66478. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  66479. var t = _this.triangles[tIdx];
  66480. if (!t)
  66481. return;
  66482. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  66483. return;
  66484. }
  66485. for (var j = 0; j < 3; ++j) {
  66486. if (t.error[j] < threshold) {
  66487. var deleted0 = [];
  66488. var deleted1 = [];
  66489. var v0 = t.vertices[j];
  66490. var v1 = t.vertices[(j + 1) % 3];
  66491. if (v0.isBorder || v1.isBorder)
  66492. continue;
  66493. var p = BABYLON.Vector3.Zero();
  66494. var n = BABYLON.Vector3.Zero();
  66495. var uv = BABYLON.Vector2.Zero();
  66496. var color = new BABYLON.Color4(0, 0, 0, 1);
  66497. _this.calculateError(v0, v1, p, n, uv, color);
  66498. var delTr = [];
  66499. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  66500. continue;
  66501. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  66502. continue;
  66503. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  66504. continue;
  66505. var uniqueArray = [];
  66506. delTr.forEach(function (deletedT) {
  66507. if (uniqueArray.indexOf(deletedT) === -1) {
  66508. deletedT.deletePending = true;
  66509. uniqueArray.push(deletedT);
  66510. }
  66511. });
  66512. if (uniqueArray.length % 2 !== 0) {
  66513. continue;
  66514. }
  66515. v0.q = v1.q.add(v0.q);
  66516. v0.updatePosition(p);
  66517. var tStart = _this.references.length;
  66518. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  66519. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  66520. var tCount = _this.references.length - tStart;
  66521. if (tCount <= v0.triangleCount) {
  66522. if (tCount) {
  66523. for (var c = 0; c < tCount; c++) {
  66524. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  66525. }
  66526. }
  66527. }
  66528. else {
  66529. v0.triangleStart = tStart;
  66530. }
  66531. v0.triangleCount = tCount;
  66532. break;
  66533. }
  66534. }
  66535. };
  66536. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  66537. }, 0);
  66538. };
  66539. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  66540. if (triangleCount - deletedTriangles <= targetCount)
  66541. loop.breakLoop();
  66542. else {
  66543. iterationFunction(loop.index, function () {
  66544. loop.executeNext();
  66545. });
  66546. }
  66547. }, function () {
  66548. setTimeout(function () {
  66549. //reconstruct this part of the mesh
  66550. _this.reconstructMesh(submeshIndex);
  66551. successCallback();
  66552. }, 0);
  66553. });
  66554. };
  66555. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  66556. var _this = this;
  66557. this.vertices = [];
  66558. this.triangles = [];
  66559. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  66560. var indices = this._mesh.getIndices();
  66561. var submesh = this._mesh.subMeshes[submeshIndex];
  66562. var findInVertices = function (positionToSearch) {
  66563. if (optimizeMesh) {
  66564. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  66565. if (_this.vertices[ii].position.equals(positionToSearch)) {
  66566. return _this.vertices[ii];
  66567. }
  66568. }
  66569. }
  66570. return null;
  66571. };
  66572. var vertexReferences = [];
  66573. var vertexInit = function (i) {
  66574. var offset = i + submesh.verticesStart;
  66575. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  66576. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  66577. vertex.originalOffsets.push(offset);
  66578. if (vertex.id === _this.vertices.length) {
  66579. _this.vertices.push(vertex);
  66580. }
  66581. vertexReferences.push(vertex.id);
  66582. };
  66583. //var totalVertices = mesh.getTotalVertices();
  66584. var totalVertices = submesh.verticesCount;
  66585. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  66586. var indicesInit = function (i) {
  66587. var offset = (submesh.indexStart / 3) + i;
  66588. var pos = (offset * 3);
  66589. var i0 = indices[pos + 0];
  66590. var i1 = indices[pos + 1];
  66591. var i2 = indices[pos + 2];
  66592. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  66593. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  66594. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  66595. var triangle = new DecimationTriangle([v0, v1, v2]);
  66596. triangle.originalOffset = pos;
  66597. _this.triangles.push(triangle);
  66598. };
  66599. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  66600. _this.init(callback);
  66601. });
  66602. });
  66603. };
  66604. QuadraticErrorSimplification.prototype.init = function (callback) {
  66605. var _this = this;
  66606. var triangleInit1 = function (i) {
  66607. var t = _this.triangles[i];
  66608. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  66609. for (var j = 0; j < 3; j++) {
  66610. 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))));
  66611. }
  66612. };
  66613. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  66614. var triangleInit2 = function (i) {
  66615. var t = _this.triangles[i];
  66616. for (var j = 0; j < 3; ++j) {
  66617. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  66618. }
  66619. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  66620. };
  66621. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  66622. _this.initialized = true;
  66623. callback();
  66624. });
  66625. });
  66626. };
  66627. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  66628. var newTriangles = [];
  66629. var i;
  66630. for (i = 0; i < this.vertices.length; ++i) {
  66631. this.vertices[i].triangleCount = 0;
  66632. }
  66633. var t;
  66634. var j;
  66635. for (i = 0; i < this.triangles.length; ++i) {
  66636. if (!this.triangles[i].deleted) {
  66637. t = this.triangles[i];
  66638. for (j = 0; j < 3; ++j) {
  66639. t.vertices[j].triangleCount = 1;
  66640. }
  66641. newTriangles.push(t);
  66642. }
  66643. }
  66644. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  66645. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  66646. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  66647. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  66648. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  66649. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  66650. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  66651. var vertexCount = 0;
  66652. for (i = 0; i < this.vertices.length; ++i) {
  66653. var vertex = this.vertices[i];
  66654. vertex.id = vertexCount;
  66655. if (vertex.triangleCount) {
  66656. vertex.originalOffsets.forEach(function (originalOffset) {
  66657. newPositionData.push(vertex.position.x);
  66658. newPositionData.push(vertex.position.y);
  66659. newPositionData.push(vertex.position.z);
  66660. newNormalData.push(normalData[originalOffset * 3]);
  66661. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  66662. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  66663. if (uvs && uvs.length) {
  66664. newUVsData.push(uvs[(originalOffset * 2)]);
  66665. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  66666. }
  66667. else if (colorsData && colorsData.length) {
  66668. newColorsData.push(colorsData[(originalOffset * 4)]);
  66669. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  66670. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  66671. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  66672. }
  66673. ++vertexCount;
  66674. });
  66675. }
  66676. }
  66677. var startingIndex = this._reconstructedMesh.getTotalIndices();
  66678. var startingVertex = this._reconstructedMesh.getTotalVertices();
  66679. var submeshesArray = this._reconstructedMesh.subMeshes;
  66680. this._reconstructedMesh.subMeshes = [];
  66681. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  66682. var originalIndices = this._mesh.getIndices();
  66683. for (i = 0; i < newTriangles.length; ++i) {
  66684. t = newTriangles[i]; //now get the new referencing point for each vertex
  66685. [0, 1, 2].forEach(function (idx) {
  66686. var id = originalIndices[t.originalOffset + idx];
  66687. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  66688. if (offset < 0)
  66689. offset = 0;
  66690. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  66691. });
  66692. }
  66693. //overwriting the old vertex buffers and indices.
  66694. this._reconstructedMesh.setIndices(newIndicesArray);
  66695. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  66696. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  66697. if (newUVsData.length > 0)
  66698. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  66699. if (newColorsData.length > 0)
  66700. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  66701. //create submesh
  66702. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  66703. if (submeshIndex > 0) {
  66704. this._reconstructedMesh.subMeshes = [];
  66705. submeshesArray.forEach(function (submesh) {
  66706. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  66707. });
  66708. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  66709. }
  66710. };
  66711. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  66712. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  66713. this._reconstructedMesh.material = this._mesh.material;
  66714. this._reconstructedMesh.parent = this._mesh.parent;
  66715. this._reconstructedMesh.isVisible = false;
  66716. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  66717. };
  66718. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  66719. for (var i = 0; i < vertex1.triangleCount; ++i) {
  66720. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  66721. if (t.deleted)
  66722. continue;
  66723. var s = this.references[vertex1.triangleStart + i].vertexId;
  66724. var v1 = t.vertices[(s + 1) % 3];
  66725. var v2 = t.vertices[(s + 2) % 3];
  66726. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  66727. deletedArray[i] = true;
  66728. delTr.push(t);
  66729. continue;
  66730. }
  66731. var d1 = v1.position.subtract(point);
  66732. d1 = d1.normalize();
  66733. var d2 = v2.position.subtract(point);
  66734. d2 = d2.normalize();
  66735. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  66736. return true;
  66737. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  66738. deletedArray[i] = false;
  66739. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  66740. return true;
  66741. }
  66742. return false;
  66743. };
  66744. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  66745. var newDeleted = deletedTriangles;
  66746. for (var i = 0; i < vertex.triangleCount; ++i) {
  66747. var ref = this.references[vertex.triangleStart + i];
  66748. var t = this.triangles[ref.triangleId];
  66749. if (t.deleted)
  66750. continue;
  66751. if (deletedArray[i] && t.deletePending) {
  66752. t.deleted = true;
  66753. newDeleted++;
  66754. continue;
  66755. }
  66756. t.vertices[ref.vertexId] = origVertex;
  66757. t.isDirty = true;
  66758. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  66759. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  66760. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  66761. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  66762. this.references.push(ref);
  66763. }
  66764. return newDeleted;
  66765. };
  66766. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  66767. for (var i = 0; i < this.vertices.length; ++i) {
  66768. var vCount = [];
  66769. var vId = [];
  66770. var v = this.vertices[i];
  66771. var j;
  66772. for (j = 0; j < v.triangleCount; ++j) {
  66773. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  66774. for (var ii = 0; ii < 3; ii++) {
  66775. var ofs = 0;
  66776. var vv = triangle.vertices[ii];
  66777. while (ofs < vCount.length) {
  66778. if (vId[ofs] === vv.id)
  66779. break;
  66780. ++ofs;
  66781. }
  66782. if (ofs === vCount.length) {
  66783. vCount.push(1);
  66784. vId.push(vv.id);
  66785. }
  66786. else {
  66787. vCount[ofs]++;
  66788. }
  66789. }
  66790. }
  66791. for (j = 0; j < vCount.length; ++j) {
  66792. if (vCount[j] === 1) {
  66793. this.vertices[vId[j]].isBorder = true;
  66794. }
  66795. else {
  66796. this.vertices[vId[j]].isBorder = false;
  66797. }
  66798. }
  66799. }
  66800. };
  66801. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  66802. if (identifyBorders === void 0) { identifyBorders = false; }
  66803. var i;
  66804. if (!identifyBorders) {
  66805. var newTrianglesVector = [];
  66806. for (i = 0; i < this.triangles.length; ++i) {
  66807. if (!this.triangles[i].deleted) {
  66808. newTrianglesVector.push(this.triangles[i]);
  66809. }
  66810. }
  66811. this.triangles = newTrianglesVector;
  66812. }
  66813. for (i = 0; i < this.vertices.length; ++i) {
  66814. this.vertices[i].triangleCount = 0;
  66815. this.vertices[i].triangleStart = 0;
  66816. }
  66817. var t;
  66818. var j;
  66819. var v;
  66820. for (i = 0; i < this.triangles.length; ++i) {
  66821. t = this.triangles[i];
  66822. for (j = 0; j < 3; ++j) {
  66823. v = t.vertices[j];
  66824. v.triangleCount++;
  66825. }
  66826. }
  66827. var tStart = 0;
  66828. for (i = 0; i < this.vertices.length; ++i) {
  66829. this.vertices[i].triangleStart = tStart;
  66830. tStart += this.vertices[i].triangleCount;
  66831. this.vertices[i].triangleCount = 0;
  66832. }
  66833. var newReferences = new Array(this.triangles.length * 3);
  66834. for (i = 0; i < this.triangles.length; ++i) {
  66835. t = this.triangles[i];
  66836. for (j = 0; j < 3; ++j) {
  66837. v = t.vertices[j];
  66838. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  66839. v.triangleCount++;
  66840. }
  66841. }
  66842. this.references = newReferences;
  66843. if (identifyBorders) {
  66844. this.identifyBorder();
  66845. }
  66846. };
  66847. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  66848. var x = point.x;
  66849. var y = point.y;
  66850. var z = point.z;
  66851. 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
  66852. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  66853. };
  66854. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  66855. var q = vertex1.q.add(vertex2.q);
  66856. var border = vertex1.isBorder && vertex2.isBorder;
  66857. var error = 0;
  66858. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  66859. if (qDet !== 0 && !border) {
  66860. if (!pointResult) {
  66861. pointResult = BABYLON.Vector3.Zero();
  66862. }
  66863. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  66864. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  66865. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  66866. error = this.vertexError(q, pointResult);
  66867. }
  66868. else {
  66869. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  66870. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  66871. var error1 = this.vertexError(q, vertex1.position);
  66872. var error2 = this.vertexError(q, vertex2.position);
  66873. var error3 = this.vertexError(q, p3);
  66874. error = Math.min(error1, error2, error3);
  66875. if (error === error1) {
  66876. if (pointResult) {
  66877. pointResult.copyFrom(vertex1.position);
  66878. }
  66879. }
  66880. else if (error === error2) {
  66881. if (pointResult) {
  66882. pointResult.copyFrom(vertex2.position);
  66883. }
  66884. }
  66885. else {
  66886. if (pointResult) {
  66887. pointResult.copyFrom(p3);
  66888. }
  66889. }
  66890. }
  66891. return error;
  66892. };
  66893. return QuadraticErrorSimplification;
  66894. }());
  66895. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  66896. })(BABYLON || (BABYLON = {}));
  66897. //# sourceMappingURL=babylon.meshSimplification.js.map
  66898. var BABYLON;
  66899. (function (BABYLON) {
  66900. var Internals;
  66901. (function (Internals) {
  66902. var MeshLODLevel = (function () {
  66903. function MeshLODLevel(distance, mesh) {
  66904. this.distance = distance;
  66905. this.mesh = mesh;
  66906. }
  66907. return MeshLODLevel;
  66908. }());
  66909. Internals.MeshLODLevel = MeshLODLevel;
  66910. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  66911. })(BABYLON || (BABYLON = {}));
  66912. //# sourceMappingURL=babylon.meshLODLevel.js.map
  66913. var BABYLON;
  66914. (function (BABYLON) {
  66915. // Standard optimizations
  66916. var SceneOptimization = (function () {
  66917. function SceneOptimization(priority) {
  66918. if (priority === void 0) { priority = 0; }
  66919. this.priority = priority;
  66920. this.apply = function (scene) {
  66921. return true; // Return true if everything that can be done was applied
  66922. };
  66923. }
  66924. return SceneOptimization;
  66925. }());
  66926. BABYLON.SceneOptimization = SceneOptimization;
  66927. var TextureOptimization = (function (_super) {
  66928. __extends(TextureOptimization, _super);
  66929. function TextureOptimization(priority, maximumSize) {
  66930. if (priority === void 0) { priority = 0; }
  66931. if (maximumSize === void 0) { maximumSize = 1024; }
  66932. var _this = _super.call(this, priority) || this;
  66933. _this.priority = priority;
  66934. _this.maximumSize = maximumSize;
  66935. _this.apply = function (scene) {
  66936. var allDone = true;
  66937. for (var index = 0; index < scene.textures.length; index++) {
  66938. var texture = scene.textures[index];
  66939. if (!texture.canRescale || texture.getContext) {
  66940. continue;
  66941. }
  66942. var currentSize = texture.getSize();
  66943. var maxDimension = Math.max(currentSize.width, currentSize.height);
  66944. if (maxDimension > _this.maximumSize) {
  66945. texture.scale(0.5);
  66946. allDone = false;
  66947. }
  66948. }
  66949. return allDone;
  66950. };
  66951. return _this;
  66952. }
  66953. return TextureOptimization;
  66954. }(SceneOptimization));
  66955. BABYLON.TextureOptimization = TextureOptimization;
  66956. var HardwareScalingOptimization = (function (_super) {
  66957. __extends(HardwareScalingOptimization, _super);
  66958. function HardwareScalingOptimization(priority, maximumScale) {
  66959. if (priority === void 0) { priority = 0; }
  66960. if (maximumScale === void 0) { maximumScale = 2; }
  66961. var _this = _super.call(this, priority) || this;
  66962. _this.priority = priority;
  66963. _this.maximumScale = maximumScale;
  66964. _this._currentScale = 1;
  66965. _this.apply = function (scene) {
  66966. _this._currentScale++;
  66967. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  66968. return _this._currentScale >= _this.maximumScale;
  66969. };
  66970. return _this;
  66971. }
  66972. return HardwareScalingOptimization;
  66973. }(SceneOptimization));
  66974. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  66975. var ShadowsOptimization = (function (_super) {
  66976. __extends(ShadowsOptimization, _super);
  66977. function ShadowsOptimization() {
  66978. var _this = _super !== null && _super.apply(this, arguments) || this;
  66979. _this.apply = function (scene) {
  66980. scene.shadowsEnabled = false;
  66981. return true;
  66982. };
  66983. return _this;
  66984. }
  66985. return ShadowsOptimization;
  66986. }(SceneOptimization));
  66987. BABYLON.ShadowsOptimization = ShadowsOptimization;
  66988. var PostProcessesOptimization = (function (_super) {
  66989. __extends(PostProcessesOptimization, _super);
  66990. function PostProcessesOptimization() {
  66991. var _this = _super !== null && _super.apply(this, arguments) || this;
  66992. _this.apply = function (scene) {
  66993. scene.postProcessesEnabled = false;
  66994. return true;
  66995. };
  66996. return _this;
  66997. }
  66998. return PostProcessesOptimization;
  66999. }(SceneOptimization));
  67000. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  67001. var LensFlaresOptimization = (function (_super) {
  67002. __extends(LensFlaresOptimization, _super);
  67003. function LensFlaresOptimization() {
  67004. var _this = _super !== null && _super.apply(this, arguments) || this;
  67005. _this.apply = function (scene) {
  67006. scene.lensFlaresEnabled = false;
  67007. return true;
  67008. };
  67009. return _this;
  67010. }
  67011. return LensFlaresOptimization;
  67012. }(SceneOptimization));
  67013. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  67014. var ParticlesOptimization = (function (_super) {
  67015. __extends(ParticlesOptimization, _super);
  67016. function ParticlesOptimization() {
  67017. var _this = _super !== null && _super.apply(this, arguments) || this;
  67018. _this.apply = function (scene) {
  67019. scene.particlesEnabled = false;
  67020. return true;
  67021. };
  67022. return _this;
  67023. }
  67024. return ParticlesOptimization;
  67025. }(SceneOptimization));
  67026. BABYLON.ParticlesOptimization = ParticlesOptimization;
  67027. var RenderTargetsOptimization = (function (_super) {
  67028. __extends(RenderTargetsOptimization, _super);
  67029. function RenderTargetsOptimization() {
  67030. var _this = _super !== null && _super.apply(this, arguments) || this;
  67031. _this.apply = function (scene) {
  67032. scene.renderTargetsEnabled = false;
  67033. return true;
  67034. };
  67035. return _this;
  67036. }
  67037. return RenderTargetsOptimization;
  67038. }(SceneOptimization));
  67039. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  67040. var MergeMeshesOptimization = (function (_super) {
  67041. __extends(MergeMeshesOptimization, _super);
  67042. function MergeMeshesOptimization() {
  67043. var _this = _super !== null && _super.apply(this, arguments) || this;
  67044. _this._canBeMerged = function (abstractMesh) {
  67045. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  67046. return false;
  67047. }
  67048. var mesh = abstractMesh;
  67049. if (!mesh.isVisible || !mesh.isEnabled()) {
  67050. return false;
  67051. }
  67052. if (mesh.instances.length > 0) {
  67053. return false;
  67054. }
  67055. if (mesh.skeleton || mesh.hasLODLevels) {
  67056. return false;
  67057. }
  67058. if (mesh.parent) {
  67059. return false;
  67060. }
  67061. return true;
  67062. };
  67063. _this.apply = function (scene, updateSelectionTree) {
  67064. var globalPool = scene.meshes.slice(0);
  67065. var globalLength = globalPool.length;
  67066. for (var index = 0; index < globalLength; index++) {
  67067. var currentPool = new Array();
  67068. var current = globalPool[index];
  67069. // Checks
  67070. if (!_this._canBeMerged(current)) {
  67071. continue;
  67072. }
  67073. currentPool.push(current);
  67074. // Find compatible meshes
  67075. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  67076. var otherMesh = globalPool[subIndex];
  67077. if (!_this._canBeMerged(otherMesh)) {
  67078. continue;
  67079. }
  67080. if (otherMesh.material !== current.material) {
  67081. continue;
  67082. }
  67083. if (otherMesh.checkCollisions !== current.checkCollisions) {
  67084. continue;
  67085. }
  67086. currentPool.push(otherMesh);
  67087. globalLength--;
  67088. globalPool.splice(subIndex, 1);
  67089. subIndex--;
  67090. }
  67091. if (currentPool.length < 2) {
  67092. continue;
  67093. }
  67094. // Merge meshes
  67095. BABYLON.Mesh.MergeMeshes(currentPool);
  67096. }
  67097. if (updateSelectionTree != undefined) {
  67098. if (updateSelectionTree) {
  67099. scene.createOrUpdateSelectionOctree();
  67100. }
  67101. }
  67102. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  67103. scene.createOrUpdateSelectionOctree();
  67104. }
  67105. return true;
  67106. };
  67107. return _this;
  67108. }
  67109. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  67110. get: function () {
  67111. return MergeMeshesOptimization._UpdateSelectionTree;
  67112. },
  67113. set: function (value) {
  67114. MergeMeshesOptimization._UpdateSelectionTree = value;
  67115. },
  67116. enumerable: true,
  67117. configurable: true
  67118. });
  67119. MergeMeshesOptimization._UpdateSelectionTree = false;
  67120. return MergeMeshesOptimization;
  67121. }(SceneOptimization));
  67122. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  67123. // Options
  67124. var SceneOptimizerOptions = (function () {
  67125. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  67126. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  67127. if (trackerDuration === void 0) { trackerDuration = 2000; }
  67128. this.targetFrameRate = targetFrameRate;
  67129. this.trackerDuration = trackerDuration;
  67130. this.optimizations = new Array();
  67131. }
  67132. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  67133. var result = new SceneOptimizerOptions(targetFrameRate);
  67134. var priority = 0;
  67135. result.optimizations.push(new MergeMeshesOptimization(priority));
  67136. result.optimizations.push(new ShadowsOptimization(priority));
  67137. result.optimizations.push(new LensFlaresOptimization(priority));
  67138. // Next priority
  67139. priority++;
  67140. result.optimizations.push(new PostProcessesOptimization(priority));
  67141. result.optimizations.push(new ParticlesOptimization(priority));
  67142. // Next priority
  67143. priority++;
  67144. result.optimizations.push(new TextureOptimization(priority, 1024));
  67145. return result;
  67146. };
  67147. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  67148. var result = new SceneOptimizerOptions(targetFrameRate);
  67149. var priority = 0;
  67150. result.optimizations.push(new MergeMeshesOptimization(priority));
  67151. result.optimizations.push(new ShadowsOptimization(priority));
  67152. result.optimizations.push(new LensFlaresOptimization(priority));
  67153. // Next priority
  67154. priority++;
  67155. result.optimizations.push(new PostProcessesOptimization(priority));
  67156. result.optimizations.push(new ParticlesOptimization(priority));
  67157. // Next priority
  67158. priority++;
  67159. result.optimizations.push(new TextureOptimization(priority, 512));
  67160. // Next priority
  67161. priority++;
  67162. result.optimizations.push(new RenderTargetsOptimization(priority));
  67163. // Next priority
  67164. priority++;
  67165. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  67166. return result;
  67167. };
  67168. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  67169. var result = new SceneOptimizerOptions(targetFrameRate);
  67170. var priority = 0;
  67171. result.optimizations.push(new MergeMeshesOptimization(priority));
  67172. result.optimizations.push(new ShadowsOptimization(priority));
  67173. result.optimizations.push(new LensFlaresOptimization(priority));
  67174. // Next priority
  67175. priority++;
  67176. result.optimizations.push(new PostProcessesOptimization(priority));
  67177. result.optimizations.push(new ParticlesOptimization(priority));
  67178. // Next priority
  67179. priority++;
  67180. result.optimizations.push(new TextureOptimization(priority, 256));
  67181. // Next priority
  67182. priority++;
  67183. result.optimizations.push(new RenderTargetsOptimization(priority));
  67184. // Next priority
  67185. priority++;
  67186. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  67187. return result;
  67188. };
  67189. return SceneOptimizerOptions;
  67190. }());
  67191. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  67192. // Scene optimizer tool
  67193. var SceneOptimizer = (function () {
  67194. function SceneOptimizer() {
  67195. }
  67196. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  67197. // TODO: add an epsilon
  67198. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  67199. if (onSuccess) {
  67200. onSuccess();
  67201. }
  67202. return;
  67203. }
  67204. // Apply current level of optimizations
  67205. var allDone = true;
  67206. var noOptimizationApplied = true;
  67207. for (var index = 0; index < options.optimizations.length; index++) {
  67208. var optimization = options.optimizations[index];
  67209. if (optimization.priority === currentPriorityLevel) {
  67210. noOptimizationApplied = false;
  67211. allDone = allDone && optimization.apply(scene);
  67212. }
  67213. }
  67214. // If no optimization was applied, this is a failure :(
  67215. if (noOptimizationApplied) {
  67216. if (onFailure) {
  67217. onFailure();
  67218. }
  67219. return;
  67220. }
  67221. // If all optimizations were done, move to next level
  67222. if (allDone) {
  67223. currentPriorityLevel++;
  67224. }
  67225. // Let's the system running for a specific amount of time before checking FPS
  67226. scene.executeWhenReady(function () {
  67227. setTimeout(function () {
  67228. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  67229. }, options.trackerDuration);
  67230. });
  67231. };
  67232. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  67233. if (!options) {
  67234. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  67235. }
  67236. // Let's the system running for a specific amount of time before checking FPS
  67237. scene.executeWhenReady(function () {
  67238. setTimeout(function () {
  67239. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  67240. }, options.trackerDuration);
  67241. });
  67242. };
  67243. return SceneOptimizer;
  67244. }());
  67245. BABYLON.SceneOptimizer = SceneOptimizer;
  67246. })(BABYLON || (BABYLON = {}));
  67247. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  67248. var BABYLON;
  67249. (function (BABYLON) {
  67250. var OutlineRenderer = (function () {
  67251. function OutlineRenderer(scene) {
  67252. this.zOffset = 1;
  67253. this._scene = scene;
  67254. }
  67255. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  67256. var _this = this;
  67257. if (useOverlay === void 0) { useOverlay = false; }
  67258. var scene = this._scene;
  67259. var engine = this._scene.getEngine();
  67260. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  67261. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  67262. return;
  67263. }
  67264. var mesh = subMesh.getRenderingMesh();
  67265. var material = subMesh.getMaterial();
  67266. engine.enableEffect(this._effect);
  67267. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  67268. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  67269. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  67270. // Bones
  67271. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67272. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67273. }
  67274. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  67275. // Alpha test
  67276. if (material && material.needAlphaTesting()) {
  67277. var alphaTexture = material.getAlphaTestTexture();
  67278. if (alphaTexture) {
  67279. this._effect.setTexture("diffuseSampler", alphaTexture);
  67280. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67281. }
  67282. }
  67283. engine.setZOffset(-this.zOffset);
  67284. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  67285. engine.setZOffset(0);
  67286. };
  67287. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  67288. var defines = [];
  67289. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  67290. var mesh = subMesh.getMesh();
  67291. var material = subMesh.getMaterial();
  67292. // Alpha test
  67293. if (material && material.needAlphaTesting()) {
  67294. defines.push("#define ALPHATEST");
  67295. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67296. attribs.push(BABYLON.VertexBuffer.UVKind);
  67297. defines.push("#define UV1");
  67298. }
  67299. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67300. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67301. defines.push("#define UV2");
  67302. }
  67303. }
  67304. // Bones
  67305. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67306. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67307. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67308. if (mesh.numBoneInfluencers > 4) {
  67309. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  67310. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  67311. }
  67312. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67313. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  67314. }
  67315. else {
  67316. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67317. }
  67318. // Instances
  67319. if (useInstances) {
  67320. defines.push("#define INSTANCES");
  67321. attribs.push("world0");
  67322. attribs.push("world1");
  67323. attribs.push("world2");
  67324. attribs.push("world3");
  67325. }
  67326. // Get correct effect
  67327. var join = defines.join("\n");
  67328. if (this._cachedDefines !== join) {
  67329. this._cachedDefines = join;
  67330. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  67331. }
  67332. return this._effect.isReady();
  67333. };
  67334. return OutlineRenderer;
  67335. }());
  67336. BABYLON.OutlineRenderer = OutlineRenderer;
  67337. })(BABYLON || (BABYLON = {}));
  67338. //# sourceMappingURL=babylon.outlineRenderer.js.map
  67339. var BABYLON;
  67340. (function (BABYLON) {
  67341. var FaceAdjacencies = (function () {
  67342. function FaceAdjacencies() {
  67343. this.edges = new Array();
  67344. this.edgesConnectedCount = 0;
  67345. }
  67346. return FaceAdjacencies;
  67347. }());
  67348. var EdgesRenderer = (function () {
  67349. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  67350. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  67351. if (epsilon === void 0) { epsilon = 0.95; }
  67352. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  67353. this.edgesWidthScalerForOrthographic = 1000.0;
  67354. this.edgesWidthScalerForPerspective = 50.0;
  67355. this._linesPositions = new Array();
  67356. this._linesNormals = new Array();
  67357. this._linesIndices = new Array();
  67358. this._buffers = {};
  67359. this._checkVerticesInsteadOfIndices = false;
  67360. this._source = source;
  67361. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  67362. this._epsilon = epsilon;
  67363. this._prepareRessources();
  67364. this._generateEdgesLines();
  67365. }
  67366. EdgesRenderer.prototype._prepareRessources = function () {
  67367. if (this._lineShader) {
  67368. return;
  67369. }
  67370. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  67371. attributes: ["position", "normal"],
  67372. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  67373. });
  67374. this._lineShader.disableDepthWrite = true;
  67375. this._lineShader.backFaceCulling = false;
  67376. };
  67377. EdgesRenderer.prototype.dispose = function () {
  67378. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  67379. if (buffer) {
  67380. buffer.dispose();
  67381. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  67382. }
  67383. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  67384. if (buffer) {
  67385. buffer.dispose();
  67386. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  67387. }
  67388. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  67389. this._lineShader.dispose();
  67390. };
  67391. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  67392. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  67393. return 0;
  67394. }
  67395. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  67396. return 1;
  67397. }
  67398. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  67399. return 2;
  67400. }
  67401. return -1;
  67402. };
  67403. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  67404. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  67405. return 0;
  67406. }
  67407. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  67408. return 1;
  67409. }
  67410. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  67411. return 2;
  67412. }
  67413. return -1;
  67414. };
  67415. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  67416. var needToCreateLine;
  67417. if (edge === undefined) {
  67418. needToCreateLine = true;
  67419. }
  67420. else {
  67421. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  67422. needToCreateLine = dotProduct < this._epsilon;
  67423. }
  67424. if (needToCreateLine) {
  67425. var offset = this._linesPositions.length / 3;
  67426. var normal = p0.subtract(p1);
  67427. normal.normalize();
  67428. // Positions
  67429. this._linesPositions.push(p0.x);
  67430. this._linesPositions.push(p0.y);
  67431. this._linesPositions.push(p0.z);
  67432. this._linesPositions.push(p0.x);
  67433. this._linesPositions.push(p0.y);
  67434. this._linesPositions.push(p0.z);
  67435. this._linesPositions.push(p1.x);
  67436. this._linesPositions.push(p1.y);
  67437. this._linesPositions.push(p1.z);
  67438. this._linesPositions.push(p1.x);
  67439. this._linesPositions.push(p1.y);
  67440. this._linesPositions.push(p1.z);
  67441. // Normals
  67442. this._linesNormals.push(p1.x);
  67443. this._linesNormals.push(p1.y);
  67444. this._linesNormals.push(p1.z);
  67445. this._linesNormals.push(-1);
  67446. this._linesNormals.push(p1.x);
  67447. this._linesNormals.push(p1.y);
  67448. this._linesNormals.push(p1.z);
  67449. this._linesNormals.push(1);
  67450. this._linesNormals.push(p0.x);
  67451. this._linesNormals.push(p0.y);
  67452. this._linesNormals.push(p0.z);
  67453. this._linesNormals.push(-1);
  67454. this._linesNormals.push(p0.x);
  67455. this._linesNormals.push(p0.y);
  67456. this._linesNormals.push(p0.z);
  67457. this._linesNormals.push(1);
  67458. // Indices
  67459. this._linesIndices.push(offset);
  67460. this._linesIndices.push(offset + 1);
  67461. this._linesIndices.push(offset + 2);
  67462. this._linesIndices.push(offset);
  67463. this._linesIndices.push(offset + 2);
  67464. this._linesIndices.push(offset + 3);
  67465. }
  67466. };
  67467. EdgesRenderer.prototype._generateEdgesLines = function () {
  67468. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  67469. var indices = this._source.getIndices();
  67470. // First let's find adjacencies
  67471. var adjacencies = new Array();
  67472. var faceNormals = new Array();
  67473. var index;
  67474. var faceAdjacencies;
  67475. // Prepare faces
  67476. for (index = 0; index < indices.length; index += 3) {
  67477. faceAdjacencies = new FaceAdjacencies();
  67478. var p0Index = indices[index];
  67479. var p1Index = indices[index + 1];
  67480. var p2Index = indices[index + 2];
  67481. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  67482. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  67483. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  67484. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  67485. faceNormal.normalize();
  67486. faceNormals.push(faceNormal);
  67487. adjacencies.push(faceAdjacencies);
  67488. }
  67489. // Scan
  67490. for (index = 0; index < adjacencies.length; index++) {
  67491. faceAdjacencies = adjacencies[index];
  67492. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  67493. var otherFaceAdjacencies = adjacencies[otherIndex];
  67494. if (faceAdjacencies.edgesConnectedCount === 3) {
  67495. break;
  67496. }
  67497. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  67498. continue;
  67499. }
  67500. var otherP0 = indices[otherIndex * 3];
  67501. var otherP1 = indices[otherIndex * 3 + 1];
  67502. var otherP2 = indices[otherIndex * 3 + 2];
  67503. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  67504. var otherEdgeIndex;
  67505. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  67506. continue;
  67507. }
  67508. switch (edgeIndex) {
  67509. case 0:
  67510. if (this._checkVerticesInsteadOfIndices) {
  67511. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  67512. }
  67513. else {
  67514. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  67515. }
  67516. break;
  67517. case 1:
  67518. if (this._checkVerticesInsteadOfIndices) {
  67519. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  67520. }
  67521. else {
  67522. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  67523. }
  67524. break;
  67525. case 2:
  67526. if (this._checkVerticesInsteadOfIndices) {
  67527. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  67528. }
  67529. else {
  67530. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  67531. }
  67532. break;
  67533. }
  67534. if (otherEdgeIndex === -1) {
  67535. continue;
  67536. }
  67537. faceAdjacencies.edges[edgeIndex] = otherIndex;
  67538. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  67539. faceAdjacencies.edgesConnectedCount++;
  67540. otherFaceAdjacencies.edgesConnectedCount++;
  67541. if (faceAdjacencies.edgesConnectedCount === 3) {
  67542. break;
  67543. }
  67544. }
  67545. }
  67546. }
  67547. // Create lines
  67548. for (index = 0; index < adjacencies.length; index++) {
  67549. // 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
  67550. var current = adjacencies[index];
  67551. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  67552. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  67553. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  67554. }
  67555. // Merge into a single mesh
  67556. var engine = this._source.getScene().getEngine();
  67557. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  67558. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  67559. this._ib = engine.createIndexBuffer(this._linesIndices);
  67560. this._indicesCount = this._linesIndices.length;
  67561. };
  67562. EdgesRenderer.prototype.render = function () {
  67563. if (!this._lineShader.isReady()) {
  67564. return;
  67565. }
  67566. var scene = this._source.getScene();
  67567. var engine = scene.getEngine();
  67568. this._lineShader._preBind();
  67569. // VBOs
  67570. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  67571. scene.resetCachedMaterial();
  67572. this._lineShader.setColor4("color", this._source.edgesColor);
  67573. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  67574. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  67575. }
  67576. else {
  67577. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  67578. }
  67579. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  67580. this._lineShader.bind(this._source.getWorldMatrix());
  67581. // Draw order
  67582. engine.draw(true, 0, this._indicesCount);
  67583. this._lineShader.unbind();
  67584. engine.setDepthWrite(true);
  67585. };
  67586. return EdgesRenderer;
  67587. }());
  67588. BABYLON.EdgesRenderer = EdgesRenderer;
  67589. })(BABYLON || (BABYLON = {}));
  67590. //# sourceMappingURL=babylon.edgesRenderer.js.map
  67591. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  67592. /// <reference path="..\Math\babylon.math.ts" />
  67593. var BABYLON;
  67594. (function (BABYLON) {
  67595. /**
  67596. * Special Glow Blur post process only blurring the alpha channel
  67597. * It enforces keeping the most luminous color in the color channel.
  67598. */
  67599. var GlowBlurPostProcess = (function (_super) {
  67600. __extends(GlowBlurPostProcess, _super);
  67601. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  67602. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  67603. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  67604. _this.direction = direction;
  67605. _this.kernel = kernel;
  67606. _this.onApplyObservable.add(function (effect) {
  67607. effect.setFloat2("screenSize", _this.width, _this.height);
  67608. effect.setVector2("direction", _this.direction);
  67609. effect.setFloat("blurWidth", _this.kernel);
  67610. });
  67611. return _this;
  67612. }
  67613. return GlowBlurPostProcess;
  67614. }(BABYLON.PostProcess));
  67615. /**
  67616. * The highlight layer Helps adding a glow effect around a mesh.
  67617. *
  67618. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  67619. * glowy meshes to your scene.
  67620. *
  67621. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  67622. */
  67623. var HighlightLayer = (function () {
  67624. /**
  67625. * Instantiates a new highlight Layer and references it to the scene..
  67626. * @param name The name of the layer
  67627. * @param scene The scene to use the layer in
  67628. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  67629. */
  67630. function HighlightLayer(name, scene, options) {
  67631. this.name = name;
  67632. this._vertexBuffers = {};
  67633. this._mainTextureDesiredSize = { width: 0, height: 0 };
  67634. this._meshes = {};
  67635. this._maxSize = 0;
  67636. this._shouldRender = false;
  67637. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  67638. this._excludedMeshes = {};
  67639. /**
  67640. * Specifies whether or not the inner glow is ACTIVE in the layer.
  67641. */
  67642. this.innerGlow = true;
  67643. /**
  67644. * Specifies whether or not the outer glow is ACTIVE in the layer.
  67645. */
  67646. this.outerGlow = true;
  67647. /**
  67648. * Specifies wether the highlight layer is enabled or not.
  67649. */
  67650. this.isEnabled = true;
  67651. /**
  67652. * An event triggered when the highlight layer has been disposed.
  67653. * @type {BABYLON.Observable}
  67654. */
  67655. this.onDisposeObservable = new BABYLON.Observable();
  67656. /**
  67657. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  67658. * @type {BABYLON.Observable}
  67659. */
  67660. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  67661. /**
  67662. * An event triggered when the highlight layer is being blurred.
  67663. * @type {BABYLON.Observable}
  67664. */
  67665. this.onBeforeBlurObservable = new BABYLON.Observable();
  67666. /**
  67667. * An event triggered when the highlight layer has been blurred.
  67668. * @type {BABYLON.Observable}
  67669. */
  67670. this.onAfterBlurObservable = new BABYLON.Observable();
  67671. /**
  67672. * An event triggered when the glowing blurred texture is being merged in the scene.
  67673. * @type {BABYLON.Observable}
  67674. */
  67675. this.onBeforeComposeObservable = new BABYLON.Observable();
  67676. /**
  67677. * An event triggered when the glowing blurred texture has been merged in the scene.
  67678. * @type {BABYLON.Observable}
  67679. */
  67680. this.onAfterComposeObservable = new BABYLON.Observable();
  67681. /**
  67682. * An event triggered when the highlight layer changes its size.
  67683. * @type {BABYLON.Observable}
  67684. */
  67685. this.onSizeChangedObservable = new BABYLON.Observable();
  67686. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  67687. var engine = scene.getEngine();
  67688. this._engine = engine;
  67689. this._maxSize = this._engine.getCaps().maxTextureSize;
  67690. this._scene.highlightLayers.push(this);
  67691. // Warn on stencil.
  67692. if (!this._engine.isStencilEnable) {
  67693. 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 }");
  67694. }
  67695. // Adapt options
  67696. this._options = options || {
  67697. mainTextureRatio: 0.5,
  67698. blurTextureSizeRatio: 0.5,
  67699. blurHorizontalSize: 1.0,
  67700. blurVerticalSize: 1.0,
  67701. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  67702. };
  67703. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  67704. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  67705. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  67706. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  67707. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  67708. // VBO
  67709. var vertices = [];
  67710. vertices.push(1, 1);
  67711. vertices.push(-1, 1);
  67712. vertices.push(-1, -1);
  67713. vertices.push(1, -1);
  67714. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  67715. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  67716. this._createIndexBuffer();
  67717. // Effect
  67718. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  67719. // Render target
  67720. this.setMainTextureSize();
  67721. // Create Textures and post processes
  67722. this.createTextureAndPostProcesses();
  67723. }
  67724. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  67725. /**
  67726. * Gets the horizontal size of the blur.
  67727. */
  67728. get: function () {
  67729. return this._horizontalBlurPostprocess.kernel;
  67730. },
  67731. /**
  67732. * Specifies the horizontal size of the blur.
  67733. */
  67734. set: function (value) {
  67735. this._horizontalBlurPostprocess.kernel = value;
  67736. },
  67737. enumerable: true,
  67738. configurable: true
  67739. });
  67740. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  67741. /**
  67742. * Gets the vertical size of the blur.
  67743. */
  67744. get: function () {
  67745. return this._verticalBlurPostprocess.kernel;
  67746. },
  67747. /**
  67748. * Specifies the vertical size of the blur.
  67749. */
  67750. set: function (value) {
  67751. this._verticalBlurPostprocess.kernel = value;
  67752. },
  67753. enumerable: true,
  67754. configurable: true
  67755. });
  67756. Object.defineProperty(HighlightLayer.prototype, "camera", {
  67757. /**
  67758. * Gets the camera attached to the layer.
  67759. */
  67760. get: function () {
  67761. return this._options.camera;
  67762. },
  67763. enumerable: true,
  67764. configurable: true
  67765. });
  67766. HighlightLayer.prototype._createIndexBuffer = function () {
  67767. var engine = this._scene.getEngine();
  67768. // Indices
  67769. var indices = [];
  67770. indices.push(0);
  67771. indices.push(1);
  67772. indices.push(2);
  67773. indices.push(0);
  67774. indices.push(2);
  67775. indices.push(3);
  67776. this._indexBuffer = engine.createIndexBuffer(indices);
  67777. };
  67778. HighlightLayer.prototype._rebuild = function () {
  67779. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  67780. this._createIndexBuffer();
  67781. };
  67782. /**
  67783. * Creates the render target textures and post processes used in the highlight layer.
  67784. */
  67785. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  67786. var _this = this;
  67787. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  67788. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  67789. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  67790. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  67791. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  67792. width: this._mainTextureDesiredSize.width,
  67793. height: this._mainTextureDesiredSize.height
  67794. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  67795. this._mainTexture.activeCamera = this._options.camera;
  67796. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67797. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67798. this._mainTexture.anisotropicFilteringLevel = 1;
  67799. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  67800. this._mainTexture.renderParticles = false;
  67801. this._mainTexture.renderList = null;
  67802. this._mainTexture.ignoreCameraViewport = true;
  67803. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  67804. width: blurTextureWidth,
  67805. height: blurTextureHeight
  67806. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  67807. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67808. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67809. this._blurTexture.anisotropicFilteringLevel = 16;
  67810. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  67811. this._blurTexture.renderParticles = false;
  67812. this._blurTexture.ignoreCameraViewport = true;
  67813. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  67814. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  67815. effect.setTexture("textureSampler", _this._mainTexture);
  67816. });
  67817. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  67818. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  67819. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  67820. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  67821. });
  67822. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  67823. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  67824. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  67825. });
  67826. }
  67827. else {
  67828. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  67829. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  67830. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  67831. });
  67832. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  67833. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  67834. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  67835. });
  67836. }
  67837. this._mainTexture.onAfterUnbindObservable.add(function () {
  67838. _this.onBeforeBlurObservable.notifyObservers(_this);
  67839. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture(), true);
  67840. _this.onAfterBlurObservable.notifyObservers(_this);
  67841. });
  67842. // Custom render function
  67843. var renderSubMesh = function (subMesh) {
  67844. var mesh = subMesh.getRenderingMesh();
  67845. var scene = _this._scene;
  67846. var engine = scene.getEngine();
  67847. // Culling
  67848. engine.setState(subMesh.getMaterial().backFaceCulling);
  67849. // Managing instances
  67850. var batch = mesh._getInstancesRenderList(subMesh._id);
  67851. if (batch.mustReturn) {
  67852. return;
  67853. }
  67854. // Excluded Mesh
  67855. if (_this._excludedMeshes[mesh.uniqueId]) {
  67856. return;
  67857. }
  67858. ;
  67859. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  67860. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  67861. var material = subMesh.getMaterial();
  67862. var emissiveTexture = null;
  67863. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  67864. emissiveTexture = material.emissiveTexture;
  67865. }
  67866. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  67867. engine.enableEffect(_this._glowMapGenerationEffect);
  67868. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  67869. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  67870. if (highlightLayerMesh) {
  67871. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  67872. }
  67873. else {
  67874. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  67875. }
  67876. // Alpha test
  67877. if (material && material.needAlphaTesting()) {
  67878. var alphaTexture = material.getAlphaTestTexture();
  67879. if (alphaTexture) {
  67880. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  67881. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67882. }
  67883. }
  67884. // Glow emissive only
  67885. if (emissiveTexture) {
  67886. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  67887. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  67888. }
  67889. // Bones
  67890. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67891. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67892. }
  67893. // Draw
  67894. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  67895. }
  67896. else {
  67897. // Need to reset refresh rate of the shadowMap
  67898. _this._mainTexture.resetRefreshCounter();
  67899. }
  67900. };
  67901. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  67902. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  67903. var index;
  67904. for (index = 0; index < opaqueSubMeshes.length; index++) {
  67905. renderSubMesh(opaqueSubMeshes.data[index]);
  67906. }
  67907. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  67908. renderSubMesh(alphaTestSubMeshes.data[index]);
  67909. }
  67910. for (index = 0; index < transparentSubMeshes.length; index++) {
  67911. renderSubMesh(transparentSubMeshes.data[index]);
  67912. }
  67913. };
  67914. this._mainTexture.onClearObservable.add(function (engine) {
  67915. engine.clear(HighlightLayer.neutralColor, true, true, true);
  67916. });
  67917. };
  67918. /**
  67919. * Checks for the readiness of the element composing the layer.
  67920. * @param subMesh the mesh to check for
  67921. * @param useInstances specify wether or not to use instances to render the mesh
  67922. * @param emissiveTexture the associated emissive texture used to generate the glow
  67923. * @return true if ready otherwise, false
  67924. */
  67925. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  67926. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  67927. return false;
  67928. }
  67929. var defines = [];
  67930. var attribs = [BABYLON.VertexBuffer.PositionKind];
  67931. var mesh = subMesh.getMesh();
  67932. var material = subMesh.getMaterial();
  67933. var uv1 = false;
  67934. var uv2 = false;
  67935. // Alpha test
  67936. if (material && material.needAlphaTesting()) {
  67937. var alphaTexture = material.getAlphaTestTexture();
  67938. if (alphaTexture) {
  67939. defines.push("#define ALPHATEST");
  67940. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  67941. alphaTexture.coordinatesIndex === 1) {
  67942. defines.push("#define DIFFUSEUV2");
  67943. uv2 = true;
  67944. }
  67945. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67946. defines.push("#define DIFFUSEUV1");
  67947. uv1 = true;
  67948. }
  67949. }
  67950. }
  67951. // Emissive
  67952. if (emissiveTexture) {
  67953. defines.push("#define EMISSIVE");
  67954. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  67955. emissiveTexture.coordinatesIndex === 1) {
  67956. defines.push("#define EMISSIVEUV2");
  67957. uv2 = true;
  67958. }
  67959. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67960. defines.push("#define EMISSIVEUV1");
  67961. uv1 = true;
  67962. }
  67963. }
  67964. if (uv1) {
  67965. attribs.push(BABYLON.VertexBuffer.UVKind);
  67966. defines.push("#define UV1");
  67967. }
  67968. if (uv2) {
  67969. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67970. defines.push("#define UV2");
  67971. }
  67972. // Bones
  67973. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67974. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67975. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67976. if (mesh.numBoneInfluencers > 4) {
  67977. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  67978. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  67979. }
  67980. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67981. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  67982. }
  67983. else {
  67984. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67985. }
  67986. // Instances
  67987. if (useInstances) {
  67988. defines.push("#define INSTANCES");
  67989. attribs.push("world0");
  67990. attribs.push("world1");
  67991. attribs.push("world2");
  67992. attribs.push("world3");
  67993. }
  67994. // Get correct effect
  67995. var join = defines.join("\n");
  67996. if (this._cachedDefines !== join) {
  67997. this._cachedDefines = join;
  67998. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  67999. }
  68000. return this._glowMapGenerationEffect.isReady();
  68001. };
  68002. /**
  68003. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  68004. */
  68005. HighlightLayer.prototype.render = function () {
  68006. var currentEffect = this._glowMapMergeEffect;
  68007. // Check
  68008. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  68009. return;
  68010. var engine = this._scene.getEngine();
  68011. this.onBeforeComposeObservable.notifyObservers(this);
  68012. // Render
  68013. engine.enableEffect(currentEffect);
  68014. engine.setState(false);
  68015. // Cache
  68016. var previousStencilBuffer = engine.getStencilBuffer();
  68017. var previousStencilFunction = engine.getStencilFunction();
  68018. var previousStencilMask = engine.getStencilMask();
  68019. var previousStencilOperationPass = engine.getStencilOperationPass();
  68020. var previousStencilOperationFail = engine.getStencilOperationFail();
  68021. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  68022. var previousAlphaMode = engine.getAlphaMode();
  68023. // Texture
  68024. currentEffect.setTexture("textureSampler", this._blurTexture);
  68025. // VBOs
  68026. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  68027. // Stencil operations
  68028. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  68029. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  68030. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  68031. // Draw order
  68032. engine.setAlphaMode(this._options.alphaBlendingMode);
  68033. engine.setStencilMask(0x00);
  68034. engine.setStencilBuffer(true);
  68035. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  68036. if (this.outerGlow) {
  68037. currentEffect.setFloat("offset", 0);
  68038. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  68039. engine.draw(true, 0, 6);
  68040. }
  68041. if (this.innerGlow) {
  68042. currentEffect.setFloat("offset", 1);
  68043. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  68044. engine.draw(true, 0, 6);
  68045. }
  68046. // Restore Cache
  68047. engine.setStencilFunction(previousStencilFunction);
  68048. engine.setStencilMask(previousStencilMask);
  68049. engine.setAlphaMode(previousAlphaMode);
  68050. engine.setStencilBuffer(previousStencilBuffer);
  68051. engine.setStencilOperationPass(previousStencilOperationPass);
  68052. engine.setStencilOperationFail(previousStencilOperationFail);
  68053. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  68054. engine._stencilState.reset();
  68055. this.onAfterComposeObservable.notifyObservers(this);
  68056. // Handle size changes.
  68057. var size = this._mainTexture.getSize();
  68058. this.setMainTextureSize();
  68059. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  68060. // Recreate RTT and post processes on size change.
  68061. this.onSizeChangedObservable.notifyObservers(this);
  68062. this.disposeTextureAndPostProcesses();
  68063. this.createTextureAndPostProcesses();
  68064. }
  68065. };
  68066. /**
  68067. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  68068. * @param mesh The mesh to exclude from the highlight layer
  68069. */
  68070. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  68071. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  68072. if (!meshExcluded) {
  68073. this._excludedMeshes[mesh.uniqueId] = {
  68074. mesh: mesh,
  68075. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  68076. mesh.getEngine().setStencilBuffer(false);
  68077. }),
  68078. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  68079. mesh.getEngine().setStencilBuffer(true);
  68080. }),
  68081. };
  68082. }
  68083. };
  68084. /**
  68085. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  68086. * @param mesh The mesh to highlight
  68087. */
  68088. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  68089. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  68090. if (meshExcluded) {
  68091. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  68092. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  68093. }
  68094. this._excludedMeshes[mesh.uniqueId] = undefined;
  68095. };
  68096. /**
  68097. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  68098. * @param mesh The mesh to highlight
  68099. * @param color The color of the highlight
  68100. * @param glowEmissiveOnly Extract the glow from the emissive texture
  68101. */
  68102. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  68103. var _this = this;
  68104. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  68105. var meshHighlight = this._meshes[mesh.uniqueId];
  68106. if (meshHighlight) {
  68107. meshHighlight.color = color;
  68108. }
  68109. else {
  68110. this._meshes[mesh.uniqueId] = {
  68111. mesh: mesh,
  68112. color: color,
  68113. // Lambda required for capture due to Observable this context
  68114. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  68115. if (_this._excludedMeshes[mesh.uniqueId]) {
  68116. _this.defaultStencilReference(mesh);
  68117. }
  68118. else {
  68119. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  68120. }
  68121. }),
  68122. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  68123. glowEmissiveOnly: glowEmissiveOnly
  68124. };
  68125. }
  68126. this._shouldRender = true;
  68127. };
  68128. /**
  68129. * Remove a mesh from the highlight layer in order to make it stop glowing.
  68130. * @param mesh The mesh to highlight
  68131. */
  68132. HighlightLayer.prototype.removeMesh = function (mesh) {
  68133. var meshHighlight = this._meshes[mesh.uniqueId];
  68134. if (meshHighlight) {
  68135. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  68136. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  68137. }
  68138. this._meshes[mesh.uniqueId] = undefined;
  68139. this._shouldRender = false;
  68140. for (var meshHighlightToCheck in this._meshes) {
  68141. if (meshHighlightToCheck) {
  68142. this._shouldRender = true;
  68143. break;
  68144. }
  68145. }
  68146. };
  68147. /**
  68148. * Returns true if the layer contains information to display, otherwise false.
  68149. */
  68150. HighlightLayer.prototype.shouldRender = function () {
  68151. return this.isEnabled && this._shouldRender;
  68152. };
  68153. /**
  68154. * Sets the main texture desired size which is the closest power of two
  68155. * of the engine canvas size.
  68156. */
  68157. HighlightLayer.prototype.setMainTextureSize = function () {
  68158. if (this._options.mainTextureFixedSize) {
  68159. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  68160. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  68161. }
  68162. else {
  68163. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  68164. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  68165. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  68166. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  68167. }
  68168. };
  68169. /**
  68170. * Force the stencil to the normal expected value for none glowing parts
  68171. */
  68172. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  68173. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  68174. };
  68175. /**
  68176. * Dispose only the render target textures and post process.
  68177. */
  68178. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  68179. this._blurTexture.dispose();
  68180. this._mainTexture.dispose();
  68181. this._downSamplePostprocess.dispose();
  68182. this._horizontalBlurPostprocess.dispose();
  68183. this._verticalBlurPostprocess.dispose();
  68184. };
  68185. /**
  68186. * Dispose the highlight layer and free resources.
  68187. */
  68188. HighlightLayer.prototype.dispose = function () {
  68189. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68190. if (vertexBuffer) {
  68191. vertexBuffer.dispose();
  68192. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  68193. }
  68194. if (this._indexBuffer) {
  68195. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  68196. this._indexBuffer = null;
  68197. }
  68198. // Clean textures and post processes
  68199. this.disposeTextureAndPostProcesses();
  68200. // Clean mesh references
  68201. for (var id in this._meshes) {
  68202. var meshHighlight = this._meshes[id];
  68203. if (meshHighlight && meshHighlight.mesh) {
  68204. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  68205. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  68206. }
  68207. }
  68208. this._meshes = null;
  68209. for (var id in this._excludedMeshes) {
  68210. var meshHighlight = this._excludedMeshes[id];
  68211. if (meshHighlight) {
  68212. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  68213. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  68214. }
  68215. }
  68216. this._excludedMeshes = null;
  68217. // Remove from scene
  68218. var index = this._scene.highlightLayers.indexOf(this, 0);
  68219. if (index > -1) {
  68220. this._scene.highlightLayers.splice(index, 1);
  68221. }
  68222. // Callback
  68223. this.onDisposeObservable.notifyObservers(this);
  68224. this.onDisposeObservable.clear();
  68225. this.onBeforeRenderMainTextureObservable.clear();
  68226. this.onBeforeBlurObservable.clear();
  68227. this.onBeforeComposeObservable.clear();
  68228. this.onAfterComposeObservable.clear();
  68229. this.onSizeChangedObservable.clear();
  68230. };
  68231. /**
  68232. * The neutral color used during the preparation of the glow effect.
  68233. * This is black by default as the blend operation is a blend operation.
  68234. */
  68235. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  68236. /**
  68237. * Stencil value used for glowing meshes.
  68238. */
  68239. HighlightLayer.glowingMeshStencilReference = 0x02;
  68240. /**
  68241. * Stencil value used for the other meshes in the scene.
  68242. */
  68243. HighlightLayer.normalMeshStencilReference = 0x01;
  68244. return HighlightLayer;
  68245. }());
  68246. BABYLON.HighlightLayer = HighlightLayer;
  68247. })(BABYLON || (BABYLON = {}));
  68248. //# sourceMappingURL=babylon.highlightlayer.js.map
  68249. var BABYLON;
  68250. (function (BABYLON) {
  68251. var MeshAssetTask = (function () {
  68252. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  68253. this.name = name;
  68254. this.meshesNames = meshesNames;
  68255. this.rootUrl = rootUrl;
  68256. this.sceneFilename = sceneFilename;
  68257. this.isCompleted = false;
  68258. }
  68259. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  68260. var _this = this;
  68261. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  68262. _this.loadedMeshes = meshes;
  68263. _this.loadedParticleSystems = particleSystems;
  68264. _this.loadedSkeletons = skeletons;
  68265. _this.isCompleted = true;
  68266. if (_this.onSuccess) {
  68267. _this.onSuccess(_this);
  68268. }
  68269. onSuccess();
  68270. }, null, function () {
  68271. if (_this.onError) {
  68272. _this.onError(_this);
  68273. }
  68274. onError();
  68275. });
  68276. };
  68277. return MeshAssetTask;
  68278. }());
  68279. BABYLON.MeshAssetTask = MeshAssetTask;
  68280. var TextFileAssetTask = (function () {
  68281. function TextFileAssetTask(name, url) {
  68282. this.name = name;
  68283. this.url = url;
  68284. this.isCompleted = false;
  68285. }
  68286. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  68287. var _this = this;
  68288. BABYLON.Tools.LoadFile(this.url, function (data) {
  68289. _this.text = data;
  68290. _this.isCompleted = true;
  68291. if (_this.onSuccess) {
  68292. _this.onSuccess(_this);
  68293. }
  68294. onSuccess();
  68295. }, null, scene.database, false, function () {
  68296. if (_this.onError) {
  68297. _this.onError(_this);
  68298. }
  68299. onError();
  68300. });
  68301. };
  68302. return TextFileAssetTask;
  68303. }());
  68304. BABYLON.TextFileAssetTask = TextFileAssetTask;
  68305. var BinaryFileAssetTask = (function () {
  68306. function BinaryFileAssetTask(name, url) {
  68307. this.name = name;
  68308. this.url = url;
  68309. this.isCompleted = false;
  68310. }
  68311. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  68312. var _this = this;
  68313. BABYLON.Tools.LoadFile(this.url, function (data) {
  68314. _this.data = data;
  68315. _this.isCompleted = true;
  68316. if (_this.onSuccess) {
  68317. _this.onSuccess(_this);
  68318. }
  68319. onSuccess();
  68320. }, null, scene.database, true, function () {
  68321. if (_this.onError) {
  68322. _this.onError(_this);
  68323. }
  68324. onError();
  68325. });
  68326. };
  68327. return BinaryFileAssetTask;
  68328. }());
  68329. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  68330. var ImageAssetTask = (function () {
  68331. function ImageAssetTask(name, url) {
  68332. this.name = name;
  68333. this.url = url;
  68334. this.isCompleted = false;
  68335. }
  68336. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  68337. var _this = this;
  68338. var img = new Image();
  68339. BABYLON.Tools.SetCorsBehavior(this.url, img);
  68340. img.onload = function () {
  68341. _this.image = img;
  68342. _this.isCompleted = true;
  68343. if (_this.onSuccess) {
  68344. _this.onSuccess(_this);
  68345. }
  68346. onSuccess();
  68347. };
  68348. img.onerror = function () {
  68349. if (_this.onError) {
  68350. _this.onError(_this);
  68351. }
  68352. onError();
  68353. };
  68354. img.src = this.url;
  68355. };
  68356. return ImageAssetTask;
  68357. }());
  68358. BABYLON.ImageAssetTask = ImageAssetTask;
  68359. var TextureAssetTask = (function () {
  68360. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  68361. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68362. this.name = name;
  68363. this.url = url;
  68364. this.noMipmap = noMipmap;
  68365. this.invertY = invertY;
  68366. this.samplingMode = samplingMode;
  68367. this.isCompleted = false;
  68368. }
  68369. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  68370. var _this = this;
  68371. var onload = function () {
  68372. _this.isCompleted = true;
  68373. if (_this.onSuccess) {
  68374. _this.onSuccess(_this);
  68375. }
  68376. onSuccess();
  68377. };
  68378. var onerror = function () {
  68379. if (_this.onError) {
  68380. _this.onError(_this);
  68381. }
  68382. onError();
  68383. };
  68384. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  68385. };
  68386. return TextureAssetTask;
  68387. }());
  68388. BABYLON.TextureAssetTask = TextureAssetTask;
  68389. var CubeTextureAssetTask = (function () {
  68390. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  68391. this.name = name;
  68392. this.url = url;
  68393. this.extensions = extensions;
  68394. this.noMipmap = noMipmap;
  68395. this.files = files;
  68396. this.isCompleted = false;
  68397. }
  68398. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  68399. var _this = this;
  68400. var onload = function () {
  68401. _this.isCompleted = true;
  68402. if (_this.onSuccess) {
  68403. _this.onSuccess(_this);
  68404. }
  68405. onSuccess();
  68406. };
  68407. var onerror = function () {
  68408. if (_this.onError) {
  68409. _this.onError(_this);
  68410. }
  68411. onError();
  68412. };
  68413. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  68414. };
  68415. return CubeTextureAssetTask;
  68416. }());
  68417. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  68418. var HDRCubeTextureAssetTask = (function () {
  68419. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  68420. if (noMipmap === void 0) { noMipmap = false; }
  68421. if (generateHarmonics === void 0) { generateHarmonics = true; }
  68422. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  68423. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  68424. this.name = name;
  68425. this.url = url;
  68426. this.size = size;
  68427. this.noMipmap = noMipmap;
  68428. this.generateHarmonics = generateHarmonics;
  68429. this.useInGammaSpace = useInGammaSpace;
  68430. this.usePMREMGenerator = usePMREMGenerator;
  68431. this.isCompleted = false;
  68432. }
  68433. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  68434. var _this = this;
  68435. var onload = function () {
  68436. _this.isCompleted = true;
  68437. if (_this.onSuccess) {
  68438. _this.onSuccess(_this);
  68439. }
  68440. onSuccess();
  68441. };
  68442. var onerror = function () {
  68443. if (_this.onError) {
  68444. _this.onError(_this);
  68445. }
  68446. onError();
  68447. };
  68448. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  68449. };
  68450. return HDRCubeTextureAssetTask;
  68451. }());
  68452. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  68453. var AssetsManager = (function () {
  68454. function AssetsManager(scene) {
  68455. this.tasks = new Array();
  68456. this.waitingTasksCount = 0;
  68457. this.useDefaultLoadingScreen = true;
  68458. this._scene = scene;
  68459. }
  68460. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  68461. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  68462. this.tasks.push(task);
  68463. return task;
  68464. };
  68465. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  68466. var task = new TextFileAssetTask(taskName, url);
  68467. this.tasks.push(task);
  68468. return task;
  68469. };
  68470. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  68471. var task = new BinaryFileAssetTask(taskName, url);
  68472. this.tasks.push(task);
  68473. return task;
  68474. };
  68475. AssetsManager.prototype.addImageTask = function (taskName, url) {
  68476. var task = new ImageAssetTask(taskName, url);
  68477. this.tasks.push(task);
  68478. return task;
  68479. };
  68480. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  68481. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68482. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  68483. this.tasks.push(task);
  68484. return task;
  68485. };
  68486. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  68487. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  68488. this.tasks.push(task);
  68489. return task;
  68490. };
  68491. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  68492. if (noMipmap === void 0) { noMipmap = false; }
  68493. if (generateHarmonics === void 0) { generateHarmonics = true; }
  68494. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  68495. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  68496. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  68497. this.tasks.push(task);
  68498. return task;
  68499. };
  68500. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  68501. this.waitingTasksCount--;
  68502. if (this.waitingTasksCount === 0) {
  68503. if (this.onFinish) {
  68504. this.onFinish(this.tasks);
  68505. }
  68506. this._scene.getEngine().hideLoadingUI();
  68507. }
  68508. };
  68509. AssetsManager.prototype._runTask = function (task) {
  68510. var _this = this;
  68511. task.run(this._scene, function () {
  68512. if (_this.onTaskSuccess) {
  68513. _this.onTaskSuccess(task);
  68514. }
  68515. _this._decreaseWaitingTasksCount();
  68516. }, function () {
  68517. if (_this.onTaskError) {
  68518. _this.onTaskError(task);
  68519. }
  68520. _this._decreaseWaitingTasksCount();
  68521. });
  68522. };
  68523. AssetsManager.prototype.reset = function () {
  68524. this.tasks = new Array();
  68525. return this;
  68526. };
  68527. AssetsManager.prototype.load = function () {
  68528. this.waitingTasksCount = this.tasks.length;
  68529. if (this.waitingTasksCount === 0) {
  68530. if (this.onFinish) {
  68531. this.onFinish(this.tasks);
  68532. }
  68533. return this;
  68534. }
  68535. if (this.useDefaultLoadingScreen) {
  68536. this._scene.getEngine().displayLoadingUI();
  68537. }
  68538. for (var index = 0; index < this.tasks.length; index++) {
  68539. var task = this.tasks[index];
  68540. this._runTask(task);
  68541. }
  68542. return this;
  68543. };
  68544. return AssetsManager;
  68545. }());
  68546. BABYLON.AssetsManager = AssetsManager;
  68547. })(BABYLON || (BABYLON = {}));
  68548. //# sourceMappingURL=babylon.assetsManager.js.map
  68549. var BABYLON;
  68550. (function (BABYLON) {
  68551. var MapTexture = (function (_super) {
  68552. __extends(MapTexture, _super);
  68553. function MapTexture(name, scene, size, samplingMode, useMipMap, margin) {
  68554. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68555. if (useMipMap === void 0) { useMipMap = false; }
  68556. if (margin === void 0) { margin = 0; }
  68557. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  68558. _this.name = name;
  68559. _this._size = size;
  68560. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68561. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68562. // Create the rectPackMap that will allocate portion of the texture
  68563. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height), margin);
  68564. // Create the texture that will store the content
  68565. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  68566. return _this;
  68567. }
  68568. /**
  68569. * Allocate a rectangle of a given size in the texture map
  68570. * @param size the size of the rectangle to allocation
  68571. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  68572. */
  68573. MapTexture.prototype.allocateRect = function (size) {
  68574. return this._rectPackingMap.addRect(size);
  68575. };
  68576. /**
  68577. * Free a given rectangle from the texture map
  68578. * @param rectInfo the instance corresponding to the rect to free.
  68579. */
  68580. MapTexture.prototype.freeRect = function (rectInfo) {
  68581. if (rectInfo) {
  68582. rectInfo.freeContent();
  68583. }
  68584. };
  68585. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  68586. /**
  68587. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  68588. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  68589. * @returns {}
  68590. */
  68591. get: function () {
  68592. return this._rectPackingMap.freeSpace;
  68593. },
  68594. enumerable: true,
  68595. configurable: true
  68596. });
  68597. /**
  68598. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  68599. * 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.
  68600. * Don't forget to call unbindTexture when you're done rendering
  68601. * @param rect the zone to render to
  68602. * @param clear true to clear the portion's color/depth data
  68603. */
  68604. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  68605. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  68606. };
  68607. /**
  68608. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  68609. * 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.
  68610. * Don't forget to call unbindTexture when you're done rendering
  68611. * @param pos the position into the texture
  68612. * @param size the portion to fit the clip space to
  68613. * @param clear true to clear the portion's color/depth data
  68614. */
  68615. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  68616. var engine = this.getScene().getEngine();
  68617. engine.bindFramebuffer(this._texture);
  68618. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  68619. if (clear) {
  68620. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  68621. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  68622. }
  68623. };
  68624. /**
  68625. * Unbind the texture map from the rendering engine.
  68626. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  68627. * @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.
  68628. */
  68629. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  68630. // Dump ?
  68631. if (dumpForDebug) {
  68632. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  68633. }
  68634. var engine = this.getScene().getEngine();
  68635. if (this._replacedViewport) {
  68636. engine.setViewport(this._replacedViewport);
  68637. this._replacedViewport = null;
  68638. }
  68639. engine.unBindFramebuffer(this._texture);
  68640. };
  68641. Object.defineProperty(MapTexture.prototype, "canRescale", {
  68642. get: function () {
  68643. return false;
  68644. },
  68645. enumerable: true,
  68646. configurable: true
  68647. });
  68648. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  68649. // Anyway, there's not much point to use this method for this kind of texture I guess
  68650. MapTexture.prototype.clone = function () {
  68651. return null;
  68652. };
  68653. return MapTexture;
  68654. }(BABYLON.Texture));
  68655. BABYLON.MapTexture = MapTexture;
  68656. })(BABYLON || (BABYLON = {}));
  68657. //# sourceMappingURL=babylon.mapTexture.js.map
  68658. var BABYLON;
  68659. (function (BABYLON) {
  68660. /**
  68661. * This class describe a rectangle that were added to the map.
  68662. * You have access to its coordinates either in pixel or normalized (UV)
  68663. */
  68664. var PackedRect = (function () {
  68665. function PackedRect(root, parent, pos, size) {
  68666. this._pos = pos;
  68667. this._size = size;
  68668. this._root = root;
  68669. this._parent = parent;
  68670. this._contentSize = null;
  68671. this._bottomNode = null;
  68672. this._leftNode = null;
  68673. this._initialSize = null;
  68674. this._rightNode = null;
  68675. }
  68676. Object.defineProperty(PackedRect.prototype, "pos", {
  68677. /**
  68678. * @returns the position of this node into the map
  68679. */
  68680. get: function () {
  68681. return this._pos;
  68682. },
  68683. enumerable: true,
  68684. configurable: true
  68685. });
  68686. Object.defineProperty(PackedRect.prototype, "contentSize", {
  68687. /**
  68688. * @returns the size of the rectangle this node handles
  68689. */
  68690. get: function () {
  68691. return this._contentSize;
  68692. },
  68693. enumerable: true,
  68694. configurable: true
  68695. });
  68696. /**
  68697. * Retrieve the inner position (considering the margin) and stores it into the res object
  68698. * @param res must be a valid Vector2 that will contain the inner position after this call
  68699. */
  68700. PackedRect.prototype.getInnerPosToRef = function (res) {
  68701. var m = this._root._margin;
  68702. res.x = this._pos.x + m;
  68703. res.y = this._pos.y + m;
  68704. };
  68705. /**
  68706. * Retrieve the inner size (considering the margin) and stores it into the res object
  68707. * @param res must be a valid Size that will contain the inner size after this call
  68708. */
  68709. PackedRect.prototype.getInnerSizeToRef = function (res) {
  68710. var m = this._root._margin;
  68711. res.width = this._contentSize.width - (m * 2);
  68712. res.height = this._contentSize.height - (m * 2);
  68713. };
  68714. Object.defineProperty(PackedRect.prototype, "UVs", {
  68715. /**
  68716. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  68717. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  68718. */
  68719. get: function () {
  68720. if (!this._contentSize) {
  68721. throw new Error("Can't compute UVs for this object because it's nor allocated");
  68722. }
  68723. return this.getUVsForCustomSize(this._contentSize);
  68724. },
  68725. enumerable: true,
  68726. configurable: true
  68727. });
  68728. /**
  68729. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations)
  68730. * and then using only a part of the PackRect.
  68731. * This method will return the UVs for this part by given the custom size of what you really use
  68732. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  68733. */
  68734. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  68735. var mainWidth = this._root._size.width;
  68736. var mainHeight = this._root._size.height;
  68737. var margin = this._root._margin;
  68738. var topLeft = new BABYLON.Vector2((this._pos.x + margin) / mainWidth, (this._pos.y + margin) / mainHeight);
  68739. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width + margin - 1) / mainWidth, (this._pos.y + customSize.height + margin - 1) / mainHeight);
  68740. var uvs = new Array();
  68741. uvs.push(topLeft);
  68742. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  68743. uvs.push(rightBottom);
  68744. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  68745. return uvs;
  68746. };
  68747. /**
  68748. * Free this rectangle from the map.
  68749. * Call this method when you no longer need the rectangle to be in the map.
  68750. */
  68751. PackedRect.prototype.freeContent = function () {
  68752. if (!this.contentSize) {
  68753. return;
  68754. }
  68755. this._contentSize = null;
  68756. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  68757. this.attemptDefrag();
  68758. };
  68759. Object.defineProperty(PackedRect.prototype, "isUsed", {
  68760. get: function () {
  68761. return this._contentSize != null || this._leftNode != null;
  68762. },
  68763. enumerable: true,
  68764. configurable: true
  68765. });
  68766. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  68767. var node = this.findNode(contentSize);
  68768. // Not enough space...
  68769. if (!node) {
  68770. return null;
  68771. }
  68772. node.splitNode(contentSize);
  68773. return node;
  68774. };
  68775. PackedRect.prototype.findNode = function (size) {
  68776. var resNode = null;
  68777. var margin = this._root._margin * 2;
  68778. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  68779. if (this.isUsed) {
  68780. if (this._leftNode) {
  68781. resNode = this._leftNode.findNode(size);
  68782. }
  68783. if (!resNode && this._rightNode) {
  68784. resNode = this._rightNode.findNode(size);
  68785. }
  68786. if (!resNode && this._bottomNode) {
  68787. resNode = this._bottomNode.findNode(size);
  68788. }
  68789. }
  68790. else if (this._initialSize) {
  68791. if (((size.width + margin) <= this._initialSize.width) && ((size.height + margin) <= this._initialSize.height)) {
  68792. resNode = this;
  68793. }
  68794. else {
  68795. return null;
  68796. }
  68797. }
  68798. else if (((size.width + margin) <= this._size.width) && ((size.height + margin) <= this._size.height)) {
  68799. resNode = this;
  68800. }
  68801. return resNode;
  68802. };
  68803. PackedRect.prototype.splitNode = function (contentSize) {
  68804. var cs = PackedRect.TpsSize;
  68805. var margin = this._root._margin * 2;
  68806. cs.copyFrom(contentSize);
  68807. cs.width += margin;
  68808. cs.height += margin;
  68809. // 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)
  68810. if (!this._contentSize && this._initialSize) {
  68811. this._contentSize = cs.clone();
  68812. 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));
  68813. return this._leftNode.splitNode(contentSize);
  68814. }
  68815. else {
  68816. this._contentSize = cs.clone();
  68817. this._initialSize = cs.clone();
  68818. if (cs.width !== this._size.width) {
  68819. 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));
  68820. }
  68821. if (cs.height !== this._size.height) {
  68822. 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));
  68823. }
  68824. return this;
  68825. }
  68826. };
  68827. PackedRect.prototype.attemptDefrag = function () {
  68828. if (!this.isUsed && this.isRecursiveFree) {
  68829. this.clearNode();
  68830. if (this._parent) {
  68831. this._parent.attemptDefrag();
  68832. }
  68833. }
  68834. };
  68835. PackedRect.prototype.clearNode = function () {
  68836. this._initialSize = null;
  68837. this._rightNode = null;
  68838. this._bottomNode = null;
  68839. };
  68840. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  68841. get: function () {
  68842. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  68843. },
  68844. enumerable: true,
  68845. configurable: true
  68846. });
  68847. PackedRect.prototype.evalFreeSize = function (size) {
  68848. var levelSize = 0;
  68849. if (!this.isUsed) {
  68850. var margin = this._root._margin;
  68851. var is = this._initialSize;
  68852. if (is) {
  68853. levelSize = is.surface - (is.width * margin) - (is.height * margin);
  68854. }
  68855. else {
  68856. var size_1 = this._size;
  68857. levelSize = size_1.surface - (size_1.width * margin) - (size_1.height * margin);
  68858. }
  68859. }
  68860. if (this._rightNode) {
  68861. levelSize += this._rightNode.evalFreeSize(0);
  68862. }
  68863. if (this._bottomNode) {
  68864. levelSize += this._bottomNode.evalFreeSize(0);
  68865. }
  68866. return levelSize + size;
  68867. };
  68868. PackedRect.TpsSize = BABYLON.Size.Zero();
  68869. return PackedRect;
  68870. }());
  68871. BABYLON.PackedRect = PackedRect;
  68872. /**
  68873. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  68874. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  68875. * 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.
  68876. * In case you need a margin around the allocated rect, specify the amount in the margin argument during construction.
  68877. * In such case you will have to rely on innerPositionToRef and innerSizeToRef calls to get the proper size
  68878. */
  68879. var RectPackingMap = (function (_super) {
  68880. __extends(RectPackingMap, _super);
  68881. /**
  68882. * Create an instance of the object with a dimension using the given size
  68883. * @param size The dimension of the rectangle that will contain all the sub ones.
  68884. * @param margin The margin (empty space) created (in pixels) around the allocated Rectangles
  68885. */
  68886. function RectPackingMap(size, margin) {
  68887. if (margin === void 0) { margin = 0; }
  68888. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  68889. _this._margin = margin;
  68890. _this._root = _this;
  68891. return _this;
  68892. }
  68893. /**
  68894. * Add a rectangle, finding the best location to store it into the map
  68895. * @param size the dimension of the rectangle to store
  68896. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  68897. */
  68898. RectPackingMap.prototype.addRect = function (size) {
  68899. var node = this.findAndSplitNode(size);
  68900. return node;
  68901. };
  68902. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  68903. /**
  68904. * Return the current space free normalized between [0;1]
  68905. * @returns {}
  68906. */
  68907. get: function () {
  68908. var freeSize = 0;
  68909. freeSize = this.evalFreeSize(freeSize);
  68910. return freeSize / (this._size.width * this._size.height);
  68911. },
  68912. enumerable: true,
  68913. configurable: true
  68914. });
  68915. return RectPackingMap;
  68916. }(PackedRect));
  68917. BABYLON.RectPackingMap = RectPackingMap;
  68918. })(BABYLON || (BABYLON = {}));
  68919. //# sourceMappingURL=babylon.rectPackingMap.js.map
  68920. var BABYLON;
  68921. (function (BABYLON) {
  68922. /**
  68923. * This groups together the common properties used for image processing either in direct forward pass
  68924. * or through post processing effect depending on the use of the image processing pipeline in your scene
  68925. * or not.
  68926. */
  68927. var ImageProcessingConfiguration = (function () {
  68928. function ImageProcessingConfiguration() {
  68929. /**
  68930. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  68931. */
  68932. this.colorCurves = new BABYLON.ColorCurves();
  68933. this._colorCurvesEnabled = false;
  68934. this._colorGradingEnabled = false;
  68935. this._colorGradingWithGreenDepth = false;
  68936. this._colorGradingBGR = false;
  68937. this._exposure = 1.0;
  68938. this._toneMappingEnabled = false;
  68939. this._contrast = 1.0;
  68940. /**
  68941. * Vignette stretch size.
  68942. */
  68943. this.vignetteStretch = 0;
  68944. /**
  68945. * Vignette centre X Offset.
  68946. */
  68947. this.vignetteCentreX = 0;
  68948. /**
  68949. * Vignette centre Y Offset.
  68950. */
  68951. this.vignetteCentreY = 0;
  68952. /**
  68953. * Vignette weight or intensity of the vignette effect.
  68954. */
  68955. this.vignetteWeight = 1.5;
  68956. /**
  68957. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  68958. * if vignetteEnabled is set to true.
  68959. */
  68960. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  68961. /**
  68962. * Camera field of view used by the Vignette effect.
  68963. */
  68964. this.vignetteCameraFov = 0.5;
  68965. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  68966. this._vignetteEnabled = false;
  68967. this._applyByPostProcess = false;
  68968. /**
  68969. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  68970. * @type {BABYLON.Observable}
  68971. */
  68972. this.onUpdateParameters = new BABYLON.Observable();
  68973. }
  68974. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  68975. /**
  68976. * Gets wether the color curves effect is enabled.
  68977. */
  68978. get: function () {
  68979. return this._colorCurvesEnabled;
  68980. },
  68981. /**
  68982. * Sets wether the color curves effect is enabled.
  68983. */
  68984. set: function (value) {
  68985. if (this._colorCurvesEnabled === value) {
  68986. return;
  68987. }
  68988. this._colorCurvesEnabled = value;
  68989. this._updateParameters();
  68990. },
  68991. enumerable: true,
  68992. configurable: true
  68993. });
  68994. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  68995. /**
  68996. * Gets wether the color grading effect is enabled.
  68997. */
  68998. get: function () {
  68999. return this._colorGradingEnabled;
  69000. },
  69001. /**
  69002. * Sets wether the color grading effect is enabled.
  69003. */
  69004. set: function (value) {
  69005. if (this._colorGradingEnabled === value) {
  69006. return;
  69007. }
  69008. this._colorGradingEnabled = value;
  69009. this._updateParameters();
  69010. },
  69011. enumerable: true,
  69012. configurable: true
  69013. });
  69014. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  69015. /**
  69016. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  69017. */
  69018. get: function () {
  69019. return this._colorGradingWithGreenDepth;
  69020. },
  69021. /**
  69022. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  69023. */
  69024. set: function (value) {
  69025. if (this._colorGradingWithGreenDepth === value) {
  69026. return;
  69027. }
  69028. this._colorGradingWithGreenDepth = value;
  69029. this._updateParameters();
  69030. },
  69031. enumerable: true,
  69032. configurable: true
  69033. });
  69034. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  69035. /**
  69036. * Gets wether the color grading texture contains BGR values.
  69037. */
  69038. get: function () {
  69039. return this._colorGradingBGR;
  69040. },
  69041. /**
  69042. * Sets wether the color grading texture contains BGR values.
  69043. */
  69044. set: function (value) {
  69045. if (this._colorGradingBGR === value) {
  69046. return;
  69047. }
  69048. this._colorGradingBGR = value;
  69049. this._updateParameters();
  69050. },
  69051. enumerable: true,
  69052. configurable: true
  69053. });
  69054. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  69055. /**
  69056. * Gets the Exposure used in the effect.
  69057. */
  69058. get: function () {
  69059. return this._exposure;
  69060. },
  69061. /**
  69062. * Sets the Exposure used in the effect.
  69063. */
  69064. set: function (value) {
  69065. if (this._exposure === value) {
  69066. return;
  69067. }
  69068. this._exposure = value;
  69069. this._updateParameters();
  69070. },
  69071. enumerable: true,
  69072. configurable: true
  69073. });
  69074. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  69075. /**
  69076. * Gets wether the tone mapping effect is enabled.
  69077. */
  69078. get: function () {
  69079. return this._toneMappingEnabled;
  69080. },
  69081. /**
  69082. * Sets wether the tone mapping effect is enabled.
  69083. */
  69084. set: function (value) {
  69085. if (this._toneMappingEnabled === value) {
  69086. return;
  69087. }
  69088. this._toneMappingEnabled = value;
  69089. this._updateParameters();
  69090. },
  69091. enumerable: true,
  69092. configurable: true
  69093. });
  69094. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  69095. /**
  69096. * Gets the contrast used in the effect.
  69097. */
  69098. get: function () {
  69099. return this._contrast;
  69100. },
  69101. /**
  69102. * Sets the contrast used in the effect.
  69103. */
  69104. set: function (value) {
  69105. if (this._contrast === value) {
  69106. return;
  69107. }
  69108. this._contrast = value;
  69109. this._updateParameters();
  69110. },
  69111. enumerable: true,
  69112. configurable: true
  69113. });
  69114. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  69115. /**
  69116. * Gets the vignette blend mode allowing different kind of effect.
  69117. */
  69118. get: function () {
  69119. return this._vignetteBlendMode;
  69120. },
  69121. /**
  69122. * Sets the vignette blend mode allowing different kind of effect.
  69123. */
  69124. set: function (value) {
  69125. if (this._vignetteBlendMode === value) {
  69126. return;
  69127. }
  69128. this._vignetteBlendMode = value;
  69129. this._updateParameters();
  69130. },
  69131. enumerable: true,
  69132. configurable: true
  69133. });
  69134. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  69135. /**
  69136. * Gets wether the vignette effect is enabled.
  69137. */
  69138. get: function () {
  69139. return this._vignetteEnabled;
  69140. },
  69141. /**
  69142. * Sets wether the vignette effect is enabled.
  69143. */
  69144. set: function (value) {
  69145. if (this._vignetteEnabled === value) {
  69146. return;
  69147. }
  69148. this._vignetteEnabled = value;
  69149. this._updateParameters();
  69150. },
  69151. enumerable: true,
  69152. configurable: true
  69153. });
  69154. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  69155. /**
  69156. * Gets wether the image processing is applied through a post process or not.
  69157. */
  69158. get: function () {
  69159. return this._applyByPostProcess;
  69160. },
  69161. /**
  69162. * Sets wether the image processing is applied through a post process or not.
  69163. */
  69164. set: function (value) {
  69165. if (this._applyByPostProcess === value) {
  69166. return;
  69167. }
  69168. this._applyByPostProcess = value;
  69169. this._updateParameters();
  69170. },
  69171. enumerable: true,
  69172. configurable: true
  69173. });
  69174. /**
  69175. * Method called each time the image processing information changes requires to recompile the effect.
  69176. */
  69177. ImageProcessingConfiguration.prototype._updateParameters = function () {
  69178. this.onUpdateParameters.notifyObservers(this);
  69179. };
  69180. ImageProcessingConfiguration.prototype.getClassName = function () {
  69181. return "ImageProcessingConfiguration";
  69182. };
  69183. /**
  69184. * Prepare the list of uniforms associated with the Image Processing effects.
  69185. * @param uniformsList The list of uniforms used in the effect
  69186. * @param defines the list of defines currently in use
  69187. */
  69188. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  69189. if (defines.EXPOSURE) {
  69190. uniforms.push("exposureLinear");
  69191. }
  69192. if (defines.CONTRAST) {
  69193. uniforms.push("contrast");
  69194. }
  69195. if (defines.COLORGRADING) {
  69196. uniforms.push("colorTransformSettings");
  69197. }
  69198. if (defines.VIGNETTE) {
  69199. uniforms.push("vInverseScreenSize");
  69200. uniforms.push("vignetteSettings1");
  69201. uniforms.push("vignetteSettings2");
  69202. }
  69203. if (defines.COLORCURVES) {
  69204. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  69205. }
  69206. };
  69207. /**
  69208. * Prepare the list of samplers associated with the Image Processing effects.
  69209. * @param uniformsList The list of uniforms used in the effect
  69210. * @param defines the list of defines currently in use
  69211. */
  69212. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  69213. if (defines.COLORGRADING) {
  69214. samplersList.push("txColorTransform");
  69215. }
  69216. };
  69217. /**
  69218. * Prepare the list of defines associated to the shader.
  69219. * @param defines the list of defines to complete
  69220. */
  69221. ImageProcessingConfiguration.prototype.prepareDefines = function (defines) {
  69222. defines.VIGNETTE = this.vignetteEnabled;
  69223. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  69224. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  69225. defines.TONEMAPPING = this.toneMappingEnabled;
  69226. defines.CONTRAST = (this.contrast !== 1.0);
  69227. defines.EXPOSURE = (this.exposure !== 1.0);
  69228. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  69229. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  69230. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  69231. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  69232. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  69233. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  69234. };
  69235. /**
  69236. * Returns true if all the image processing information are ready.
  69237. */
  69238. ImageProcessingConfiguration.prototype.isReady = function () {
  69239. // Color Grading texure can not be none blocking.
  69240. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  69241. };
  69242. /**
  69243. * Binds the image processing to the shader.
  69244. * @param effect The effect to bind to
  69245. */
  69246. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  69247. if (aspectRatio === void 0) { aspectRatio = 1; }
  69248. // Color Curves
  69249. if (this._colorCurvesEnabled) {
  69250. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  69251. }
  69252. // Vignette
  69253. if (this._vignetteEnabled) {
  69254. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  69255. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  69256. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  69257. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  69258. var vignetteScaleX = vignetteScaleY * aspectRatio;
  69259. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  69260. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  69261. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  69262. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  69263. var vignettePower = -2.0 * this.vignetteWeight;
  69264. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  69265. }
  69266. // Exposure
  69267. effect.setFloat("exposureLinear", this.exposure);
  69268. // Contrast
  69269. effect.setFloat("contrast", this.contrast);
  69270. // Color transform settings
  69271. if (this.colorGradingTexture) {
  69272. effect.setTexture("txColorTransform", this.colorGradingTexture);
  69273. var textureSize = this.colorGradingTexture.getSize().height;
  69274. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  69275. 0.5 / textureSize, // textureOffset
  69276. textureSize, // textureSize
  69277. this.colorGradingTexture.level // weight
  69278. );
  69279. }
  69280. };
  69281. /**
  69282. * Clones the current image processing instance.
  69283. * @return The cloned image processing
  69284. */
  69285. ImageProcessingConfiguration.prototype.clone = function () {
  69286. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  69287. };
  69288. /**
  69289. * Serializes the current image processing instance to a json representation.
  69290. * @return a JSON representation
  69291. */
  69292. ImageProcessingConfiguration.prototype.serialize = function () {
  69293. return BABYLON.SerializationHelper.Serialize(this);
  69294. };
  69295. /**
  69296. * Parses the image processing from a json representation.
  69297. * @param source the JSON source to parse
  69298. * @return The parsed image processing
  69299. */
  69300. ImageProcessingConfiguration.Parse = function (source) {
  69301. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  69302. };
  69303. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  69304. /**
  69305. * Used to apply the vignette as a mix with the pixel color.
  69306. */
  69307. get: function () {
  69308. return this._VIGNETTEMODE_MULTIPLY;
  69309. },
  69310. enumerable: true,
  69311. configurable: true
  69312. });
  69313. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  69314. /**
  69315. * Used to apply the vignette as a replacement of the pixel color.
  69316. */
  69317. get: function () {
  69318. return this._VIGNETTEMODE_OPAQUE;
  69319. },
  69320. enumerable: true,
  69321. configurable: true
  69322. });
  69323. // Static constants associated to the image processing.
  69324. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  69325. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  69326. __decorate([
  69327. BABYLON.serializeAsColorCurves()
  69328. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  69329. __decorate([
  69330. BABYLON.serialize()
  69331. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  69332. __decorate([
  69333. BABYLON.serializeAsTexture()
  69334. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  69335. __decorate([
  69336. BABYLON.serialize()
  69337. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  69338. __decorate([
  69339. BABYLON.serialize()
  69340. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  69341. __decorate([
  69342. BABYLON.serialize()
  69343. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  69344. __decorate([
  69345. BABYLON.serialize()
  69346. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  69347. __decorate([
  69348. BABYLON.serialize()
  69349. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  69350. __decorate([
  69351. BABYLON.serialize()
  69352. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  69353. __decorate([
  69354. BABYLON.serialize()
  69355. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  69356. __decorate([
  69357. BABYLON.serialize()
  69358. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  69359. __decorate([
  69360. BABYLON.serialize()
  69361. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  69362. __decorate([
  69363. BABYLON.serialize()
  69364. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  69365. __decorate([
  69366. BABYLON.serializeAsColor4()
  69367. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  69368. __decorate([
  69369. BABYLON.serialize()
  69370. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  69371. __decorate([
  69372. BABYLON.serialize()
  69373. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  69374. __decorate([
  69375. BABYLON.serialize()
  69376. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  69377. __decorate([
  69378. BABYLON.serialize()
  69379. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  69380. return ImageProcessingConfiguration;
  69381. }());
  69382. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  69383. })(BABYLON || (BABYLON = {}));
  69384. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  69385. var BABYLON;
  69386. (function (BABYLON) {
  69387. var serializedGeometries = [];
  69388. var serializeGeometry = function (geometry, serializationGeometries) {
  69389. if (serializedGeometries[geometry.id]) {
  69390. return;
  69391. }
  69392. if (geometry.doNotSerialize) {
  69393. return;
  69394. }
  69395. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  69396. serializationGeometries.boxes.push(geometry.serialize());
  69397. }
  69398. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  69399. serializationGeometries.spheres.push(geometry.serialize());
  69400. }
  69401. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  69402. serializationGeometries.cylinders.push(geometry.serialize());
  69403. }
  69404. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  69405. serializationGeometries.toruses.push(geometry.serialize());
  69406. }
  69407. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  69408. serializationGeometries.grounds.push(geometry.serialize());
  69409. }
  69410. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  69411. serializationGeometries.planes.push(geometry.serialize());
  69412. }
  69413. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  69414. serializationGeometries.torusKnots.push(geometry.serialize());
  69415. }
  69416. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  69417. throw new Error("Unknown primitive type");
  69418. }
  69419. else {
  69420. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  69421. }
  69422. serializedGeometries[geometry.id] = true;
  69423. };
  69424. var serializeMesh = function (mesh, serializationScene) {
  69425. var serializationObject = {};
  69426. // Geometry
  69427. var geometry = mesh._geometry;
  69428. if (geometry) {
  69429. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  69430. // 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
  69431. serializeGeometry(geometry, serializationScene.geometries);
  69432. }
  69433. }
  69434. // Custom
  69435. if (mesh.serialize) {
  69436. mesh.serialize(serializationObject);
  69437. }
  69438. return serializationObject;
  69439. };
  69440. var finalizeSingleMesh = function (mesh, serializationObject) {
  69441. //only works if the mesh is already loaded
  69442. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  69443. //serialize material
  69444. if (mesh.material) {
  69445. if (mesh.material instanceof BABYLON.StandardMaterial) {
  69446. serializationObject.materials = serializationObject.materials || [];
  69447. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  69448. serializationObject.materials.push(mesh.material.serialize());
  69449. }
  69450. }
  69451. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  69452. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  69453. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  69454. serializationObject.multiMaterials.push(mesh.material.serialize());
  69455. }
  69456. }
  69457. }
  69458. //serialize geometry
  69459. var geometry = mesh._geometry;
  69460. if (geometry) {
  69461. if (!serializationObject.geometries) {
  69462. serializationObject.geometries = {};
  69463. serializationObject.geometries.boxes = [];
  69464. serializationObject.geometries.spheres = [];
  69465. serializationObject.geometries.cylinders = [];
  69466. serializationObject.geometries.toruses = [];
  69467. serializationObject.geometries.grounds = [];
  69468. serializationObject.geometries.planes = [];
  69469. serializationObject.geometries.torusKnots = [];
  69470. serializationObject.geometries.vertexData = [];
  69471. }
  69472. serializeGeometry(geometry, serializationObject.geometries);
  69473. }
  69474. // Skeletons
  69475. if (mesh.skeleton) {
  69476. serializationObject.skeletons = serializationObject.skeletons || [];
  69477. serializationObject.skeletons.push(mesh.skeleton.serialize());
  69478. }
  69479. //serialize the actual mesh
  69480. serializationObject.meshes = serializationObject.meshes || [];
  69481. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  69482. }
  69483. };
  69484. var SceneSerializer = (function () {
  69485. function SceneSerializer() {
  69486. }
  69487. SceneSerializer.ClearCache = function () {
  69488. serializedGeometries = [];
  69489. };
  69490. SceneSerializer.Serialize = function (scene) {
  69491. var serializationObject = {};
  69492. SceneSerializer.ClearCache();
  69493. // Scene
  69494. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  69495. serializationObject.autoClear = scene.autoClear;
  69496. serializationObject.clearColor = scene.clearColor.asArray();
  69497. serializationObject.ambientColor = scene.ambientColor.asArray();
  69498. serializationObject.gravity = scene.gravity.asArray();
  69499. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  69500. serializationObject.workerCollisions = scene.workerCollisions;
  69501. // Fog
  69502. if (scene.fogMode && scene.fogMode !== 0) {
  69503. serializationObject.fogMode = scene.fogMode;
  69504. serializationObject.fogColor = scene.fogColor.asArray();
  69505. serializationObject.fogStart = scene.fogStart;
  69506. serializationObject.fogEnd = scene.fogEnd;
  69507. serializationObject.fogDensity = scene.fogDensity;
  69508. }
  69509. //Physics
  69510. if (scene.isPhysicsEnabled()) {
  69511. serializationObject.physicsEnabled = true;
  69512. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  69513. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  69514. }
  69515. // Metadata
  69516. if (scene.metadata) {
  69517. serializationObject.metadata = scene.metadata;
  69518. }
  69519. // Morph targets
  69520. serializationObject.morphTargetManagers = [];
  69521. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  69522. var abstractMesh = _a[_i];
  69523. var manager = abstractMesh.morphTargetManager;
  69524. if (manager) {
  69525. serializationObject.morphTargetManagers.push(manager.serialize());
  69526. }
  69527. }
  69528. // Lights
  69529. serializationObject.lights = [];
  69530. var index;
  69531. var light;
  69532. for (index = 0; index < scene.lights.length; index++) {
  69533. light = scene.lights[index];
  69534. if (!light.doNotSerialize) {
  69535. serializationObject.lights.push(light.serialize());
  69536. }
  69537. }
  69538. // Cameras
  69539. serializationObject.cameras = [];
  69540. for (index = 0; index < scene.cameras.length; index++) {
  69541. var camera = scene.cameras[index];
  69542. if (!camera.doNotSerialize) {
  69543. serializationObject.cameras.push(camera.serialize());
  69544. }
  69545. }
  69546. if (scene.activeCamera) {
  69547. serializationObject.activeCameraID = scene.activeCamera.id;
  69548. }
  69549. // Animations
  69550. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  69551. // Materials
  69552. serializationObject.materials = [];
  69553. serializationObject.multiMaterials = [];
  69554. var material;
  69555. for (index = 0; index < scene.materials.length; index++) {
  69556. material = scene.materials[index];
  69557. if (!material.doNotSerialize) {
  69558. serializationObject.materials.push(material.serialize());
  69559. }
  69560. }
  69561. // MultiMaterials
  69562. serializationObject.multiMaterials = [];
  69563. for (index = 0; index < scene.multiMaterials.length; index++) {
  69564. var multiMaterial = scene.multiMaterials[index];
  69565. serializationObject.multiMaterials.push(multiMaterial.serialize());
  69566. }
  69567. // Skeletons
  69568. serializationObject.skeletons = [];
  69569. for (index = 0; index < scene.skeletons.length; index++) {
  69570. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  69571. }
  69572. // Geometries
  69573. serializationObject.geometries = {};
  69574. serializationObject.geometries.boxes = [];
  69575. serializationObject.geometries.spheres = [];
  69576. serializationObject.geometries.cylinders = [];
  69577. serializationObject.geometries.toruses = [];
  69578. serializationObject.geometries.grounds = [];
  69579. serializationObject.geometries.planes = [];
  69580. serializationObject.geometries.torusKnots = [];
  69581. serializationObject.geometries.vertexData = [];
  69582. serializedGeometries = [];
  69583. var geometries = scene.getGeometries();
  69584. for (index = 0; index < geometries.length; index++) {
  69585. var geometry = geometries[index];
  69586. if (geometry.isReady()) {
  69587. serializeGeometry(geometry, serializationObject.geometries);
  69588. }
  69589. }
  69590. // Meshes
  69591. serializationObject.meshes = [];
  69592. for (index = 0; index < scene.meshes.length; index++) {
  69593. var abstractMesh = scene.meshes[index];
  69594. if (abstractMesh instanceof BABYLON.Mesh) {
  69595. var mesh = abstractMesh;
  69596. if (!mesh.doNotSerialize) {
  69597. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  69598. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  69599. }
  69600. }
  69601. }
  69602. }
  69603. // Particles Systems
  69604. serializationObject.particleSystems = [];
  69605. for (index = 0; index < scene.particleSystems.length; index++) {
  69606. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  69607. }
  69608. // Lens flares
  69609. serializationObject.lensFlareSystems = [];
  69610. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  69611. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  69612. }
  69613. // Shadows
  69614. serializationObject.shadowGenerators = [];
  69615. for (index = 0; index < scene.lights.length; index++) {
  69616. light = scene.lights[index];
  69617. var shadowGenerator = light.getShadowGenerator();
  69618. if (shadowGenerator) {
  69619. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  69620. }
  69621. }
  69622. // Action Manager
  69623. if (scene.actionManager) {
  69624. serializationObject.actions = scene.actionManager.serialize("scene");
  69625. }
  69626. // Audio
  69627. serializationObject.sounds = [];
  69628. for (index = 0; index < scene.soundTracks.length; index++) {
  69629. var soundtrack = scene.soundTracks[index];
  69630. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  69631. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  69632. }
  69633. }
  69634. return serializationObject;
  69635. };
  69636. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  69637. if (withParents === void 0) { withParents = false; }
  69638. if (withChildren === void 0) { withChildren = false; }
  69639. var serializationObject = {};
  69640. SceneSerializer.ClearCache();
  69641. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  69642. if (withParents || withChildren) {
  69643. //deliberate for loop! not for each, appended should be processed as well.
  69644. for (var i = 0; i < toSerialize.length; ++i) {
  69645. if (withChildren) {
  69646. toSerialize[i].getDescendants().forEach(function (node) {
  69647. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  69648. toSerialize.push(node);
  69649. }
  69650. });
  69651. }
  69652. //make sure the array doesn't contain the object already
  69653. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  69654. toSerialize.push(toSerialize[i].parent);
  69655. }
  69656. }
  69657. }
  69658. toSerialize.forEach(function (mesh) {
  69659. finalizeSingleMesh(mesh, serializationObject);
  69660. });
  69661. return serializationObject;
  69662. };
  69663. return SceneSerializer;
  69664. }());
  69665. BABYLON.SceneSerializer = SceneSerializer;
  69666. })(BABYLON || (BABYLON = {}));
  69667. //# sourceMappingURL=babylon.sceneSerializer.js.map
  69668. var BABYLON;
  69669. (function (BABYLON) {
  69670. var ReflectionProbe = (function () {
  69671. function ReflectionProbe(name, size, scene, generateMipMaps) {
  69672. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69673. var _this = this;
  69674. this.name = name;
  69675. this._viewMatrix = BABYLON.Matrix.Identity();
  69676. this._target = BABYLON.Vector3.Zero();
  69677. this._add = BABYLON.Vector3.Zero();
  69678. this.invertYAxis = false;
  69679. this.position = BABYLON.Vector3.Zero();
  69680. this._scene = scene;
  69681. this._scene.reflectionProbes.push(this);
  69682. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  69683. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  69684. switch (faceIndex) {
  69685. case 0:
  69686. _this._add.copyFromFloats(1, 0, 0);
  69687. break;
  69688. case 1:
  69689. _this._add.copyFromFloats(-1, 0, 0);
  69690. break;
  69691. case 2:
  69692. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  69693. break;
  69694. case 3:
  69695. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  69696. break;
  69697. case 4:
  69698. _this._add.copyFromFloats(0, 0, 1);
  69699. break;
  69700. case 5:
  69701. _this._add.copyFromFloats(0, 0, -1);
  69702. break;
  69703. }
  69704. if (_this._attachedMesh) {
  69705. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  69706. }
  69707. _this.position.addToRef(_this._add, _this._target);
  69708. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  69709. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  69710. });
  69711. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  69712. scene.updateTransformMatrix(true);
  69713. });
  69714. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  69715. }
  69716. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  69717. get: function () {
  69718. return this._renderTargetTexture.samples;
  69719. },
  69720. set: function (value) {
  69721. this._renderTargetTexture.samples = value;
  69722. },
  69723. enumerable: true,
  69724. configurable: true
  69725. });
  69726. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  69727. get: function () {
  69728. return this._renderTargetTexture.refreshRate;
  69729. },
  69730. set: function (value) {
  69731. this._renderTargetTexture.refreshRate = value;
  69732. },
  69733. enumerable: true,
  69734. configurable: true
  69735. });
  69736. ReflectionProbe.prototype.getScene = function () {
  69737. return this._scene;
  69738. };
  69739. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  69740. get: function () {
  69741. return this._renderTargetTexture;
  69742. },
  69743. enumerable: true,
  69744. configurable: true
  69745. });
  69746. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  69747. get: function () {
  69748. return this._renderTargetTexture.renderList;
  69749. },
  69750. enumerable: true,
  69751. configurable: true
  69752. });
  69753. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  69754. this._attachedMesh = mesh;
  69755. };
  69756. /**
  69757. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  69758. *
  69759. * @param renderingGroupId The rendering group id corresponding to its index
  69760. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  69761. */
  69762. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  69763. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  69764. };
  69765. ReflectionProbe.prototype.dispose = function () {
  69766. var index = this._scene.reflectionProbes.indexOf(this);
  69767. if (index !== -1) {
  69768. // Remove from the scene if found
  69769. this._scene.reflectionProbes.splice(index, 1);
  69770. }
  69771. if (this._renderTargetTexture) {
  69772. this._renderTargetTexture.dispose();
  69773. this._renderTargetTexture = null;
  69774. }
  69775. };
  69776. return ReflectionProbe;
  69777. }());
  69778. BABYLON.ReflectionProbe = ReflectionProbe;
  69779. })(BABYLON || (BABYLON = {}));
  69780. //# sourceMappingURL=babylon.reflectionProbe.js.map
  69781. var BABYLON;
  69782. (function (BABYLON) {
  69783. var Layer = (function () {
  69784. function Layer(name, imgUrl, scene, isBackground, color) {
  69785. this.name = name;
  69786. this.scale = new BABYLON.Vector2(1, 1);
  69787. this.offset = new BABYLON.Vector2(0, 0);
  69788. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  69789. this.layerMask = 0x0FFFFFFF;
  69790. this._vertexBuffers = {};
  69791. // Events
  69792. /**
  69793. * An event triggered when the layer is disposed.
  69794. * @type {BABYLON.Observable}
  69795. */
  69796. this.onDisposeObservable = new BABYLON.Observable();
  69797. /**
  69798. * An event triggered before rendering the scene
  69799. * @type {BABYLON.Observable}
  69800. */
  69801. this.onBeforeRenderObservable = new BABYLON.Observable();
  69802. /**
  69803. * An event triggered after rendering the scene
  69804. * @type {BABYLON.Observable}
  69805. */
  69806. this.onAfterRenderObservable = new BABYLON.Observable();
  69807. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  69808. this.isBackground = isBackground === undefined ? true : isBackground;
  69809. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  69810. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  69811. this._scene.layers.push(this);
  69812. var engine = this._scene.getEngine();
  69813. // VBO
  69814. var vertices = [];
  69815. vertices.push(1, 1);
  69816. vertices.push(-1, 1);
  69817. vertices.push(-1, -1);
  69818. vertices.push(1, -1);
  69819. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69820. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  69821. this._createIndexBuffer();
  69822. // Effects
  69823. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  69824. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  69825. }
  69826. Object.defineProperty(Layer.prototype, "onDispose", {
  69827. set: function (callback) {
  69828. if (this._onDisposeObserver) {
  69829. this.onDisposeObservable.remove(this._onDisposeObserver);
  69830. }
  69831. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  69832. },
  69833. enumerable: true,
  69834. configurable: true
  69835. });
  69836. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  69837. set: function (callback) {
  69838. if (this._onBeforeRenderObserver) {
  69839. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  69840. }
  69841. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  69842. },
  69843. enumerable: true,
  69844. configurable: true
  69845. });
  69846. Object.defineProperty(Layer.prototype, "onAfterRender", {
  69847. set: function (callback) {
  69848. if (this._onAfterRenderObserver) {
  69849. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  69850. }
  69851. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  69852. },
  69853. enumerable: true,
  69854. configurable: true
  69855. });
  69856. Layer.prototype._createIndexBuffer = function () {
  69857. var engine = this._scene.getEngine();
  69858. // Indices
  69859. var indices = [];
  69860. indices.push(0);
  69861. indices.push(1);
  69862. indices.push(2);
  69863. indices.push(0);
  69864. indices.push(2);
  69865. indices.push(3);
  69866. this._indexBuffer = engine.createIndexBuffer(indices);
  69867. };
  69868. Layer.prototype._rebuild = function () {
  69869. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  69870. this._createIndexBuffer();
  69871. };
  69872. Layer.prototype.render = function () {
  69873. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  69874. // Check
  69875. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  69876. return;
  69877. var engine = this._scene.getEngine();
  69878. this.onBeforeRenderObservable.notifyObservers(this);
  69879. // Render
  69880. engine.enableEffect(currentEffect);
  69881. engine.setState(false);
  69882. // Texture
  69883. currentEffect.setTexture("textureSampler", this.texture);
  69884. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  69885. // Color
  69886. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  69887. // Scale / offset
  69888. currentEffect.setVector2("offset", this.offset);
  69889. currentEffect.setVector2("scale", this.scale);
  69890. // VBOs
  69891. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  69892. // Draw order
  69893. if (!this.alphaTest) {
  69894. engine.setAlphaMode(this.alphaBlendingMode);
  69895. engine.draw(true, 0, 6);
  69896. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  69897. }
  69898. else {
  69899. engine.draw(true, 0, 6);
  69900. }
  69901. this.onAfterRenderObservable.notifyObservers(this);
  69902. };
  69903. Layer.prototype.dispose = function () {
  69904. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69905. if (vertexBuffer) {
  69906. vertexBuffer.dispose();
  69907. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69908. }
  69909. if (this._indexBuffer) {
  69910. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  69911. this._indexBuffer = null;
  69912. }
  69913. if (this.texture) {
  69914. this.texture.dispose();
  69915. this.texture = null;
  69916. }
  69917. // Remove from scene
  69918. var index = this._scene.layers.indexOf(this);
  69919. this._scene.layers.splice(index, 1);
  69920. // Callback
  69921. this.onDisposeObservable.notifyObservers(this);
  69922. this.onDisposeObservable.clear();
  69923. this.onAfterRenderObservable.clear();
  69924. this.onBeforeRenderObservable.clear();
  69925. };
  69926. return Layer;
  69927. }());
  69928. BABYLON.Layer = Layer;
  69929. })(BABYLON || (BABYLON = {}));
  69930. //# sourceMappingURL=babylon.layer.js.map
  69931. var BABYLON;
  69932. (function (BABYLON) {
  69933. var TextureTools = (function () {
  69934. function TextureTools() {
  69935. }
  69936. /**
  69937. * Uses the GPU to create a copy texture rescaled at a given size
  69938. * @param texture Texture to copy from
  69939. * @param width Desired width
  69940. * @param height Desired height
  69941. * @return Generated texture
  69942. */
  69943. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  69944. if (useBilinearMode === void 0) { useBilinearMode = true; }
  69945. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  69946. var scene = texture.getScene();
  69947. var engine = scene.getEngine();
  69948. rtt.wrapU = texture.wrapU;
  69949. rtt.wrapV = texture.wrapV;
  69950. rtt.uOffset = texture.uOffset;
  69951. rtt.vOffset = texture.vOffset;
  69952. rtt.uScale = texture.uScale;
  69953. rtt.vScale = texture.vScale;
  69954. rtt.uAng = texture.uAng;
  69955. rtt.vAng = texture.vAng;
  69956. rtt.wAng = texture.wAng;
  69957. rtt.coordinatesIndex = texture.coordinatesIndex;
  69958. rtt.level = texture.level;
  69959. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  69960. rtt._texture.isReady = false;
  69961. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69962. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69963. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  69964. passPostProcess.getEffect().executeWhenCompiled(function () {
  69965. passPostProcess.onApply = function (effect) {
  69966. effect.setTexture("textureSampler", texture);
  69967. };
  69968. scene.postProcessManager.directRender([passPostProcess], rtt.getInternalTexture());
  69969. engine.unBindFramebuffer(rtt.getInternalTexture());
  69970. rtt.disposeFramebufferObjects();
  69971. passPostProcess.dispose();
  69972. rtt._texture.isReady = true;
  69973. });
  69974. return rtt;
  69975. };
  69976. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  69977. if (!scene._environmentBRDFTexture) {
  69978. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  69979. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69980. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69981. scene._environmentBRDFTexture = texture;
  69982. }
  69983. return scene._environmentBRDFTexture;
  69984. };
  69985. 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=";
  69986. return TextureTools;
  69987. }());
  69988. BABYLON.TextureTools = TextureTools;
  69989. })(BABYLON || (BABYLON = {}));
  69990. //# sourceMappingURL=babylon.textureTools.js.map
  69991. var BABYLON;
  69992. (function (BABYLON) {
  69993. var FramingBehavior = (function () {
  69994. function FramingBehavior() {
  69995. this._mode = FramingBehavior.FitFrustumSidesMode;
  69996. this._radiusScale = 1.0;
  69997. this._positionScale = 0.5;
  69998. this._defaultElevation = 0.3;
  69999. this._elevationReturnTime = 1500;
  70000. this._elevationReturnWaitTime = 1000;
  70001. this._zoomStopsAnimation = false;
  70002. this._framingTime = 1500;
  70003. this._isPointerDown = false;
  70004. this._lastFrameTime = null;
  70005. this._lastInteractionTime = -Infinity;
  70006. // Framing control
  70007. this._animatables = new Array();
  70008. this._betaIsAnimating = false;
  70009. this._lastFrameRadius = 0;
  70010. }
  70011. Object.defineProperty(FramingBehavior.prototype, "name", {
  70012. get: function () {
  70013. return "Framing";
  70014. },
  70015. enumerable: true,
  70016. configurable: true
  70017. });
  70018. Object.defineProperty(FramingBehavior.prototype, "mode", {
  70019. /**
  70020. * Gets current mode used by the behavior.
  70021. */
  70022. get: function () {
  70023. return this._mode;
  70024. },
  70025. /**
  70026. * Sets the current mode used by the behavior
  70027. */
  70028. set: function (mode) {
  70029. this._mode = mode;
  70030. },
  70031. enumerable: true,
  70032. configurable: true
  70033. });
  70034. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  70035. /**
  70036. * Gets the scale applied to the radius
  70037. */
  70038. get: function () {
  70039. return this._radiusScale;
  70040. },
  70041. /**
  70042. * Sets the scale applied to the radius (1 by default)
  70043. */
  70044. set: function (radius) {
  70045. this._radiusScale = radius;
  70046. },
  70047. enumerable: true,
  70048. configurable: true
  70049. });
  70050. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  70051. /**
  70052. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  70053. */
  70054. get: function () {
  70055. return this._positionScale;
  70056. },
  70057. /**
  70058. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  70059. */
  70060. set: function (scale) {
  70061. this._positionScale = scale;
  70062. },
  70063. enumerable: true,
  70064. configurable: true
  70065. });
  70066. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  70067. /**
  70068. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  70069. * behaviour is triggered, in radians.
  70070. */
  70071. get: function () {
  70072. return this._defaultElevation;
  70073. },
  70074. /**
  70075. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  70076. * behaviour is triggered, in radians.
  70077. */
  70078. set: function (elevation) {
  70079. this._defaultElevation = elevation;
  70080. },
  70081. enumerable: true,
  70082. configurable: true
  70083. });
  70084. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  70085. /**
  70086. * Gets the time (in milliseconds) taken to return to the default beta position.
  70087. * Negative value indicates camera should not return to default.
  70088. */
  70089. get: function () {
  70090. return this._elevationReturnTime;
  70091. },
  70092. /**
  70093. * Sets the time (in milliseconds) taken to return to the default beta position.
  70094. * Negative value indicates camera should not return to default.
  70095. */
  70096. set: function (speed) {
  70097. this._elevationReturnTime = speed;
  70098. },
  70099. enumerable: true,
  70100. configurable: true
  70101. });
  70102. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  70103. /**
  70104. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  70105. */
  70106. get: function () {
  70107. return this._elevationReturnWaitTime;
  70108. },
  70109. /**
  70110. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  70111. */
  70112. set: function (time) {
  70113. this._elevationReturnWaitTime = time;
  70114. },
  70115. enumerable: true,
  70116. configurable: true
  70117. });
  70118. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  70119. /**
  70120. * Gets the flag that indicates if user zooming should stop animation.
  70121. */
  70122. get: function () {
  70123. return this._zoomStopsAnimation;
  70124. },
  70125. /**
  70126. * Sets the flag that indicates if user zooming should stop animation.
  70127. */
  70128. set: function (flag) {
  70129. this._zoomStopsAnimation = flag;
  70130. },
  70131. enumerable: true,
  70132. configurable: true
  70133. });
  70134. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  70135. /**
  70136. * Gets the transition time when framing the mesh, in milliseconds
  70137. */
  70138. get: function () {
  70139. return this._framingTime;
  70140. },
  70141. /**
  70142. * Sets the transition time when framing the mesh, in milliseconds
  70143. */
  70144. set: function (time) {
  70145. this._framingTime = time;
  70146. },
  70147. enumerable: true,
  70148. configurable: true
  70149. });
  70150. FramingBehavior.prototype.attach = function (camera) {
  70151. var _this = this;
  70152. this._attachedCamera = camera;
  70153. var scene = this._attachedCamera.getScene();
  70154. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  70155. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  70156. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  70157. _this._isPointerDown = true;
  70158. return;
  70159. }
  70160. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  70161. _this._isPointerDown = false;
  70162. }
  70163. });
  70164. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  70165. if (mesh) {
  70166. _this.zoomOnMesh(mesh);
  70167. }
  70168. });
  70169. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  70170. // Stop the animation if there is user interaction and the animation should stop for this interaction
  70171. _this._applyUserInteraction();
  70172. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  70173. // back to the default position after a given timeout
  70174. _this._maintainCameraAboveGround();
  70175. });
  70176. };
  70177. FramingBehavior.prototype.detach = function () {
  70178. var scene = this._attachedCamera.getScene();
  70179. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  70180. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  70181. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  70182. this._attachedCamera = null;
  70183. };
  70184. /**
  70185. * Targets the given mesh and updates zoom level accordingly.
  70186. * @param mesh The mesh to target.
  70187. * @param radius Optional. If a cached radius position already exists, overrides default.
  70188. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  70189. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  70190. */
  70191. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ) {
  70192. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  70193. mesh.computeWorldMatrix(true);
  70194. var boundingBox = mesh.getBoundingInfo().boundingBox;
  70195. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ);
  70196. };
  70197. /**
  70198. * Targets the given mesh and updates zoom level accordingly.
  70199. * @param mesh The mesh to target.
  70200. * @param radius Optional. If a cached radius position already exists, overrides default.
  70201. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  70202. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  70203. */
  70204. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ) {
  70205. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  70206. var zoomTarget;
  70207. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  70208. var bottom = minimumWorld.y;
  70209. var top = maximumWorld.y;
  70210. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  70211. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  70212. if (focusOnOriginXZ) {
  70213. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  70214. }
  70215. else {
  70216. var centerWorld = minimumWorld.add(radiusWorld);
  70217. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  70218. }
  70219. if (!this._vectorTransition) {
  70220. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  70221. }
  70222. this._betaIsAnimating = true;
  70223. this._animatables.push(BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime));
  70224. // sets the radius and lower radius bounds
  70225. // Small delta ensures camera is not always at lower zoom limit.
  70226. var delta = 0.1;
  70227. var radius = 0;
  70228. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  70229. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  70230. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  70231. radius = position;
  70232. }
  70233. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  70234. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  70235. if (this._attachedCamera.lowerRadiusLimit === null) {
  70236. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  70237. }
  70238. }
  70239. // transition to new radius
  70240. if (!this._radiusTransition) {
  70241. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  70242. }
  70243. this._animatables.push(BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime));
  70244. };
  70245. /**
  70246. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  70247. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  70248. * frustum width.
  70249. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  70250. * to fully enclose the mesh in the viewing frustum.
  70251. */
  70252. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  70253. var size = maximumWorld.subtract(minimumWorld);
  70254. var boxVectorGlobalDiagonal = size.length();
  70255. var frustumSlope = this._getFrustumSlope();
  70256. // Formula for setting distance
  70257. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  70258. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  70259. // Horizon distance
  70260. var radius = radiusWithoutFraming * this._radiusScale;
  70261. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  70262. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  70263. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  70264. var camera = this._attachedCamera;
  70265. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  70266. // Don't exceed the requested limit
  70267. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  70268. }
  70269. // Don't exceed the upper radius limit
  70270. if (camera.upperRadiusLimit) {
  70271. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  70272. }
  70273. return distance;
  70274. };
  70275. /**
  70276. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  70277. * is automatically returned to its default position (expected to be above ground plane).
  70278. */
  70279. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  70280. var _this = this;
  70281. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  70282. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  70283. var limitBeta = Math.PI * 0.5;
  70284. // Bring the camera back up if below the ground plane
  70285. if (!this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  70286. this._betaIsAnimating = true;
  70287. //Transition to new position
  70288. this.stopAllAnimations();
  70289. if (!this._betaTransition) {
  70290. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  70291. }
  70292. this._animatables.push(BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  70293. _this._clearAnimationLocks();
  70294. _this.stopAllAnimations();
  70295. }));
  70296. }
  70297. };
  70298. /**
  70299. * Returns the frustum slope based on the canvas ratio and camera FOV
  70300. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  70301. */
  70302. FramingBehavior.prototype._getFrustumSlope = function () {
  70303. // Calculate the viewport ratio
  70304. // Aspect Ratio is Height/Width.
  70305. var camera = this._attachedCamera;
  70306. var engine = camera.getScene().getEngine();
  70307. var aspectRatio = engine.getAspectRatio(camera);
  70308. // Camera FOV is the vertical field of view (top-bottom) in radians.
  70309. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  70310. var frustumSlopeY = Math.tan(camera.fov / 2);
  70311. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  70312. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  70313. // along the forward vector.
  70314. var frustumSlopeX = frustumSlopeY * aspectRatio;
  70315. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  70316. };
  70317. /**
  70318. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  70319. */
  70320. FramingBehavior.prototype._clearAnimationLocks = function () {
  70321. this._betaIsAnimating = false;
  70322. };
  70323. /**
  70324. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  70325. */
  70326. FramingBehavior.prototype._applyUserInteraction = function () {
  70327. if (this.isUserIsMoving) {
  70328. this._lastInteractionTime = BABYLON.Tools.Now;
  70329. this.stopAllAnimations();
  70330. this._clearAnimationLocks();
  70331. }
  70332. };
  70333. /**
  70334. * Stops and removes all animations that have been applied to the camera
  70335. */
  70336. FramingBehavior.prototype.stopAllAnimations = function () {
  70337. this._attachedCamera.animations = [];
  70338. while (this._animatables.length) {
  70339. if (this._animatables[0]) {
  70340. this._animatables[0].onAnimationEnd = null;
  70341. this._animatables[0].stop();
  70342. }
  70343. this._animatables.shift();
  70344. }
  70345. };
  70346. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  70347. /**
  70348. * Gets a value indicating if the user is moving the camera
  70349. */
  70350. get: function () {
  70351. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  70352. this._attachedCamera.inertialBetaOffset !== 0 ||
  70353. this._attachedCamera.inertialRadiusOffset !== 0 ||
  70354. this._attachedCamera.inertialPanningX !== 0 ||
  70355. this._attachedCamera.inertialPanningY !== 0 ||
  70356. this._isPointerDown;
  70357. },
  70358. enumerable: true,
  70359. configurable: true
  70360. });
  70361. /**
  70362. * The easing function used by animations
  70363. */
  70364. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  70365. /**
  70366. * The easing mode used by animations
  70367. */
  70368. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  70369. // Statics
  70370. /**
  70371. * The camera can move all the way towards the mesh.
  70372. */
  70373. FramingBehavior.IgnoreBoundsSizeMode = 0;
  70374. /**
  70375. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  70376. */
  70377. FramingBehavior.FitFrustumSidesMode = 1;
  70378. return FramingBehavior;
  70379. }());
  70380. BABYLON.FramingBehavior = FramingBehavior;
  70381. })(BABYLON || (BABYLON = {}));
  70382. //# sourceMappingURL=babylon.framingBehavior.js.map
  70383. var BABYLON;
  70384. (function (BABYLON) {
  70385. /**
  70386. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  70387. */
  70388. var BouncingBehavior = (function () {
  70389. function BouncingBehavior() {
  70390. /**
  70391. * The duration of the animation, in milliseconds
  70392. */
  70393. this.transitionDuration = 450;
  70394. /**
  70395. * Length of the distance animated by the transition when lower radius is reached
  70396. */
  70397. this.lowerRadiusTransitionRange = 2;
  70398. /**
  70399. * Length of the distance animated by the transition when upper radius is reached
  70400. */
  70401. this.upperRadiusTransitionRange = -2;
  70402. this._autoTransitionRange = false;
  70403. // Animations
  70404. this._radiusIsAnimating = false;
  70405. this._radiusBounceTransition = null;
  70406. this._animatables = new Array();
  70407. }
  70408. Object.defineProperty(BouncingBehavior.prototype, "name", {
  70409. get: function () {
  70410. return "Bouncing";
  70411. },
  70412. enumerable: true,
  70413. configurable: true
  70414. });
  70415. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  70416. /**
  70417. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  70418. */
  70419. get: function () {
  70420. return this._autoTransitionRange;
  70421. },
  70422. /**
  70423. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  70424. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  70425. */
  70426. set: function (value) {
  70427. var _this = this;
  70428. if (this._autoTransitionRange === value) {
  70429. return;
  70430. }
  70431. this._autoTransitionRange = value;
  70432. var camera = this._attachedCamera;
  70433. if (value) {
  70434. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  70435. if (!mesh) {
  70436. return;
  70437. }
  70438. mesh.computeWorldMatrix(true);
  70439. var diagonal = mesh.getBoundingInfo().diagonalLength;
  70440. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  70441. _this.upperRadiusTransitionRange = diagonal * 0.05;
  70442. });
  70443. }
  70444. else if (this._onMeshTargetChangedObserver) {
  70445. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  70446. }
  70447. },
  70448. enumerable: true,
  70449. configurable: true
  70450. });
  70451. BouncingBehavior.prototype.attach = function (camera) {
  70452. var _this = this;
  70453. this._attachedCamera = camera;
  70454. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  70455. // Add the bounce animation to the lower radius limit
  70456. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  70457. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  70458. }
  70459. // Add the bounce animation to the upper radius limit
  70460. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  70461. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  70462. }
  70463. });
  70464. };
  70465. BouncingBehavior.prototype.detach = function () {
  70466. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  70467. if (this._onMeshTargetChangedObserver) {
  70468. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  70469. }
  70470. this._attachedCamera = null;
  70471. };
  70472. /**
  70473. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  70474. * @param radiusLimit The limit to check against.
  70475. * @return Bool to indicate if at limit.
  70476. */
  70477. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  70478. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  70479. return true;
  70480. }
  70481. return false;
  70482. };
  70483. /**
  70484. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  70485. * @param radiusDelta The delta by which to animate to. Can be negative.
  70486. */
  70487. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  70488. var _this = this;
  70489. if (!this._radiusBounceTransition) {
  70490. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  70491. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  70492. }
  70493. // Prevent zoom until bounce has completed
  70494. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  70495. this._attachedCamera.wheelPrecision = Infinity;
  70496. this._attachedCamera.inertialRadiusOffset = 0;
  70497. // Animate to the radius limit
  70498. this.stopAllAnimations();
  70499. this._radiusIsAnimating = true;
  70500. this._animatables.push(BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); }));
  70501. };
  70502. /**
  70503. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  70504. */
  70505. BouncingBehavior.prototype._clearAnimationLocks = function () {
  70506. this._radiusIsAnimating = false;
  70507. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  70508. };
  70509. /**
  70510. * Stops and removes all animations that have been applied to the camera
  70511. */
  70512. BouncingBehavior.prototype.stopAllAnimations = function () {
  70513. this._attachedCamera.animations = [];
  70514. while (this._animatables.length) {
  70515. this._animatables[0].onAnimationEnd = null;
  70516. this._animatables[0].stop();
  70517. this._animatables.shift();
  70518. }
  70519. };
  70520. /**
  70521. * The easing function used by animations
  70522. */
  70523. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  70524. /**
  70525. * The easing mode used by animations
  70526. */
  70527. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  70528. return BouncingBehavior;
  70529. }());
  70530. BABYLON.BouncingBehavior = BouncingBehavior;
  70531. })(BABYLON || (BABYLON = {}));
  70532. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  70533. var BABYLON;
  70534. (function (BABYLON) {
  70535. var AutoRotationBehavior = (function () {
  70536. function AutoRotationBehavior() {
  70537. this._zoomStopsAnimation = false;
  70538. this._idleRotationSpeed = 0.05;
  70539. this._idleRotationWaitTime = 2000;
  70540. this._idleRotationSpinupTime = 2000;
  70541. this._isPointerDown = false;
  70542. this._lastFrameTime = null;
  70543. this._lastInteractionTime = -Infinity;
  70544. this._cameraRotationSpeed = 0;
  70545. this._lastFrameRadius = 0;
  70546. }
  70547. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  70548. get: function () {
  70549. return "AutoRotation";
  70550. },
  70551. enumerable: true,
  70552. configurable: true
  70553. });
  70554. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  70555. /**
  70556. * Gets the flag that indicates if user zooming should stop animation.
  70557. */
  70558. get: function () {
  70559. return this._zoomStopsAnimation;
  70560. },
  70561. /**
  70562. * Sets the flag that indicates if user zooming should stop animation.
  70563. */
  70564. set: function (flag) {
  70565. this._zoomStopsAnimation = flag;
  70566. },
  70567. enumerable: true,
  70568. configurable: true
  70569. });
  70570. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  70571. /**
  70572. * Gets the default speed at which the camera rotates around the model.
  70573. */
  70574. get: function () {
  70575. return this._idleRotationSpeed;
  70576. },
  70577. /**
  70578. * Sets the default speed at which the camera rotates around the model.
  70579. */
  70580. set: function (speed) {
  70581. this._idleRotationSpeed = speed;
  70582. },
  70583. enumerable: true,
  70584. configurable: true
  70585. });
  70586. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  70587. /**
  70588. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  70589. */
  70590. get: function () {
  70591. return this._idleRotationWaitTime;
  70592. },
  70593. /**
  70594. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  70595. */
  70596. set: function (time) {
  70597. this._idleRotationWaitTime = time;
  70598. },
  70599. enumerable: true,
  70600. configurable: true
  70601. });
  70602. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  70603. /**
  70604. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  70605. */
  70606. get: function () {
  70607. return this._idleRotationSpinupTime;
  70608. },
  70609. /**
  70610. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  70611. */
  70612. set: function (time) {
  70613. this._idleRotationSpinupTime = time;
  70614. },
  70615. enumerable: true,
  70616. configurable: true
  70617. });
  70618. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  70619. /**
  70620. * Gets a value indicating if the camera is currently rotating because of this behavior
  70621. */
  70622. get: function () {
  70623. return Math.abs(this._cameraRotationSpeed) > 0;
  70624. },
  70625. enumerable: true,
  70626. configurable: true
  70627. });
  70628. AutoRotationBehavior.prototype.attach = function (camera) {
  70629. var _this = this;
  70630. this._attachedCamera = camera;
  70631. var scene = this._attachedCamera.getScene();
  70632. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  70633. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  70634. _this._isPointerDown = true;
  70635. return;
  70636. }
  70637. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  70638. _this._isPointerDown = false;
  70639. }
  70640. });
  70641. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  70642. var now = BABYLON.Tools.Now;
  70643. var dt = 0;
  70644. if (_this._lastFrameTime != null) {
  70645. dt = now - _this._lastFrameTime;
  70646. }
  70647. _this._lastFrameTime = now;
  70648. // Stop the animation if there is user interaction and the animation should stop for this interaction
  70649. _this._applyUserInteraction();
  70650. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  70651. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  70652. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  70653. // Step camera rotation by rotation speed
  70654. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  70655. });
  70656. };
  70657. AutoRotationBehavior.prototype.detach = function () {
  70658. var scene = this._attachedCamera.getScene();
  70659. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  70660. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  70661. this._attachedCamera = null;
  70662. };
  70663. /**
  70664. * Returns true if user is scrolling.
  70665. * @return true if user is scrolling.
  70666. */
  70667. AutoRotationBehavior.prototype._userIsZooming = function () {
  70668. return this._attachedCamera.inertialRadiusOffset !== 0;
  70669. };
  70670. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  70671. var zoomHasHitLimit = false;
  70672. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  70673. zoomHasHitLimit = true;
  70674. }
  70675. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  70676. this._lastFrameRadius = this._attachedCamera.radius;
  70677. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  70678. };
  70679. /**
  70680. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  70681. */
  70682. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  70683. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  70684. this._lastInteractionTime = BABYLON.Tools.Now;
  70685. }
  70686. };
  70687. // Tools
  70688. AutoRotationBehavior.prototype._userIsMoving = function () {
  70689. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  70690. this._attachedCamera.inertialBetaOffset !== 0 ||
  70691. this._attachedCamera.inertialRadiusOffset !== 0 ||
  70692. this._attachedCamera.inertialPanningX !== 0 ||
  70693. this._attachedCamera.inertialPanningY !== 0 ||
  70694. this._isPointerDown;
  70695. };
  70696. return AutoRotationBehavior;
  70697. }());
  70698. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  70699. })(BABYLON || (BABYLON = {}));
  70700. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  70701. 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}"};
  70702. 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};"};
  70703. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  70704. module.exports = BABYLON;
  70705. };